React组件通讯的三种方式
1,父子组件传值(props)
2,兄弟组件传值(props)
3,跨组件传值(createContext )
使用props传值 我们需要注意这三点:
- 单向数据流(自上而下,当父组件的传过来的数据在父组件内发生了变化,子组件也会改变,子不能修改父)
- 只读的(只能读,不能修改 ,谁传过来的数据就在谁的组件里修改)
- 可以传递任何数据(对象,数组,函数,jsx…)
porps的基本用法:
1.父子组件通讯
1-1父传子
目标:把父组件里的num 传给子使用
父组件:
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
// 引入子组件
import Son from './Son'
export default class Parent extends Component {
state = {
num: 10
}
render () {
return (
<div>
<h1>父组件</h1>
<hr />
//把num传给子组件 子组件通过props.number使用
<Son number={this.state.num} />
</div>
)
}
}
ReactDOM.render(<Parent />, document.getElementById('root'))
子组件:
/* eslint-disable react/prop-types */
import React, { Component } from 'react'
export default class Son extends Component {
render () {
return (
<div>
<h2>子组件</h2>
//通过props可以拿到父传过来的参数
<h3>接收的值{this.props.number}</h3>
</div>
)
}
}
这样就完成了父传子
1-2子传父
利用回调函数父组件传递一个回调函数给子 ,子组件调用,将要传递的数据作为回调函数的参数
父组件:
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
// 引入子组件
import Son from './Son'
export default class Parent extends Component {
// 定义回调 num接收子的参数
fnp = (num) => {
// 控制台打印子传过来的数据
console.log('子传过来的参数', num)
}
render () {
return (
<div>
<h1>父组件</h1>
<hr />
{/* 把回调作为参数传给子 */}
<Son fns={this.fnp} />
</div>
)
}
}
ReactDOM.render(<Parent />, document.getElementById('root'))
子组件:
import React, { Component } from 'react'
export default class Son extends Component {
btn = () => {
// 通过回调把10086传给父
this.props.fns(10086)
}
render () {
console.log('props', this.props)
return (
<div>
<h2>子组件</h2>
//绑定事件-调用父的回调
<button onClick={this.btn}>点击把值传给父</button>
</div>
)
}
}
效果:
2.兄弟组件通讯
在React看来 兄弟组件传值 是一个伪命题 所以这里我们用到状态提升,而不是像Vue一样兄弟组件通过Bus当中间组件
状态提升:
- 将共享状态(数据)提升到最近的公共父组件中,由公共父组件管理这个状态。
- 要通讯的子组件只需通过 props 接收状态或操作状态的方法