React中組件通訊的幾種方式

http://www.javashuo.com/article/p-vrnlbbhk-dz.htmljavascript

 

須要組件之進行通訊的幾種狀況

  • 父組件向子組件通訊
  • 子組件向父組件通訊
  • 跨級組件通訊
  • 沒有嵌套關係組件之間的通訊

1. 父組件向子組件通訊

React數據流動是單向的,父組件向子組件通訊也是最多見的;父組件經過props向子組件傳遞須要的信息
Child.jsxjava

import React from 'react'; import PropTypes from 'prop-types'; export default function Child({ name }) { return <h1>Hello, {name}</h1>; } Child.propTypes = { name: PropTypes.string.isRequired, }; 

Parent.jsxreact

import React, { Component } from 'react'; import Child from './Child'; class Parent extends Component { render() { return ( <div> <Child name="Sara" /> </div> ); } } export default Parent; 

2. 子組件向父組件通訊

  • 利用回調函數
  • 利用自定義事件機制

回調函數

實如今子組件中點擊隱藏組件按鈕能夠將自身隱藏的功能npm

List3.jsxsegmentfault

import React, { Component } from 'react'; import PropTypes from 'prop-types'; class List3 extends Component { static propTypes = { hideConponent: PropTypes.func.isRequired, } render() { return ( <div> 哈哈,我是List3 <button onClick={this.props.hideConponent}>隱藏List3組件</button> </div> ); } } export default List3; 

App.jsx瀏覽器

import React, { Component } from 'react'; import List3 from './components/List3'; export default class App extends Component { constructor(...args) { super(...args); this.state = { isShowList3: false, }; } showConponent = () => { this.setState({ isShowList3: true, }); } hideConponent = () => { this.setState({ isShowList3: false, }); } render() { return ( <div> <button onClick={this.showConponent}>顯示Lists組件</button> { this.state.isShowList3 ? <List3 hideConponent={this.hideConponent} /> : null } </div> ); } } 

觀察一下實現方法,能夠發現它與傳統回調函數的實現方法同樣.並且setState通常與回調函數均會成對出現,由於回調函數便是轉換內部狀態是的函數傳統;app

3. 跨級組件通訊

  • 層層組件傳遞props
例如A組件和B組件之間要進行通訊,先找到A和B公共的父組件,A先向C組件通訊,C組件經過props和B組件通訊,此時C組件起的就是中間件的做用
  • 使用context
context是一個全局變量,像是一個大容器,在任何地方均可以訪問到,咱們能夠把要通訊的信息放在context上,而後在其餘組件中能夠隨意取到;
可是React官方不建議使用大量context,儘管他能夠減小逐層傳遞,可是當組件結構複雜的時候,咱們並不知道context是從哪裏傳過來的;並且context是一個全局變量,全局變量正是致使應用走向混亂的罪魁禍首.

使用context

下面例子中的組件關係: ListItem是List的子組件,List是app的子組件ide

ListItem.jsx函數

import React, { Component } from 'react'; import PropTypes from 'prop-types'; class ListItem extends Component { // 子組件聲明本身要使用context static contextTypes = { color: PropTypes.string, } static propTypes = { value: PropTypes.string, } render() { const { value } = this.props; return ( <li style={{ background: this.context.color }}> <span>{value}</span> </li> ); } } export default ListItem; 

List.jsxui

import ListItem from './ListItem'; class List extends Component { // 父組件聲明本身支持context static childContextTypes = { color: PropTypes.string, } static propTypes = { list: PropTypes.array, } // 提供一個函數,用來返回相應的context對象 getChildContext() { return { color: 'red', }; } render() { const { list } = this.props; return ( <div> <ul> { list.map((entry, index) => <ListItem key={`list-${index}`} value={entry.text} />, ) } </ul> </div> ); } } export default List; 

App.jsx

import React, { Component } from 'react'; import List from './components/List'; const list = [ { text: '題目一', }, { text: '題目二', }, ]; export default class App extends Component { render() { return ( <div> <List list={list} /> </div> ); } }

4. 沒有嵌套關係的組件通訊

  • 使用自定義事件機制
在componentDidMount事件中,若是組件掛載完成,再訂閱事件;在組件卸載的時候,在componentWillUnmount事件中取消事件的訂閱;
以經常使用的發佈/訂閱模式舉例,借用Node.js Events模塊的瀏覽器版實現

使用自定義事件的方式

下面例子中的組件關係: List1和List2沒有任何嵌套關係,App是他們的父組件;

實現這樣一個功能: 點擊List2中的一個按鈕,改變List1中的信息顯示
首先須要項目中安裝events 包:

npm install events --save

在src下新建一個util目錄裏面建一個events.js

import { EventEmitter } from 'events'; export default new EventEmitter();

list1.jsx

import React, { Component } from 'react'; import emitter from '../util/events'; class List extends Component { constructor(props) { super(props); this.state = { message: 'List1', }; } componentDidMount() { // 組件裝載完成之後聲明一個自定義事件 this.eventEmitter = emitter.addListener('changeMessage', (message) => { this.setState({ message, }); }); } componentWillUnmount() { emitter.removeListener(this.eventEmitter); } render() { return ( <div> {this.state.message} </div> ); } } export default List; 

List2.jsx

import React, { Component } from 'react'; import emitter from '../util/events'; class List2 extends Component { handleClick = (message) => { emitter.emit('changeMessage', message); }; render() { return ( <div> <button onClick={this.handleClick.bind(this, 'List2')}>點擊我改變List1組件中顯示信息</button> </div> ); } } 

APP.jsx

import React, { Component } from 'react'; import List1 from './components/List1'; import List2 from './components/List2'; export default class App extends Component { render() { return ( <div> <List1 /> <List2 /> </div> ); } }

自定義事件是典型的發佈訂閱模式,經過向事件對象上添加監聽器和觸發事件來實現組件之間的通訊

總結

  • 父組件向子組件通訊: props
  • 子組件向父組件通訊: 回調函數/自定義事件
  • 跨級組件通訊: 層層組件傳遞props/context
  • 沒有嵌套關係組件之間的通訊: 自定義事件
相關文章
相關標籤/搜索