React组件间通信

众所周知,ReactJS组件与组件之间的通信是一个难点。在React实际开发中,父子组件之间的传值是比较常见的,刚入门的小伙伴很容易被组件之间的通信绕懵。 今天花了点时间总结了一下React父子组件之间传值,和vue差不多的思路,父组件向子组件传值,父通过初始state,子组件通过this.props进行接收就可以了;子组件向父组件传值需要绑定一个事件,然后事件是父组件传递过来的this.props.event来进行值的更替。我下面将会用代码进行演示。

父组件向子组件传值:

将父组件的state通过props传入子组件

父组件:

import React, { Component } from 'react'
import Son from './Son'
export default class Father extends Component {
constructor(props) {
super(props);
this.state = {
msg :'我是父组件传过来的值--5'
}
}
render() {
let style02 = {
width:400,
height: 100,
backgroundColor: 'red'
}
return (
<div style={style02}>
<p>父组件</p>
<Son msg = {this.state.msg}/>
</div>
)
}
}

子组件:

import React, { Component } from 'react'
export default class Son extends Component {
render() {
let style01 = {
width:200,
height: 100,
margin: '0 auto',
backgroundColor: 'pink'
}
return (
<div>
<p style={style01}>子组件--- <br/><span>{this.props.msg}</span></p>
</div>
)
}
}

效果图:

React组件间通信

子组件向父组件传值:

记住这句话数据在哪,方法就定义在哪!!
子组件:

import React, { Component } from 'react'
export default class Son extends Component {
constructor(props) {
super();
this.state = {
msg:'我是子组件'
}
}
render() {
return (
<div>
<h1>我是子组件</h1>
<button onClick={()=>this.props.handleClick(this.state.msg)}>点击向父组件传值</button>
</div>
)
}
}

父组件:

import React, { Component } from 'react'
import Son from './Son'
export default class Father extends Component {
constructor(props) {
super(props);
this.state = {
msg :'我是父组件传过来的值--5'
}
}
handleClick=(msg)=> {
alert(`这是子组件通过调用父组件传递的方法接受到的msg:${msg}`)
}
render() {
return (
<div>
<Son handleClick = {this.handleClick}/>
</div>
)
}
}

效果:点击按钮向父组件传值。

React组件间通信

小结:首先感谢你把这篇博客看完,是不是很简单啊朋友们,哪里不明白的可以在评论区里留言,如果大家对文章有什么建议,欢迎指点。

上一篇:Math.round(),Math.ceil(),Math.floor()


下一篇:JavaScript的Math对象