React同級組件傳值


    

在React中同級組件本身是沒有任何關聯的,要想有聯系只能通過共同的父組件傳值,一個子組件將數據傳遞到父組件中,父組件接收值再傳入另一個子組件中

 

 

<!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">
//子組件向父組件傳值,父組件接收再傳遞給另一個子組件
class Childone extends React.Component{
constructor(props){
super(props);
this.state={color:"lightblue"}
}
handlecolor(){
this.props. fn("red");             
//在觸發方法中通過props添加一個新的fn方法,並且將顏色參數red傳入父組件
this.setState({color:"red"});
}
render(){
return(
<div>
<h4 style={{color:this.state.color}}>我是第一個子組件</h4>
<button onClick={this.handlecolor.bind(this)}>改變第二個子組件顏色</button>       
//給第一個子組件綁定一個方法,點擊就觸發,注意要綁定this
</div>
)
}
}
class Childtwo extends React.Component{
constructor(props){
super(props);
}
render(props){
return(
<h4 style={{color:this.props. co}}>我是第二個子組件</h4>               
//利用prop屬性從外界即父組件獲取參數,不能用state,state是內部使用的
)
}
}
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>         
//第一個子組件的方法fn,將參數red傳入函數change中,更新父組件本身的顏色childtwocolor
<Childtwo co={this.state.childtwocolor}></Childtwo>                   
//第二個子組件獲取父組件本身的顏色,當父組件顏色更新時,它也會隨之更新
</div>
)
}
}
ReactDOM.render(
<Parents />,
document.getElementById('box')
);
</script>
</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM