在使用 React 的过程当中,不可避免的须要组件间进行消息传递(通讯),组件间通讯大致有下面几种状况:react
1.父组件向子组件通讯
父组件经过向子组件传递 props,子组件获得 props 后进行相应的处理。
演示代码:
父组件 parent.js:npm
import React,{ Component } from "react"; export default class App extends Component{ render(){ return( <div> <Sub title = "111111" /> </div> ) } } 子组件 child.js:
import React from "react";app
class Child extends React.component{函数
construtor(props){ super(props) this.state = {} } render(){ return( <h1> { props.title} </h1> ) }
}this
export default Child;code
**2.子组件向父组件通讯** 利用回调函数,实现子组件向父组件通讯:父组件将一个函数做为 props 传递给子组件,子组件调用该回调函数.便可 演示代码: child.js
import React from "react";component
class Child extends React.component{对象
construtor(props){ super(props) this.state = {} } cb = (msg) => { this.props.callback(msg); } render(){ return( <div> <button onClick = { this.cb("通讯") }>点击我</button> </div> ) }
}事件
export default Child;rem
app.js
import React from "react";
export default class App extends React.Component{
callback(msg){ console.log(msg); } render(){ return( <div> <Sub callback = { this.callback.bind(this) } /> </div> ) }
}
**3.非嵌套组件间通讯** 非嵌套组件,就是没有任何包含关系的组件,包括兄弟组件以及不在同一个父级中的非兄弟组件 首先须要引入一个包events
npm install events --save
新建ev.js文件,引入 events 包,并向外提供一个事件对象,供通讯时使用
import { EventEmitter } from "events";
export default new EventEmitter();
app.js
import React, { Component } from 'react';
import childA from "./childA ";
import childB from "./childB";
export default class App extends Component{
render(){ return( <div> <childA /> <childB /> </div> ); }
}
childA
import React,{ Component } from "react";
import emitter from "./ev"
export default class ChildA 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( <div> { this.state.msg } child a </div> ); }
}
childB:
import React,{ Component } from "react";
import emitter from "./ev"
export default class ChildB extends Component{
render(){ const cb = (msg) => { return () => { // 触发自定义事件 emitter.emit("callMe","test") } } return( <div> childB <button onClick = { cb("blue") }>点击</button> </div> ); }
}