非父子组件通信方式
状态提升(中间人模式)
也就是说,将多个组件需要共享的状态提升到他们最近的父组件上,然后互相通过父组件向对方传递props,从而实现非父子间的通信,这里的父组件也就起到了中间人的作用
发布订阅模式实现
数据的多级传递(context状态数传参)
通过使用context机制进行数据的多级传递 ,在context机制当中需要在子组件内设置静态属性contextTypes,同时在其内部通过prop-types模块去设置需要多级传递的数据的数据类型。然后就是要在上层组件的内部设置有静态属性childContextTypes,并在其内部设置与子组件contextTypes内部相同的数据以及数据类型,且在上层组件内部需要设置getChildContext()方法去获取子组件的上下文,同时去设置上下文的值。最后就是要在子组件内通过this.context.[属性]获取上层组件传递过来的数据
import React, { Component } from 'react'
import Fat from './Fat'
import PropTypes from 'prop-types'
/**
*
* 爷爷组件
*
*/
export default class FatSDie extends Component {
//设置childContextTypes
static childContextTypes={
name:PropTypes.string
}
state={
name:'112'
}
//获取设置子组件上下文
getChildContext(){
return{
name:this.state.name
}
}
render() {
return (
<div>
<Fat/>
</div>
)
}
}
import React, { Component } from 'react'
import Child from './Child'
/**
*
* 父亲组件
*
*/
export default class fat extends Component {
render() {
return (
<div>
<Child></Child>
</div>
)
}
}
import React, { Component } from 'react'
import PropTypes from 'prop-types'
/**
*
* 儿子组件
*
*/
export default class Child extends Component {
static contextTypes={
name:PropTypes.string
}
render() {
return (
<div>
{/* 获取上层组件传递的参数 */}
childName:{this.context.name}
</div>
)
}
}