我已经使用convertToRaw将内容保存到数据库中,我正在尝试加载回draft.js编辑器以使用户能够重新编辑内容 .
draft.js编辑器包含在基于react-modal的组件中,当用户单击该内容时_1143952_时会显示该组件 . 这很重要,因为模态(和编辑器)没有重新实例化,它们只是显示和隐藏 .
编辑器在(ES6)类构造函数中启动一次,只需使用:
this.state = {editorState: EditorState.createEmpty()}
当用户点击“编辑”时,我从数据库加载原始内容,然后我尝试使用以下多种变体将原始内容加载到编辑器中:
const contentState = convertFromRaw(rawContent)
const newEditorState = EditorState.push(this.state.editorState, contentState);
this.setState({editorState: newEditorState})
但是,虽然newEditorState显然包含正确的内容,但 this.setState({editorState: newEditorState})
似乎对组件(或编辑器)的状态完全没有影响 .
我打算如何为编辑设置新状态?谢谢!
UPDATE 在进一步调查中,显然只是 this.setState({editorState: newEditorState})
,仅针对编辑器组件失败 .
我已经通过设置测试状态属性并成功更新它来测试它,而editorState保持不变 .
为了完全测试,在我的构造函数中,我使用以下命令初始化了测试值:
this.state = {
editorState:EditorState.createWithContent(ContentState.createFromText('Hello')),
testVal: 'Test Val 1'
}
然后我写了一些测试代码来说明setState如何为我的测试值工作,但不是对于draft.js editorState:
const newEditorState = EditorState.createWithContent(ContentState.createFromText('Goodbye'))
console.log('Before setState')
console.log('newEditorState: ' + newEditorState.getCurrentContent().getPlainText());
console.log('editorState: ' + this.state.editorState.getCurrentContent().getPlainText());
console.log('testVal: ' + this.state.testVal);
this.setState({editorState: newEditorState, testVal: 'Test Val 2'}, function(){
console.log('After setState')
console.log('editorState: ' + this.state.editorState.getCurrentContent().getPlainText());
console.log('testVal: ' + this.state.testVal);
});
控制台输出如下所示:
Before setState
newEditorState: Goodbye
editorState: Hello
testVal: Test Val 1
After setState
editorState: Hello
testVal: Test Val 2
我不明白为什么在testVal时没有更新draft.js editorState?
2 回答
我在我的项目中使用了以下内容
好的,我发现了问题所在 .
在尝试调用
setState()
后,我立即将焦点设置到编辑器 .即我在编辑器上调用
focus()
,通过在我尝试setState之前移动focus()
调用,这一切都奏效了 . 显然接受焦点会对editorState产生影响 .