我正在使用draft.js,我想知道我如何拥有编辑器,而当有人键入结果时,结果将显示为html,但带有实际的标记(即,如果我做粗体,输出显示为粗体)。
我无法使它正常工作。我尝试了dangerouslySetInnerHTML
,但似乎没有用。
<div dangerouslySetInnerHTML={{ __html: this.state.editorContentHtml }}></div>
import React from "react";
import { Editor, EditorState } from "draft-js";
import { stateToHTML } from "draft-js-export-html";
class ExampleEditor1 extends React.Component {
constructor(props) {
super(props);
this.state = { editorState: EditorState.createEmpty() };
this.onChange = editorState => {
this.setState({
editorState,
editorContentHtml: stateToHTML(editorState.getCurrentContent())
});
};
}
render() {
return (
<div>
<div className="editor-container" style={{ border: "1px solid #000" }}>
<Editor
editorState={this.state.editorState}
onChange={this.onChange}
/>
</div>
<h4>Editor content as HTML</h4>
<div>{this.state.editorContentHtml}</div>
</div>
);
}
}
export default ExampleEditor1;
答案 0 :(得分:0)
我还没有使用draft-js-export-html
软件包,而且我很懒。因此,我没有指出您的代码无法正常工作的原因。
但是以下代码可以完成任务:
import React, { Component } from 'react';
import { Editor, EditorState } from 'draft-js';
const styles = {
editor: {
border: "1px solid gray",
display: "block",
minHeight: "15em"
}
};
class App extends Component {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createEmpty(),
preview: null
};
this.onChange = editorState => this.setState({
editorState,
preview: editorState.getCurrentContent().getPlainText()
});
this.setEditor = ref => {
this.editor = ref;
};
this.focusEditor = () => {
if (this.editor) {
this.editor.focus();
}
};
}
render() {
return (
<React.Fragment>
<div style={styles.editor} onClick={this.focusEditor}>
<Editor
ref={this.setEditor}
editorState={this.state.editorState}
onChange={this.onChange}
/>
</div>
<div
style={{ minHeight: "200px" }}
dangerouslySetInnerHTML={{ __html: this.state.preview }}
/>
</React.Fragment>
);
}
}
export default App;