React Hook : Send data from child to parent component

后端 未结 4 1239
终归单人心
终归单人心 2020-12-07 19:07

I\'m looking for the easiest solution to pass data from a child component to his parent.

I\'ve heard about using Context, pass trough properties or update props, but

4条回答
  •  长情又很酷
    2020-12-07 19:47

    A common technique for these situations is to lift the state up to the first common ancestor of all the components that needs to use the state (i.e. the PageComponent in this case) and pass down the state and state-altering functions to the child components as props.

    Example

    const { useState } = React;
    
    function PageComponent() {
      const [count, setCount] = useState(0);
      const increment = () => {
        setCount(count + 1)
      }
    
      return (
        

    count {count}

    (count should be updated from child)
    ); } const ChildComponent = ({ onClick, count }) => { return ( ) }; ReactDOM.render(, document.getElementById("root"));
    
    
    
    

提交回复
热议问题