React Hook : Send data from child to parent component

后端 未结 4 1238
终归单人心
终归单人心 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:46

    To make things super simple you can actually share state setters to children and now they have the access to set the state of its parent.

    example: Assume there are 4 components as below,

    function App() {
      return (
        
    ); } const GrandParent = () => { const [name, setName] = useState("i'm Grand Parent"); return ( <>
    {name}
    ); }; const Parent = params => { return ( <> ); }; const Child = params => { return ( <> ); };

    so grandparent component has the actual state and by sharing the setter method (setName) to parent and child, they get the access to change the state of the grandparent.

    you can find the working code in below sandbox, https://codesandbox.io/embed/async-fire-kl197

提交回复
热议问题