【问题标题】:How to change the initial content of DraftJS Editor as the state change?如何随着状态的变化而改变 DraftJS Editor 的初始内容?
【发布时间】: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>
    );
  }
}

【问题讨论】:

    标签: reactjs draftjs


    【解决方案1】:

    使用 ContentState 来初始化编辑器并更改初始内容。 要初始化,而不是 EditorState.createEmpty() 加上构造函数中的所有其他代码行,使用:

    this.state = {
      editorState: EditorState.createWithContent(
                   ContentState.createFromText('What is your name?')
                  ),
    };
    

    要在您的点击处理程序中更改此数据,请执行以下操作:

          changeContent() {
            this.setState({
                 editorState: EditorState.createWithContent(
                              ContentState.createFromText('Quel est votre nom?')
                              )
             });   
           }
    

    【讨论】:

      猜你喜欢
      • 2018-12-17
      • 2015-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-18
      相关资源
      最近更新 更多