简体   繁体   中英

How to call nested child's method from parent element in react js

I have the following structure:

Parent -> Some element 1 ... Some element N -> Child
                                            -> Child
                                            -> Child

Let's say, I want on Parent's method to call some function of every child. What is the way to do this? I see answers with the use of refs, but it looks like they work only for direct children and not for a nested ones.

Maybe it is possible to add some event tracker or something similar for child and trigger it with parent's method call?

React is uni-directional by design, data flows from parent to child and not the other way round. This is also true for childrens own methods, however it is not the case for events that should flow upward from child to parent. You can take advantage of this by passing in callbacks to your child components that allow you to interact with the child how you would like to.

const Parent = (props) => {
    // Wrapped in a useCallback to prevent circular dependencies
    const childApi = useCallback((api) => {
        // do something in the parent with the childs exposed api
        api.updateState('Hello World');
    });

    return <Child api={childApi} />;
}

const Child = (props) => {
    const { api } = props;
    const [value, setValue] = useState(null);

    const localApi = {
        updateState: (value) => {
            setValue(value);
        }
    }

    // Use effect to ensure that the callback only re-renders this component
    // when it actually does change and in conjunction with useCallback in the
    // parent avoids cyclic dependencies / infinite re-renders
    useEffect(() => {
        // Call the parents callback with the childs API as a parameter
        api(localApi);
    }, [api]);

    return <p>{value}</p>;
}

The result of the above renders Hello World to the browser through the child component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM