Passing state from a child to parent component

混江龙づ霸主 提交于 2019-12-04 10:01:04
Hemadri Dasari

Passing props from child to parent component works using callback functions in 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.

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

      //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. Your Item component does not need to keep a state at all for this. 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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!