我正在尝试将文本从调用组件更新到编辑器组件。我使用道具从调用者传递文本,但是当文本更改(道具在 ContentEditor 中更新)时,编辑器组件中的文本不是:
下面是调用组件的代码:
<ControlledEditor htmlContent={this.state.validationResultContent}/>
这是受控编辑器的代码:
export class ControlledEditor extends Component {
constructor(props) {
super(props);
this.state = {editorState: EditorState.createWithText(this.props.htmlContent)};
}
onEditorStateChange = (editorState) => {
this.setState({ editorState })
};
render() {
const { editorState } = this.state;
return (
<>
<Container className="mt-5">
<Row>
<Editor
editorState= {editorState}
onEditorStateChange={this.onEditorStateChange}
wrapperClassName="demo-wrapper"
editorClassName="demo-editor"
/>
</Row>
</Container>
</>
);
}
}
ControlledEditor.propTypes = {
htmlContent: PropTypes.string
}
谢谢您的帮助
------- 更新 1 -------
- 我在 Draft.js 上使用react-draft- wysiwyg 构建
- 要呈现的文本是 HTML,所以我更新了代码
- Linda Paiste用componentDidUpdate回答解决了主要问题链接
遵循工作代码(对我而言):
export class ControlledEditor extends Component {
constructor(props) {
super(props);
this.state = {editorState: EditorState.createEmpty()}
}
componentDidUpdate(prevProps) {
if (this.props.htmlContent !== prevProps.htmlContent) {
this.setState({
editorState: EditorState.createWithContent(ContentState.createFromBlockArray(convertFromHTML(this.props.htmlContent)))
});
}
}
onEditorStateChange = (editorState) => {
this.setState({editorState})
};
render() {
const {editorState} = this.state;
return (
<>
<Container className="mt-5">
<Row>
<Editor
editorState={editorState}
wrapperClassName="demo-wrapper"
editorClassName="demo-editor"
onEditorStateChange={this.onEditorStateChange}
/>
</Row>
</Container>
<Container className="mt-5">
<Row>
<div dangerouslySetInnerHTML={{__html: this.props.htmlContent}}/>
</Row>
</Container>
</>
);
}
}
ControlledEditor.propTypes = {
htmlContent: PropTypes.string
}