本文摘自PHP中文网,作者不言,侵删。
本篇文章给大家带来的内容是关于React组件通信的介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。最近闲来无事自学React框架,自学过程中所有的问题经验都会在此记录,希望可以帮助到学习React框架的同学,废话不多说上代码。
首先是父传子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import React, { Component } from 'react' ;
import Com1 from './componments/com1'
class App extends Component {
constructor(props){
super(props)
this.state = {
arr: [{
"userName" : "fangMing" , "text" : "123333" , "result" : true
}, {
"userName" : "zhangSan" , "text" : "345555" , "result" : false
}, {
"userName" : "liSi" , "text" : "567777" , "result" : true
}, {
"userName" : "wangWu" , "text" : "789999" , "result" : true
},]
};
this.foo = "我来自父组件"
};
render() {
return (
<div className= "App" >
<header className= "App-header" >
<img src={logo} className= "App-logo" alt= "logo" />
</header>
<Com1 age= "大卫" arr={this.state.arr} fn={this.foo}/>
</div>
);
}
}
export default App;
|
子组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import React, { Component } from 'react' ;
class Ele extends Component{
constructor(props){
super(props)
};
render(){
return (
<div>
<h1>Hello, {this.props.age}</h1>
<p>{this.props.fn}</p>
<ul>
{
this.props.arr.map(item => {
return (
<li key={item.userName}>
{item.userName} 评论是:{item.text}
</li>
)
})
}
</ul>
</div>
);
};
}
export default Ele;
|
结果显示:

以上是父传子的方法,主要还是使用props传值,下面看看子传父.
子传父:
首先是子组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import React, { Component } from 'react' ;
class Ele extends Component{
constructor(props){
super(props);
this.state = ({
childText: "我来自子组件"
})
};
clickFun(text) {
this.props.pfn(text)
}
render(){
return (
<div>
{
}
<button onClick={this.clickFun.bind(this, this.state.childText)}>
传值
</button>
</div>
);
};
}
export default Ele;
|
父组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import React, { Component } from 'react' ;
import Com1 from './componments/com1'
class App extends Component {
constructor(props){
super(props)
this.state = {
parentText: "现在是父组件" ,
};
fn(data) {
this.setState({
parentText: data
},() =>{
console.log(this.state.parentText);
});
};
render() {
return (
<div className= "App" >
<Com1 pfn={this.fn.bind(this)}/> { }
<p>text is {this.state.parentText}</p>
</div>
);
}
}
export default App;
|
以上是父子组件传值的方法,有不对的地方还望指正
还有兄弟组件传值还没学到,兄弟组件传值学到会更新上来
【相关推荐:React视频教程】
以上就是React组件通信的介绍(代码示例)的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
使用async属性异步加载执行javascript的方法
javascript怎么判断是否为对象
javascript怎么让div隐藏
javascript输出语句有哪些
javascript中的注释如何使用
详解javascript中的service workers!
javascript怎么清除cookie
利用jssdk在网页中获取地理位置
一个完整的html对象是什么样的,如何生成?
javascript怎么修改css
更多相关阅读请进入《javascript》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » React组件通信的介绍(代码示例)