【发布时间】:2020-12-10 17:01:17
【问题描述】:
我使用 Draft.js 启动了一个包含一些内容的编辑器。在下面的示例中给出的状态中定义的初始内容。更改状态时如何用新内容替换整个内容。在以下示例中,我尝试将state initData 指定为What is your name?,当用户单击input button 时,状态更改为Quel est votre nom?,并且翻译后的内容应替换编辑器。
import React, { Component } from 'react';
import { EditorState, ContentState, convertFromHTML} from 'draft-js';
export default class DraftEditor extends Component {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createEmpty(),
initData: "What is your name?" //Initial data and will be updated on button click
};
this.changeContent = this.changeContent.bind(this);
const blocksFromHtml = this.state.initData;
const html = blocksFromHtml;
const blocksFromHTML = convertFromHTML(html)
const content = ContentState.createFromBlockArray(
blocksFromHTML.contentBlocks,
blocksFromHTML.entityMap
);
this.state = { editorState: EditorState.createWithContent(content)};
this.onChange = (editorState) => {
this.setState({editorState});
}
}
onEditorStateChange = (editorState) => {
this.setState({
editorState
});
};
changeContent() {
this.setState({ initData: "Quel est votre nom?" }); //This is the data that will be replaced the initial data
}
render(){
return (
<React.Fragment>
<input type='button' value="change" onClick={this.changeContent} />
<Editor editorState={editorState} />
</React.Fragment>
);
}
}
【问题讨论】: