React siblings pass value

    

React siblings in itself is not any associated, in order to have contact only pass through a common parent component value, a sub-assembly component passes the data to the parent, the parent component and then pass the received value in the other sub-assembly

 

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="box"></div>
<script type="text/babel">
// the sub-components, the parent receives the value transmitted to the parent element then passed to another subassembly
class Childone extends React.Component{
constructor(props){
super(props);
this.state={color:"lightblue"}
}
handlecolor(){
this.props. fn("red");             
// add a new method by props fn triggering method, and the red color parameters passed in the parent component
this.setState({color:"red"});
}
render(){
return(
<div>
<H4 style = {{color: this.state.color}}> I is a first subassembly </ h4>
<Button onClick = {this.handlecolor.bind (this)}> color change of the second sub-assembly </ button>       
// first child component is bound to a method, click on the trigger, pay attention to bind this
</div>
)
}
}
class Childtwo extends React.Component{
constructor(props){
super(props);
}
render(props){
return(
<Color H4 style = {{:. this.props CO.'s }}> I is a second subassembly </ h4>               
// use prop property parameters acquired from outside the parent component i.e., can not state, state is used internally
)
}
}
class Parents extends React.Component{
constructor(props){
super(props);
this.state={childtwocolor:"lightblue"};
}
change(color) {
this.setState({childtwocolor: color});
}
render(props) {
return (
<div>
<Childone fn={(color)=>{this. change(color)}}></Childone>         
// Method fn of the first sub-assembly, the parameters passed to the function change in red, the color of the component itself update the parent childtwocolor
<Childtwo co={this.state.childtwocolor}></Childtwo>                   
// get the second sub-component color parent component itself, when the parent component color update, it will update
</div>
)
}
}
ReactDOM.render(
<Parents />,
document.getElementById('box')
);
</script>
</body>
</html>

Guess you like

Origin www.cnblogs.com/toMe-studio/p/11391996.html