在使用 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> ); }
}