您的位置:首页 > Web前端 > React

React 组件间通信

2015-06-04 21:23 525 查看
https://jsfiddle.net/69z2wepo/9719/

<script src="https://facebook.github.io/react/js/jsfiddle-integration.js"></script>

<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
<hr/>
<div id="container1">
<!-- This element's contents will be replaced with your component. -->
</div>

<hr/>
<!--在容器页面中操作Foo的方法-->
<div onclick="clickSpan()" style="border:#CCCCCC 1px solid">click me to change Foo's age to 20 from container page</div>


  

var Foo=React.createClass({
//setGender是部件Foo向外公开的一个方法,用于操作Foo的gender值
setAge:function(age){
var stateVal={};
if(age>20)
{
stateVal={gender:'male',age:age}
}
else
{
stateVal={gender:'femle',age:age}
}
this.setState(stateVal);
},
getInitialState:function(){
return {
age:0,
gender:'female'
}
},
render:function(){
return <div>
<div>
<strong>{this.props.componentName}</strong>
</div>
<div>
gender:<input value={this.state.gender}  type="text" ref="txt"  />
</div>
<div>
age:{this.state.age}
</div>
</div>
}
});

var Bar = React.createClass({
onAgeChange:null,
render: function() {
return <div>
<div onClick={this.helloClick}>
<strong>{this.props.componentName}</strong>(click me to show age value)
</div>
<div>
age:<input onChange={this.onChange} type="text" ref="age"  />
</div>
<div>
age:{this.state.age}
</div>
</div>;
},
helloClick:function(){
alert(this.refs.age.getDOMNode().value);
},
onChange:function(e){
if(this.onAgeChange) this.onAgeChange(e.target.value);
this.state.age=e.target.value;
this.setState({age: e.target.value});
//this.forceUpdate();
},
getInitialState:function(){
return {
age:0
}
},
componentDidMount:function(){
this.refs.age.getDOMNode().value=this.state.age;
}
});

var foo=React.render(<Foo componentName="Foo"/>, document.getElementById('container'));

var bar=React.render(<Bar componentName="Bar" />, document.getElementById('container1'));

bar.onAgeChange=function(age){
foo.setAge(age);
}

function clickSpan(){
// 在容器页面中操作Foo的方法
foo.setAge(22);
}


  

参考

Thinking in React
https://facebook.github.io/react/docs/thinking-in-react.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: