【发布时间】:2019-05-07 12:41:26
【问题描述】:
ObjectList 有一个以列表形式呈现的对象数组。当用户单击列表项时,该对象将被发送回 ObjectEditor,以便用户可以查看它并继续编辑。问题是我不确定如何将该对象传递给 ObjectEditor,因为单击事件发生在 ObjectList 中。
我最初的解决方案是将它作为道具传递给 ObjectEditor 并使用 componentWillReceiveProps 方法来更新 ObjectEditor 状态。但是,该解决方案并不实用,因为我不希望它在每次道具更改时都更新。有没有更好的办法?
我是 React 的新手,所以在我了解 React 之前,我想暂时避免使用 Redux。
为了清晰起见,我已经大量削减了代码。
对象列表:
constructor(props){
super(props);
this.state = { objects: [
{title: '', items: [], anotherThing:''},
{title: '', items: [], anotherThing:''}
]}
}
viewObject = (index) => {
let object = {...this.state.object[index]};
// Then some code that passes the object to the ObjectEditor Component
}
render(){
return(
<div>
<li key={index} onClick={ () => this.viewObject(index) } >
// A list of titles from state
</li>
<ObjectEditor />
</div>
)
}
对象编辑器:
constructor(props){
super(props);
this.state = {title:'', items: [], anotherThing:''}
}
// various event handlers that update the state based off form inputs
render(){
return(
<div>
// Various form fields which get pushed to state
<button>Save & Add New</button>
// function that maps through state and renders it to the page
</div>
)
}
}
【问题讨论】:
标签: javascript reactjs