关于react组件之间的通信

时间:2021-11-17 13:48:59
才开始学react刚好到组件通信这一块,就简单的记录下
组件间的通信方式:父到子:props、context,子到父:自定义事件、回调,兄弟组件:共父props传递、自定义事件
import React, { Component } from 'react';
import './ChatRoom.css';
import PropTypes from "prop-types";
import emitter from '../../utils/event' // 要安装event包 cnpm install events --save //event.js为:
//import { EventEmitter } from "events";
//export default new EventEmitter();
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子集列表</button>
<Child1 show={this.state.show} func={this.toggle}></Child1>
</div>
)
}
}
export defaultTest;
这些都是简单的组件通信、复杂的通信还是要用到redux,关于redux还没开始研究,后续会继续。