简体   繁体   English

将状态从子级传递到父组件

[英]Passing state from a child to parent component

Is there any proper way to access a property in the state of a child component and get its value from a parent component? 是否有任何正确的方法来访问子组件状态中的属性并从父组件获取其值?

I have a component called "itemSelection" where I map through an api response to get some items like this 我有一个名为“itemSelection”的组件,我在其中映射api响应以获取这样的项目

            <div className="row">
                {this.state.items.map(i => <Item ref="item" id={i.id} name={i.name} quantity={i.quantity} />)}
            </div>

In the Item component there a property in the state called "selected" which I want to know its value if it was true or false in the itemSelection component. 在Item组件中有一个名为“selected”的状态的属性,如果在itemSelection组件中为true或false,我想知道它的值。 I know I can pass props from itemSelection to Item but what if I want the opposite? 我知道我可以将itemSelection中的道具传递给Item但是如果我想要相反的话呢? where I can pass data from Item to itemSelection 我可以将数据从Item传递到itemSelection


EDITED EDITED

So, I have made a property in the parent component "itemSelection" called "selected" and I have set it to =false= (knowing that I have the same property in the child component which is set to =false= also) 所以,我在父组件“itemSelection”中创建了一个名为“selected”的属性,并将其设置为= false =(知道我在子组件中具有相同的属性,设置为= false =)

in the child component I have put this line in the event handler function after I have made setState to the property selected to change it to =true= 在我将setState设置为所选属性以将其更改为= true =之后,我已将此行放在事件处理函数中

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

then in the parent component I have made this function 然后在父组件中我做了这个功能

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

but still didn't work, I don't know if I have set it right. 但仍然没有奏效,我不知道我是否做得对。

Passing props from child to parent component works using callback functions in React. 将道具从子组件传递到父组件使用React中的回调函数。 Or you can also use state management library like Redux and store the data in child component and get the data in parent component. 或者您也可以使用Redux等状态管理库,并将数据存储在子组件中,并获取父组件中的数据。

The example below illustrate how to send props from child to parent. 下面的示例说明了如何从子级向父级发送道具。 I am sharing below example to make you understand how you can send props from child to parent. 我将在下面分享示例,让您了解如何从子项向父项发送道具。

ItemSelection: Parent component 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>

Item: Child component 项目:子组件

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

As tried to explain in the comments you can use callbacks for this, but try to avoid to get a value from child component like that. 正如试图在评论中解释的那样,您可以使用回调,但尽量避免从子组件中获取值。 You can keep selected state in your parent component. 您可以在父组件中保持selected状态。 Your Item component does not need to keep a state at all for this. 您的Item组件不需要为此保持状态。 With proper handlers from the parent, you can update your state easily. 使用来自父级的适当处理程序,您可以轻松更新您的状态。

 class App extends React.Component { state = { items: [ { id: "1", name: "foo", quantity: 1 }, { id: "2", name: "bar", quantity: 2 }, { id: "3", name: "baz", quantity: 3 }, ], selected: "", } handleSelect = item => this.setState({ selected: item.id }) render() { const { items } = this.state; return ( <div> Selected item: {this.state.selected} { items.map( item => <Item key={item.id} item={item} onSelect={this.handleSelect} /> ) } </div> ); } } const Item = props => { const { item, onSelect } = props; const handleSelect = () => onSelect( item ); return ( <div style={{border: "1px solid gray"}} onClick={handleSelect}> <p><strong>Item id:</strong> {item.id}</p> <p><strong>Item name</strong>: {item.name}</p> <p><strong>Item quantity</strong>: {item.quantity}</p> </div> ) } ReactDOM.render(<App />, document.getElementById("root")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM