我正在尝试将 Draft.js 的编辑器状态从编辑器组件传递到我自己的 Sidebar
组件。
使用最上面的组件 Notes
我使用回调从 CustomEditor
获取编辑器状态并将其设置为 Notes
状态。然后,我将该状态作为 prop 传递给 Sidebar
。
问题是 prop 是在回调触发之前设置的。我正在考虑 setTimeout
但这似乎很粗糙。我知道 UNSAFE_componentWillReceiveProps()
但文档不推荐它。对于这个用例有什么 react 吗?
export class Notes extends Component {
constructor(props) {
super(props);
this.getEditorState = this.getEditorState.bind(this)
this.state = {
editorState: "the placeholder data Sidebar should not have as a prop"
};
}
getEditorState(state) {
console.log(state)
this.setState({editorState: state})
}
render() {
return (
<section id="Notes">
<div id="editor-holder">
<Sidebar currentEditorState={this.state.editorState}/>
<div id="Editor">
<FileHeader />
<CustomEditor getState={this.getEditorState}/>
</div>
</div>
</section>
);
}
}
export default Notes;
最佳答案
新的 Context API 就是此类问题的解决方案。我花了一些时间来理解它,但我想出了将 editorState
获取到 Sidebar
作为 Prop 。
export const NoteContext = React.createContext("placeholderEditorState");
export class Notes extends Component {
constructor(props) {
super(props);
this.getEditorState = this.getEditorState.bind(this)
this.getFolderData = this.getFolderData.bind(this)
this.state = {
editorState: null,
folderData: null
};
}
getEditorState(state) {
this.setState({editorState: state});
}
getFolderData(data) {
this.setState({folderData : data})
}
render() {
return (
<section id="Notes">
<TopBar />
<div id="editor-holder">
<NoteContext.Provider value={{editorState: this.state.editorState}} >
<NoteContext.Consumer>
{(context)=>{ return (
<Sidebar currentEditorState={context.editorState} getFolderData={this.getFolderData}/>
)}}
</NoteContext.Consumer>
</NoteContext.Provider>
<div id="Editor">
<NoteContext.Provider value={{folderData: this.state.folderData}} >
<FileHeader />
</NoteContext.Provider>
<CustomEditor getState={this.getEditorState}/>
</div>
</div>
</section>
);
}
}
现在看来很简单,说明我学到了很多东西!如果我可以改进这里的任何内容,请告诉我。
关于reactjs - React 在父级状态更改后更新子级的 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50126085/