gpt4 book ai didi

javascript - 父级将状态传递给子级 - React js

转载 作者:行者123 更新时间:2023-12-01 01:27:26 25 4
gpt4 key购买 nike

ObjectList 有一个呈现为列表的对象数组。当用户单击列表项时,该对象将发送回 ObjectEditor,以便用户可以查看它并继续编辑。问题是我不确定如何将该对象传递给 ObjectEditor,因为单击事件发生在 ObjectList 中。

我最初的解决方案是将其作为 props 传递给 ObjectEditor 并使用 componentWillReceiveProps 方法来更新 ObjectEditors 状态。然而,该解决方案并不实用,因为我不希望它在每次 props 更改时都更新。有更好的办法吗?

我是 React 新手,所以我想暂时避免使用 Redux,直到我了解 React。

为了清晰起见,我大量削减了代码。

对象列表:

      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>
)
}
}

最佳答案

我的建议是让父组件处理所有状态和逻辑,并让 ObjectEditor 组件保持一个简单的表示组件,没有自己的逻辑或状态。它看起来有点像这样。

class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
objects: [
{ title: '', items: [], anotherThing: '' },
{ title: '', items: [], anotherThing: '' }
],
editObject: {},
}
}

viewObject = (index) => {
let object = { ...this.state.object[index] };
this.setState({editObject: object}); // sets the state if the clicked item.
// Then some code that passes the object to the ObjectEditor Component
}

handleChange = (e) => {
// handle change
}

render() {
return (
<div>

<li key={index} onClick={() => this.viewObject(index)} >
// A list of titles from state
</li>

<ObjectEditor viewObject={this.state.viewObject} handleChange={this.handleChange} />
</div>
)
}
}


class ObjectEditor extends React.Component {
render() {
return (
// render some sort of editor
// display data based on the props passed down
// when user edits in the form, call up to the parent's change handler
);
}
}

关于javascript - 父级将状态传递给子级 - React js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53640878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com