如何在反应中将状态从父母传递给孩子?

时间:2020-03-20 09:16:09

标签: reactjs

如何将状态属性从父级传递给子级?在以下实现中,Dropdown组件的状态为“ isActive”,我想在Button组件中访问它以将适当的样式附加到它。 Dropdown必须通用,因为它应该采用不同类型的按钮。

<Dropdown items="...">
  <Button active ="false" />
</Dropdown>

Dropdwon.js

...

    constructor(props){
        super(props)
        this.state = {
         isActive: true,
        }
    }

    render (){
        return (
               <div className={styles.toggle} onClick={(event) => this.showMenu(event)}>
                    {this.props.children} /* want to set active prop for the child button here */
                </div>
        );
} 

...

3 个答案:

答案 0 :(得分:1)

除了我链接的答案外,还有另一种我未提及的实现此目的的方法。

您可以将函数作为下拉菜单的子元素发送,该函数将isActive作为变量:

<Dropdown items="...">
  {isActive => <Button active={isActive} />}
</Dropdown>

然后是render函数,只需调用该函数并将状态值作为参数发送:

render(){
    return (
        <div className={styles.toggle} onClick={(event) => this.showMenu(event)}>
            {this.props.children(this.state.isActive)}
        </div>
    );
} 

答案 1 :(得分:1)

您有两种可能性:

  1. 提升您的Dropdown状态并将其保留在其父组件中;
  2. 使用useContext挂钩;

第一种方法会更好,但可能对您的应用程序不利(我不知道)。让我为这两种情况举例。


这是一个示例,其中我将isActive状态提升到了父组件。

const ParentComponent = () => {
    const [isActive, setIsActive] = useState(false);

    handleIsActiveChange = (newValue) => {
        setIsActive(newValue);
    }

    <Dropdown isActive={isActive} setIsActive={handleIsActiveChange}>
        <Button isActive={isActive} />
    </Dropdown>
}

const Dropdown = props => {
    // You can use `props.isActive` to know whether the dropdown is active or not.
    // You can use `props.handleIsActiveChange` to update the `isActive` state.
}

const Button = props => {
    // You can use `props.isActive` to know whether the dropdown is active or not.
}

相反,这利用了useContext API:

const dropdownContext = React.createContext(null);

const Dropdown = props => {
    const [isActive, setIsActive] = useState(false);

    return (
        <dropdownContext.Provider value={{ isActive }}>
            {props.children}
        </dropdownContext.Provider>
    );
}

const Button = props => {   
    const dropdownCtx = React.useContext(dropdownContext);

    // You can use `dropdownCtx.isActive` to know whether the dropdown is active or not.
}

答案 2 :(得分:0)

<Dropdown >
  <Button isActive={this.state.isActive} />
</Dropdown>

在按钮中输入this.props.isActive