父组件传值给子组件
通过
来传递,子组件在接收父组件传递的数据时,通过
来接收
例如
//子组件
var MyButton=React.createClass({
render:function () {
return <button>{this.props.btnName}</button>
}
});
//父组件
var MyForm=React.createClass({
render:function () {
return <form>
<MyButton btnName={"注册"}></MyButton>
<MyButton btnName={"登录"}></MyButton>
</form>
}
})
在子组件传值给父组件时
1,在父组件中定义一个有参数的方法
2,通过属性,在调用子组件的时候,将方法传递过去
3,通过props读取传递来的方法,然后同时将值作为参数发送过去
例如
//父组件中
var MyMainComponent=React.createClass({
userMsg:'',
save:function(msg){ //sava:就是那个有参数的方法
console.log("子组件传来的值"+msg);
this.userMsg=msg;
},
get: function () {
return this.userMsg;
},
render:function () {
return <div> //funcSave就是要传递给子组件的属性
<MyInputComponent funcSave={this.save}></MyInputComponent>
<br/>
<MyButtonComponent funcGet={this.get}></MyButtonComponent>
</div>
}
});
//子组件
var MyInputComponent=React.createClass({
handleChange:function(){
this.props.funcSave(this.refs.myInput.value);//通过props读取父组件方法
},
render:function () { //并通过onChange事件将自身的value值传递给父组件
return <input ref="myInput" onChange={this.handleChange} type="text" placeholder="请输入内容"/>
}
});
var MyButtonComponent=React.createClass({
handleClick:function(){
alert(this.props.funcGet())//通过props读取父组件方法
},
render:function () { //onClick打印最后的数据
return <input onClick={this.handleClick} type="button" value="clickMe"/>
}
});
另外一种方法,通过状态来传递
<script type="text/babel">
var MyInputComponent=React.createClass({
handleChange:function(){
this.props.funcSave(this.refs.myInput.value);
},
render:function () {
return <input ref="myInput" onChange={this.handleChange} type="text" placeholder="请输入内容"/>
}
});
var MyButtonComponent=React.createClass({
handleClick:function(){
alert(this.props.MyValue)
},
render:function () {
return <input onClick={this.handleClick} type="button" value="clickMe"/>
}
});
var MyMainComponent=React.createClass({
getInitialState:function () {
return {userMsg:''}
} ,
save:function(msg){
console.log("子组件传来的值"+msg);
this.setState({userMsg:msg});
},
render:function () {
return <div>
<MyInputComponent ref="UserInput" funcSave={this.save}></MyInputComponent>
<br/>
<MyButtonComponent MyValue={this.state.userMsg}></MyButtonComponent>
<h1>{this.state.userMsg}</h1>
</div>
}
});
ReactDOM.render(
<MyMainComponent></MyMainComponent>,
document.getElementById("container")
)
</script>
将参数绑定getInitialState函数中,
getInitialState:function () {
return {userMsg:’’}
}
然后通过
this.setState({userMsg:msg},function(){})改变参数内容
最后通过
this.state.userMsg
来读取参数
context特性
记住一串单词组合getChildContextTypes
前3个、后3个、后两个
一个方法、两个静态属性