react props传值示例
通过SonTwo点击事件触发Father中valindexChange方法(需要将方法传递到子组件中)
valindexChange(){}触发后调用setState({})来更新组件状态将最新的state值传递给SonOne。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./base/react.min.js"></script>
<script src="./base/react-dom.min.js"></script>
<script src="./base/browser.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type='text/babel'>
let Father = React.createClass({
getInitialState(){
return {
valOne:"Father传值SonOne",
valindex:0,
}
},
valindexChange(){
console.log(this.state.valindex)
this.setState({
valindex:++this.state.valindex
})
},
render(){
return(
<div>
<div>这里是father</div>
<SonOne val={this.state.valOne} index={this.state.valindex}></SonOne>
<SonTwo change={this.valindexChange.bind(this)}></SonTwo>
</div>
)
}
});
let SonOne = React.createClass({
getDefaultProps(){
//无法获取props undefined
console.log(this.props)
return{
xxx:1
}
},
render(){
//{val: "Father传值SonOne", index: 0, xxx: 1}
console.log(this.props)
return(
<div>这里是Son1--------{this.props.val}-----被SonTwo点击了{this.props.index}次</div>
)
}
});
let SonTwo = React.createClass({
render(){
return(
<div>
这里是Son2
<button onClick={this.props.change}>增加</button>
</div>
)
}
});
ReactDOM.render(<Father/>,app);
</script>
</body>
</html>
react ref,refs,props传值示例
值传递流程
通过SonTwo中的点击事件来触发addFalse()继而触发father中的change()继而触发SonTwo中的addTrue()方法并将SonOne中的State作为形参传递。
addTrue()将处理完的结果return出去,SonOne中的State接收更新,继而触发this.setState({})
<script type='text/babel'>
let Father = React.createClass({
change(){
//console.log(this,this.refs.SonOne,this.two);
this.refs.SonOne.state.valindex = this.two.addTrue(this.refs.SonOne.state.valindex);
console.log(this.refs.SonOne.state.valindex)
this.setState({})
},
render(){
return(
<div>
<div>这里是father</div>
<SonOne ref="SonOne"></SonOne>
<SonTwo ref={(el)=>{this.two=el}} change={this.change.bind(this)}></SonTwo>
{/*{this.change()}----切记不可直接调用方法,亲测在chage方法的this中可以看到two属性,但this.two仍然为空*/}
</div>
)
}
});
let SonOne = React.createClass({
getInitialState(){
return {
valindex:0,
}
},
render(){
return(
<div>这里是Son1--------被SonTwo点击了{this.state.valindex}次</div>
)
}
});
let SonTwo = React.createClass({
addFalse(){
this.props.change();
},
addTrue(val){
return ++val;
},
render(){
return(
<div>
这里是Son2
<button onClick={this.addFalse}>增加</button>
</div>
)
}
});
ReactDOM.render(<Father/>,app);
</script>