How to pass the data from child to parent? when parent is class based and child is functional based

前端 未结 3 591
北海茫月
北海茫月 2021-01-23 20:55

I want to pass the data which is anything like, array, strings, numbers into the App(Parent) Component) from the Child1(Child) components.

There\'s a parent who is class

3条回答
  •  孤城傲影
    2021-01-23 21:24

    You can pass a function to Child (called Counter in the example) that will change Parent state. Since you pass the same reference for this function every time (this.increment) the only Children that will render are those that changed.

    const Counter = React.memo(
      //use React.memo to create pure component
      function Counter({ counter, increment }) {
        console.log('rendering:', counter.id)
        // can you gues why prop={new reference} is not a problem here
        //  this won't re render if props didn't
        //  change because it's a pure component
        return (
          
    counter is {counter.count}
    ) } ) class Parent extends React.PureComponent { state = { counters: [ { id: 1, count: 0 }, { id: 2, count: 0 } ] } increment = _id => this.setState({ counters: this.state.counters.map(val => _id === val.id ? { ...val, count: val.count + 1 } : val ) }) render() { return (
    {this.state.counters.map(counter => ( ))}
    ) } } //render app ReactDOM.render(, document.getElementById('root'))
    
    
    

提交回复
热议问题