将 functions/state 变量传递给 React 组件(箭头符号)

Passing functions/state variables to a React Component (Arrow notation)

我有一个用箭头函数表示法声明的 React 组件。该组件有一个子组件,该子组件应该更改 ParentComponent 的状态。我怎样才能做到这一点?如果我们将状态的变化作为函数传递(在本例中为 changeState),它会是什么样子?

const ParentComponent = () => {
    const [myState, setMyState] = useState(false);
    const changeState = () => setMyState(!myState);

    return(
        <ChildComponent /> // pass the state variables
    );
}

const ChildComponent = () => { // receive the state variables
    // change state of parent component
}

您也可以将函数作为 prop 传递给子组件。 尝试像这样将 changeState 函数传递给子组件

const ParentComponent = () => {
    const [myState, setMyState] = useState(false);
    const changeState = () => setMyState(!myState);

    return(
        <ChildComponent handleChange={changeState} /> // pass the state variables
    );
}

const ChildComponent = ({handleChange}) => { // receive the state variables
    // change state of parent component by simply calling 
    // handleChange as a normal function 

}

要将状态更改传递给子项 class,您只需将函数作为属性传递给子项即可。这适用于任何函数,如果您想进入子函数

,您甚至可以直接传入 setMyState
 const ParentComponent = () => {
    const [myState, setMyState] = useState(false);
    const changeState = () => setMyState(!myState);

    return(
        <ChildComponent 
            changeState={changeState}
        /> // pass the state variables
    );
}

const ChildComponent = ({changeState}) => { // receive the state variables
    // change state of parent component

    // you can use changeState here and 
    // it will update the parent component and rerender the page
}