React setState不影响Children

时间:2017-12-18 17:19:15

标签: javascript reactjs ckeditor state

我使用 CKEditor 对于一个简单的邮件表单,看起来像这样:

class SimpleForm extends Component{
constructor() {
    super();
    this.updateContent = this.updateContent.bind(this);
    this.state = {
    title: "MyTitle",
    CKEditorContent: 'text here',
    newMail: false,
    }
    this.baseState = Object.assign({}, this.state, {newMail: true});
}
}

updateContent(newContent) {
      console.log(newContent);
      this.setState({
          CKEditorContent: newContent.editor.getData(),
      })}

clearText(){
      this.setState(this.baseState);
    }

render() {
    return (
          <div>
              <CKEditor
                activeClass="p10"
                content={this.state.CKEditorContent}
                events={{
                  "change": this.updateContent
                }}
              />
                <Button
                  type="submit"
                  label="clear"
                  secondary={true}
                  onClick={this.clearText.bind(this)}
                />
          </div>
    );
}
}

问题是,虽然setState被正确调用 - this.title和this.CKEditorContent都重置了它们的值,但CKeditor字段的内部保持不变。

点击前

enter image description here 点击CLEAR后: enter image description here

1 个答案:

答案 0 :(得分:2)

根据this issue,你需要使用CKEditor的setData方法来操纵输入的状态。

因此,在您的情况下,解决方法是修改代码,如下所示:

    <CKEditor
      activeClass="p10"
      content={this.state.CKEditorContent}
      events={{
        change: this.updateContent,
      }}
      ref={(instance) => { this.ckeditor = instance; }}
    />

然后在你的clearText()函数中,只需将其称为:

this.ckeditor.editorInstance.setData('');