是否有任何正确的方法来访问子组件状态下的属性并从父组件获取其值?
我有一个名为“itemSelection”的组件,我在其中通过 api 响应进行映射以获取像这样的一些项目
<div className="row">
{this.state.items.map(i => <Item ref="item" id={i.id} name={i.name} quantity={i.quantity} />)}
</div>
在 Item 组件中,有一个处于状态的属性称为“selected”,我想知道它的值在 itemSelection 组件中是 true 还是 false。我知道我可以将道具从 itemSelection 传递到 Item,但如果我想要相反的结果怎么办?我可以在其中将数据从 Item 传递到 itemSelection
EDITED
因此,我在父组件“itemSelection”中创建了一个名为“selected”的属性,并将其设置为= false =(知道我在子组件中也有相同的属性,该属性也设置为= false =)
在子组件中,我将这一行放入事件处理函数中,然后我将 setState 设置为所选属性以将其更改为 =true=
this.props.getPropsFromChild(this.state.selected);
然后在父组件中我做了这个函数
getPropsFromChild = (selected) => {
this.setState({selected: selected});
}
但还是没用,不知道我是否设置对了。
将 props 从子组件传递到父组件可以使用 React 中的回调函数。或者你也可以使用像Redux这样的状态管理库,将数据存储在子组件中,并在父组件中获取数据。
下面的示例说明了如何将 props 从子级发送到父级。我分享下面的示例是为了让您了解如何将道具从孩子发送给父母。
ItemSelection:父组件
//handler function
getPropsFromChild = (id, name) => {
console.log(id, name);
}
//pass down your handler function to child component as a prop
<div className="row">
{this.state.items.map(i => <Item ref="item" id={i.id} name={i.name} getPropsFromChild={this.getPropsFromChild} quantity={i.quantity} />)}
</div>
项目:子组件
componentDidMount(){
//access handler function passed to your item component and access it using this.props and send the values as you want to the function
this.props.getPropsFromChild(“01”, “Hi”);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)