[英]How do I set a state in a child component?
Let's say I have a component.假设我有一个组件。
Inside that component I am calling a child component.在该组件内,我调用了一个子组件。
That child component has a state, which I would want to set from the parent component.该子组件有一个 state,我想从父组件设置它。
Component成分
// component
// ...
setState( 1 );
<ChildComponent ???setStateFunc={setState}???> // This setState should point to the child function
setState( 2 );
// ...
// end component
Child component子组件
// child component
// ...
const [state, setState] = useState(null);
// ...
// end child component
How do I do that?我怎么做?
If you want your Parent Component State should update from Child Component, handle your states like this:如果您希望您的父组件 State 应该从子组件更新,请像这样处理您的状态:
Add this to your Parent Component File:将此添加到您的父组件文件中:
this.state = {
value: 0
}
...
changeHandler = (e) => {
this.setState({value: e})
}
...
//Pass this function like this
<ChildComponent value={{this.state.value}} setValue={(e) => changeHandler(e)}>
And manage your setValue by setting any value from your Child Component file, like:并通过设置子组件文件中的任何值来管理您的 setValue,例如:
...
//For example if you're using TextInput component
<TextInput
value={this.props.value}
onChangeText={this.props.setValue}
/>
...
Hope this works for you.希望这对你有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.