2017-05-28 36 views
0

我有一个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}); 
}; 

回答

0

你可以简单地做: 在父:(不,我有加上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); 
}; 

这将调用父的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') 
); 
+0

我认为这将是,如果我有编辑器中的其他投入。我在编辑器中使用了其他输入的编辑器,而不是编辑器中的其他输入。我认为我确实看到了你的观点,但我可以传递一个接受编辑状态的函数并将其传递给它。这就说得通了。谢谢! – humdinger

+0

是的,向孩子传递一个函数是我看到的更新父母状态的唯一“好”解决方案 –