[英]How to get state of child component in react native
I have Main Component file and use in another child component. 我有主要组件文件,并在另一个子组件中使用。 I have to get state of the child component. 我必须获取子组件的状态。
Ex :- Home (Parent) - Form (Child) component i have been set the value of any text box in state. 例如:-主页(父母)-表单(子项)组件我已经设置了处于状态的任何文本框的值。 So ho can i get the state value of Form component into the main component. 因此,我可以将Form组件的状态值添加到主要组件中。
Pass the function as a prop to the child component 将功能作为道具传递给子组件
//Parent Component
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
};
this._handleChange = this._handleChange.bind(this);
}
_handleChange(e) {
const { name, value } = e.target;
this.setState({
[name]: value
});
}
render(){
return(){
<Form valueChange={this._handleChange} />
}
}
}
//Child Component
export default class Form extends Component {
render(){
return(){
<div>
<input type="email" name="username" onChange={(e) => this.props.valueChange()} value={username}/>
<input type="password" name="password" onChange={(e) => this.props.valueChange()} value={password}/>
</div>
}
}
}
Generally in React (and React-Native) information is passed down from the parent component to its children. 通常,在React(和React-Native)中,信息从父组件传递到其子组件。 However if you need to change something in the parent component's state based on the child-component's state, you can pass a function to the child that does just that. 但是,如果您需要根据子组件的状态更改父组件状态的某些内容,则可以将一个函数传递给子组件,以执行此操作。
For example: 例如:
// Inside Parent Component
openModalFromParent() {
this.setState({ modalOpened: true });
};
// Passing Function to Child
<ChildComponent openModal={ this.openModalFromParent } />
// Inside Child Component
<TouchableHighlight onPress={ () => this.props.openModal() } />
In this example the button in the child component would trigger a function that alters the state of the parent component - hope this helps! 在此示例中,子组件中的按钮将触发一个更改父组件状态的功能-希望这会有所帮助!
In React, your state can only flow down from the parent to the children. 在React中,您的状态只能从父级流到子级。 What you should do is move the state from the child to the parent and then pass the state to the child as props. 您应该做的是将状态从子级移到父级,然后将状态作为道具传递给子级。
Try reading this: https://reactjs.org/docs/lifting-state-up.html 尝试阅读以下内容: https : //reactjs.org/docs/lifting-state-up.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.