【问题标题】:How do I set a state in a child component?如何在子组件中设置状态?
【发布时间】:2021-11-21 16:45:48
【问题描述】:

假设我有一个组件。

在该组件内部,我调用了一个子组件。

那个子组件有一个状态,我想从父组件中设置它。

组件

// component
// ...

setState( 1 );

<ChildComponent ???setStateFunc={setState}???> // This setState should point to the child function

setState( 2 );

// ...
// end component

子组件

// child component
// ...

const [state, setState] = useState(null);

// ...
// end child component

我该怎么做?

【问题讨论】:

    标签: android react-native components state


    【解决方案1】:

    如果您希望您的父组件状态应该从子组件更新,请像这样处理您的状态:

    将此添加到您的父组件文件:

    this.state = {
        value: 0
    }
    ...
    
    changeHandler = (e) => {
       this.setState({value: e})
    }
    
    ...
    
    //Pass this function like this 
    <ChildComponent value={{this.state.value}} setValue={(e) => changeHandler(e)}>
    

    并通过设置 子组件 文件中的任何值来管理您的 setValue,例如:

    ...
    
    //For example if you're using TextInput component
    <TextInput 
        value={this.props.value}
        onChangeText={this.props.setValue}
    />
    ...
    

    希望这对你有用。

    【讨论】:

    • 感谢您的回答。这并不完全是我想要的,但仍然相关。我有点在寻找相反的方式。但我已经想出了别的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 2018-04-29
    相关资源
    最近更新 更多