Communication between react components

I just started to learn react just to the part of component communication, so I simply recorded 
the communication method between components: parent to child: props, context, child to parent: custom events, callbacks, sibling components: co-parent props transfer, customization Events
import React, { Component } from 'react';
import './ChatRoom.css';
import PropTypes from "prop-types";
import emitter from '../../utils/event' // To install the event package cnpm install events --save
class Test extends Component {
constructor () {
super(...arguments) this.state
={
show: true
}
this.toggle = this.toggle.bind(this)
}
static childContextTypes = {
color: PropTypes.string
}
getChildContext () {
return {
color: 'red'
}
}
toggle () {
this.setState({
show: !this.state.show
})
console.log(this.state.show)
}
render () {
class Child1 extends Component {
constructor () {
super(...arguments)
console.log(this.props)
this.state = {
show: this.props.show
}
}
componentDidMount () { // 添加事件的监听
this.eventEmitter = emitter.addListener('testEvent',(msg) => {
console.log(msg)
})
}
componentWillUnmount () { // 组件销毁前清除事件监听
emitter.removeListener(this.eventEmitter)
}
render () {
class Child2 extends Component {
constructor () {
super(...arguments)
console.log(this.props)
this.send = this.send.bind(this)
}
static contextTypes = {
color:PropTypes.string
}
send () {
emitter.emit('testEvent','send event')
}
render () {
const style = {
color: this.context.color
}
return (
<div style={style}>子子组件
<button onClick={this.send}>自定义事件</button>
</div>
)
}
}
return (
<div>
<button onClick={this.props.func}>child1</button>
{this.state.show?<div>child1list</div>:null}
<Child2></Child2>
</div>
)
}
}
return (
<div>
<button onClick={this.toggle}>toggle subset list</button>
<Child1 show={this.state.show} func={this.toggle}>< /Child1>
</div>
)
}
}
export defaultTest;
these are simple component communication, complex communication still use redux, the research on redux has not started, and will continue in the future.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326273669&siteId=291194637