react的子父组件传递参数
父组件在state的状态下设置
getInitialState(){
return{
childNameA:"小样,你好吗?",
childNameB:'小样,我不好!!',
item:[
],
time:0
}
子组件用props属性来接收
<p >子组件{this.props.name}</p>
完成的代码:父组件代码
import React from 'react';
import ReactDOM from 'react-dom';
import './commopent/childa/index';
import './index.css';
var ChildA=require('./commopent/childa/index'),
ChildB=require('./commopent/childb/index')
var App=React.createClass({
getInitialState(){
return{
childNameA:"小样,你好吗?",
childNameB:'小样,我不好!!',
item:[
],
time:0
}
},
render(){
return(
<div>
<h3 className='app'>组件化开发</h3>
<button onClick={this.plus}>{this.state.time}</button>
<ChildA name={this.state.childNameA} plus={this.plus} time={this.state.time}/>
<ChildB name={this.state.childNameB} items={this.state.item}/>
</div>
)
},
plus:function () {
var plaus=this.state.time;
plaus++;
var items=this.state.item;
items.push('user click')
this.setState({
time:plaus,
item:items
})
}
})
ReactDOM.render(
<App />,
document.getElementById('root')
);
子组件A的代码
import React from 'react';
import './child1.css'
var ChildA=React.createClass({
getInitialState(){
return{
name:'小样'
}
},
render(){
return(
<div className='child'>
<p >子组件{this.props.name}</p>
<input type="text" value={this.state.name} onChange={this.change}/>
{this.state.name}
<button id="btn">原生事件</button>
{/*<button onClick={this.hanldClick}>{this.state.times}</button>*/}
<button onClick={this.props.plus}>{this.props.time}</button>
</div>
)
},
change:function (e) {
this.setState({
name:e.target.value
})
},
// hanldClick:function () {
// var times=this.state.times;
// times++;
// this.setState({
// times:times
// })
// },
componentDidMount:function () {
// var btn= document.querySelector("#btn");
// btn.onclick=function () {
// alert("原生事件!!")
// }
}
})
module.exports=ChildA;
子组件B的代码
import React from 'react';
import './child.css'
var ChildB=React.createClass({
render(){
var value=this.props.items.map(function (o,i) {
return(
<li>{o}+{i}</li>
)
})
return(
<div className='child'>
<p>子组件{this.props.name}</p>
<ul>
{value}
</ul>
</div>
)
}
})
module.exports=ChildB
实现效果如下:
![在这里输入图片标题 输入图片说明](https://static.oschina.net/uploads/img/201703/13220140_T3x9.png)