前端之家收集整理的这篇文章主要介绍了
前端那些事之react篇--子父组件传递,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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:"小样,你好吗?",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://www.f2er.com/react/304612.html