react的組件之間的傳值可以有三種情況,分別是
(1)父組件——子組件 主要利用props屬性
(2)子組件——父組件 藉助於函數的傳遞,利用了類似的回調函數
(3)兄弟組件之間的值傳遞 第三方思想PubSub (還有就是子1->父,父->子2)
下面的程序演示瞭如上三種情況
<body>
<div id="div1"></div>
<script src='react-0.14.7/build/react.js'></script>
<script src='react-0.14.7/build/react-dom.js'></script>
<script src='browser.js'></script>
<script src='PubSub.js'></script>
<script type='text/babel'>
var Commsg = React.createClass({
getInitialState:function(){
return {
<span style="white-space:pre"> </span>content:0
};
},
componentWillMount:function(){
PubSub.subscribe('select',function(msg,data){
this.setState({
content:data.value
});
}.bind(this));
},
componentWillUnmount:function(){
PubSub.unsubscribe('select');
},
render:function(){
return (
<div >你掌握的語言種類個數:{this.state.content}</div>
)
}
});
var Childcom = React.createClass({
render:function(){
var array=[];
this.props.arr.forEach(function(value,index,arr){
array.push(<label key={index}><span>{value}</span><input type='checkbox' onChange={this.props.on}/></label>);
}.bind(this));
return (<div>{array}</div>)
}
});
var Parcom = React.createClass({
getInitialState:function(){
return {
count:0
};
},
change:function(e){
this.setState({
count:e.target.checked?this.state.count+ 1:this.state.count- 1
});
},
render:function(){
var arr=['c++','java','node'];
return (
<div>
<h1 onClick={this.doChange}>the countis:{this.state.count}</h1>
<Childcom arr={arr} on={this.change}/>
</div>
);
},
doChange:function(){
PubSub.publish('select',{
value:this.state.count
});
},
});
ReactDOM.render(
<div>
<Commsg />
<Parcom />
</div>,
document.getElementById('div1')
);
</script>
</body>
react的組件化:
這張圖構成了如上頁面的全部,每種顏色的方框就是一個組件,也可以看出它們之間的關係,組件封裝這種開發模式非常好用,極大提高了效率。
red means div1
green means Commsg
blue means Parcom
purple means Childcom