使用草稿编辑器状态更新父状态?

Updating state in parent with Draft editor state?

我有一个带有其他字段的表单的 Draftjs 编辑器。所有这些字段的状态都在该父组件中进行控制。我如何从草稿编辑器中获得与从更新父状态的常规 HTML 表单字段中相同的行为?

常规输入:

<input value={title} type="text" onChange={this.handleChange} name="title" placeholder="Title" id="title" />

草稿 js 编辑:

<TextEditor placeholder="Write your summary..." value={summary} toolbar />

更改处理程序:

handleChange(event) {
  this.setState({[`${event.target.name}`]: event.target.value});
};

你可以简单地做: 在 parent 中:(不是我添加了 update={ this.update } 道具)

…
render(){
    return (
    <input value={title} type="text" onChange={this.handleChange} name="title" placeholder="Title" id="title" update={ this.update }/>
    );
}

update(editorState){
  console.log('update',editorState);
}
…

在编辑中:

handleChange(event) {
  this.setState({[`${event.target.name}`]: event.target.value});
  this.props.update(this.state);
};

这将调用 parent 的 update() 函数,这就是您要搜索的内容吗?

编辑:

import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';

class Parent extends React.Component {
…
    render() {
      return (
        <div>
            <form>
            <MyEditor update={ this.update }>
            <form>
        </div>
      );
    }
   update(editorState) {
      console.log('editor s state', editorState);
   }
…
}
// from draft website :
class MyEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onChange = (editorState) => {
        this.setState({editorState});
        this.props.update(this.state);
    }
  }
  render() {
    return (
        <Editor editorState={this.state.editorState} onChange={this.onChange} />
    );
  }
}

ReactDOM.render(
  <Parent/>,
  document.getElementById('container')
);