Currently I am using reat creat app to build my appication in my application had three componentes those are com1, com2, com3 I want to update userId state value in com1 based on com3 will recive props here com2 is child component of com1.
Here is my sample code
import comp2 from './comp2.js';
class comp1 extends React.Component {
constructor(props) {
super(props);
this.state = {
userId:""
}
};
click() {
this.setSate({userId:"123"});
}
render() {
<div>Hello Child onClick={this.click}</>
<comp2 data={this.state.userId}
}
}
import comp3 from './comp3.js';
class comp2 extends React.Component {
constructor(props) {
super(props);
};
componentWillReceiveProps(nextProps) {
if (nextProps.data !== this.props.data) {
this.setState({userID:this.state.userId});
}
}
}
click() {
this.setState({userID:"456"})
}
render() {
<div>Hello Child onClick={this.click}</>
<comp3 data={this.state.userId}
}
}
class comp3 extends React.Component {
constructor(props) {
super(props);
};
componentWillReceiveProps(nextProps) {
if (nextProps.data !== this.props.data) {
this.setState({userID:this.state.userId});
}
}
render() {
<div>Hello Child onClick={this.click}</>
<comp3 data={this.state.userId}
}
}
您可以在它们之间使用共享存储,也可以使用父存储来管理子存储之间的数据。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.