gpt4 book ai didi

reactjs - 将状态从子组件传递到父组件

转载 作者:行者123 更新时间:2023-12-03 13:42:46 26 4
gpt4 key购买 nike

是否有任何正确的方法可以访问子组件状态下的属性并从父组件获取其值?

我有一个名为“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。我知道我可以将 Prop 从 itemSelection 传递到 Item,但如果我想要相反的结果怎么办?我可以在其中将数据从 Item 传递到 itemSelection

<小时/>

已编辑

因此,我在父组件“itemSelection”中创建了一个名为“selected”的属性,并将其设置为 =false= (知道我在子组件中也有相同的属性,该属性也设置为 =false= )

在子组件中,我将这一行放入事件处理函数中,然后将所选属性设置为 setState 以将其更改为 =true=

this.props.getPropsFromChild(this.state.selected);

然后在父组件中我做了这个功能

getPropsFromChild = (selected) => {
this.setState({selected: selected});
}

但是还是不行,不知道我是否设置对了。

最佳答案

使用 React 中的回调函数将 props 从子组件传递到父组件。或者你也可以使用像Redux这样的状态管理库,将数据存储在子组件中,并在父组件中获取数据。

下面的示例说明了如何将 props 从子级发送到父级。我分享下面的示例是为了让您了解如何将 Prop 从 child 发送给 parent 。

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

关于reactjs - 将状态从子组件传递到父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52305225/

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