跨级组件之间的通信
所谓跨级组件通信,就是父组件向子组件的子组件通信,向更深层的子组件通信。跨级组件通信可以采用下面两种方式:
1.使用props一层层往下传
2.使用context。
我们这里着重讲context的用法
使用 context 需要注意以下条件:
1.上级组件要声明自己支持context,并提供一个函数来返回相应的context对象
2.子组件要声明自己需要使用context,并提供其需要使用的context属性的PropTypes
3.父组件需提供一个 getChildContext 函数,以返回一个初始的 context 对象
如果组件中使用构造函数(constructor),还需要在构造函数中传入第二个参数 context,并在 super 调用父类构造函数是传入 context,否则会造成组件中无法使用 context
constructor(props,context){ super(props,context);}
1.声明自己支持的context,并且提供context中属性的PropType.
声明:
import React,{component} from 'react';
import PropTypes from 'prop-type';
import child from './child'
import './app.css'
export default class App extends Component{
static childContextTypes={
name: PropTypes.string,
getData:PropTypes.func
}
提供一个getChildContext函数,返回一个初始化的context对象
getChildContext() {
return {
name:this.state.name,
getData:this.callback.bind(this)
}
}
3. 回调函数
callback(data){
console.log(data)
}
}
子组件:
import React ,{component} from “react”
import PropTypes from “pros-types”
export default class Subsub extends Component{
1.声明自己需要使用context
static contextTypes={
color: PropTypes.string,
getData:PropTypes.func
}
render(){
const styel = {coloe:this.context.color}
const box = (msg)=>{
return ()=>{
this.context.getData(msg)
}
}
return (
child<button onclick={box(“cansd)”}>点击我
)
}
订阅事件通信
npm install --save events
新建一个ev.js,引入events包,并向外提供一个实事件对象,供通信时使用
import {EventEmitter} from ‘events’
export default new EventEmitter
app.js
import React, {Component}from ‘react’
import A from ‘./a’
import B from './b
export defalut class App fextends Component{
render(){
}
}
A.js
import Emitter from ‘./ev.js’
import React {Component} from ‘react’
export default class A extends Component{
constructor(props) {
super(props)
this.state = {
msg:null
}
}
componentDidmount(){
this.eventEmitter = emitter.addListener(“callme”,(msg)=>{
this.setState({
msg
})
})
}
componentWillUnmount(){
emitter.removeListener(this.eventEmitter)
}
render(){
return(
)
}
}
B.js
import React ,{Component} from ‘react’
import emitter from ‘./ev’
export default class B extends Component{
render(){
const box = (msg)=>{
return (msg)=>{
emitter.emit(“callme”,“Hello”)
}
}
return(<div onCloick = {box(“blue”)}>)
}
}
3.redux组件间通信原理