Reactjs - How to pass values from child component to grand-parent component?

前端 未结 2 1061
孤城傲影
孤城傲影 2020-12-31 16:00

Below is correct example for passing the values from child component to parent component in reactjs.

App.jsx

import React from \'react         


        
2条回答
  •  孤城傲影
    2020-12-31 16:43

    The most straightforward way is to pass updateState functions as far down the tree as they need to go. Ideally, your grandchild component is thought of as completely separate from the grandparent component... though that quickly becomes tedious.

    That's what React Redux is for. It creates a global state object with a publish/subscribe model. (The publish/subscribe model is somewhat abstracted away through a "connect" wrapper.) You can dispatch actions from anywhere, to anywhere. Actions trigger "reducers", which transform the global state, and React reacts to the modified state by re-rendering components (in a surprisingly efficient way).

    For small programs, Redux can be overkill. If you really do just have the grandparent/parent/grandchild in your model, just pass the updateState functions. As your program grows, try replacing them with Redux. It can be hard to learn (especially since IMHO the standard tutorials are simply awful), but it's the intended solution to the general problem you're describing.

提交回复
热议问题