React 中組件間通訊的幾種方式

在使用 React 的過程當中,不可避免的須要組件間進行消息傳遞(通訊),組件間通訊大致有下面幾種狀況:javascript

  • 父組件向子組件通訊css

  • 子組件向父組件通訊java

  • 跨級組件之間通訊react

  • 非嵌套組件間通訊npm

下面依次說下這幾種通訊方式。redux

父組件向子組件通訊

這是最簡單也是最經常使用的一種通訊方式:父組件經過向子組件傳遞 props,子組件獲得 props 後進行相應的處理。
下面是演示代碼:
父組件 App.js:ide

import React,{ Component } from "react";
import Sub from "./SubComponent.js";
import "./App.css";
export default class App extends Component{

    render(){        
            return(            
                <div>
                <Sub title = "今年過節不收禮" />
            </div>
        )
    }
}

子組件 SubComponent.js:函數

import React from "react";
const Sub = (props) => {    
                return(       
                 <h1>
                { props.title }  
            </h1>
    )
}
export default Sub;

子組件向父組件通訊

利用回調函數,能夠實現子組件向父組件通訊:父組件將一個函數做爲 props 傳遞給子組件,子組件調用該回調函數,即可以向父組件通訊。
下面是演示代碼:
SubComponent.js:工具

import React from "react";
const Sub = (props) => {  
  const cb = (msg) => {  
        return () => {
            props.callback(msg)
        }
    }    
    return(        
            <div>
            <button onClick = { cb("咱們通訊把") }>點擊我</button>
        </div>
    )
}
export default Sub;

App.js:this

import React,{ Component } from "react";
import Sub from "./SubComponent.js";
import "./App.css";
export default class App extends Component{
    callback(msg){       
             console.log(msg);
       }
    render(){        
             return(          
                  <div>
                <Sub callback = { this.callback.bind(this) } />
            </div>
        )
    }
}

跨級組件通訊

所謂跨級組件通訊,就是父組件向子組件的子組件通訊,向更深層的子組件通訊。跨級組件通訊能夠採用下面兩種方式:

  • 中間組件層層傳遞 props

  • 使用 context 對象

對於第一種方式,若是父組件結構較深,那麼中間的每一層組件都要去傳遞 props,增長了複雜度,而且這些  props 並非這些中間組件本身所須要的。不過這種方式也是可行的,當組件層次在三層之內能夠採用這種方式,當組件嵌套過深時,採用這種方式就須要斟酌了。
使用 context 是另外一種可行的方式,context 至關於一個全局變量,是一個大容器,咱們能夠把要通訊的內容放在這個容器中,這樣一來,無論嵌套有多深,均可以隨意取用。
使用 context 也很簡單,須要知足兩個條件:

  • 上級組件要聲明本身支持 context,並提供一個函數來返回相應的 context 對象

  • 子組件要聲明本身須要使用 context

下面以代碼說明,咱們新建 3 個文件:父組件 App.js,子組件 Sub.js,子組件的子組件 SubSub.js。
App.js:

import React, { Component } from 'react';
import PropTypes from "prop-types";
import Sub from "./Sub";import "./App.css";
export default class App extends Component{   
         // 父組件聲明本身支持 context
    static childContextTypes = {
            color:PropTypes.string,
           callback:PropTypes.func,
    }    // 父組件提供一個函數,用來返回相應的 context 對象
    getChildContext(){      
      return{      
            color:"red",   
             callback:this.callback.bind(this)
        }
    }

    callback(msg){        
               console.log(msg)
    }

    render(){        
          return(           
             <div>
                <Sub></Sub>
            </div>
        );
    }
}

Sub.js:

import React from "react";
import SubSub from "./SubSub";
const Sub = (props) =>{   
         return(        
               <div>
            <SubSub />
        </div>
    );
}
export default Sub;

SubSub.js:

import React,{ Component } from "react";
import PropTypes from "prop-types";
export default class SubSub extends Component{ 
   // 子組件聲明本身須要使用 context
    static contextTypes = {     
       color:PropTypes.string,      
       callback:PropTypes.func,
    }
    render(){      
      const style = { color:this.context.color }     
         const cb = (msg) => {   
                  return () => {     
                             this.context.callback(msg);
                        }
            }       
             return(    
                     <div style = { style }>
                        SUBSUB               
                 <button onClick = { cb("我胡漢三又回來了!") }>點擊我</button>
            </div>
        );
    }
}

若是是父組件向子組件單向通訊,可使用變量,若是子組件想向父組件通訊,一樣能夠由父組件提供一個回調函數,供子組件調用,回傳參數。
在使用 context 時,有兩點須要注意:

  • 父組件須要聲明本身支持 context,並提供 context 中屬性的 PropTypes

  • 子組件須要聲明本身須要使用 context,並提供其須要使用的 context 屬性的 PropTypes

  • 父組件需提供一個 getChildContext 函數,以返回一個初始的 context 對象

若是組件中使用構造函數(constructor),還須要在構造函數中傳入第二個參數 context,並在 super 調用父類構造函數是傳入 context,不然會形成組件中沒法使用 context

...
constructor(props,context){ 
     super(props,context);
}
...

改變 context 對象

咱們不該該也不能直接改變 context 對象中的屬性,要想改變 context 對象,只有讓其和父組件的 state 或者 props 進行關聯,在父組件的 state 或 props 變化時,會自動調用 getChildContext 方法,返回新的 context 對象,然後子組件進行相應的渲染。
修改 App.js,讓 context 對象可變:

import React, { Component } from 'react';
import PropTypes from "prop-types";
import Sub from "./Sub";import "./App.css";
export default class App extends Component{  
  constructor(props) {        
      super(props);        
      this.state = {           
           color:"red"
        };
    }    // 父組件聲明本身支持 context
    static childContextTypes = {    
        color:PropTypes.string,  
        callback:PropTypes.func,
    }    // 父組件提供一個函數,用來返回相應的 context 對象
    getChildContext(){     
       return{          
          color:this.state.color,     
          callback:this.callback.bind(this)
        }
    }    // 在此回調中修改父組件的 state
    callback(color){       
         this.setState({
            color,
        })
    }

    render(){  
          return(  
            <div>
                <Sub></Sub>
            </div>
        );
    }
}

此時,在子組件的 cb 方法中,傳入相應的顏色參數,就能夠改變 context 對象了,進而影響到子組件:

...
return(   
     <div style = { style }>
        SUBSUB  
       <button onClick = { cb("blue") }>點擊我</button>
    </div>);
...

context 一樣能夠應在無狀態組件上,只需將 context 做爲第二個參數傳入:

import React,{ Component } from "react";
import PropTypes from "prop-types";
const SubSub = (props,context) => {  
      const style = { color:context.color }   
     const cb = (msg) => {      
     return () => {
            context.callback(msg);
        }
    }    return(     
                   <div style = { style }>
               SUBSUB         
            <button onClick = { cb("我胡漢三又回來了!") }>點擊我</button>
        </div>
    );
}

SubSub.contextTypes = {   
    color:PropTypes.string,   
  callback:PropTypes.func,
}
export default SubSub;

非嵌套組件間通訊

非嵌套組件,就是沒有任何包含關係的組件,包括兄弟組件以及不在同一個父級中的非兄弟組件。對於非嵌套組件,能夠採用下面兩種方式:

  • 利用兩者共同父組件的 context 對象進行通訊

  • 使用自定義事件的方式

若是採用組件間共同的父級來進行中轉,會增長子組件和父組件之間的耦合度,若是組件層次較深的話,找到兩者公共的父組件不是一件容易的事,固然仍是那句話,也不是不能夠...
這裏咱們採用自定義事件的方式來實現非嵌套組件間的通訊。
咱們須要使用一個 events 包:

npm install events --save

新建一個 ev.js,引入 events 包,並向外提供一個事件對象,供通訊時使用:

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

App.js:

import React, { Component } from 'react';
import Foo from "./Foo";
import Boo from "./Boo";
import "./App.css";
export default class App extends Component{
    render(){      
     return(         
            <div>
                <Foo />
                <Boo />
            </div>
        );
    }
}

Foo.js:

import React,{ Component } from "react";
import emitter from "./ev"
export default class Foo 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 }
                我是非嵌套 1 號       
               </div>
        );
    }
}

Boo.js:

import React,{ Component } from "react";
import emitter from "./ev"
export default class Boo extends Component{
    render(){      
      const cb = (msg) => {      
            return () => {                // 觸發自定義事件
                emitter.emit("callMe","Hello")
            }
        }        return(    
                <div>
                我是非嵌套 2 號            
                <button onClick = { cb("blue") }>點擊我</button>
            </div>
        );
    }
}

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

總結

本文總結了 React 中組件的幾種通訊方式,分別是:

  • 父組件向子組件通訊:使用 props

  • 子組件向父組件通訊:使用 props 回調

  • 跨級組件間通訊:使用 context 對象

  • 非嵌套組件間通訊:使用事件訂閱

事實上,在組件間進行通訊時,這些通訊方式均可以使用,區別只在於使用相應的通訊方式的複雜程度和我的喜愛,選擇最合適的那一個。好比,經過事件訂閱模式通訊不止能夠應用在非嵌套組件間,還能夠用於跨級組件間,非嵌套組件間通訊也可使用 context 等。關鍵是選擇最合適的方式。
固然,本身實現組件間的通訊仍是太難以管理了,所以出現了不少狀態管理工具,如 flux、redux 等,使用這些工具使得組件間的通訊更容易追蹤和管理。

完。

原地址連接:https://www.jianshu.com/p/fb915d9c99c4

相關文章
相關標籤/搜索