1. 程式人生 > >React 中組件間通信的幾種方式

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

沒有 emit ack cto const fault listener exp 組件通信

在使用 React 的過程中,不可避免的需要組件間進行消息傳遞(通信),組件間通信大體有下面幾種情況:

  1. 父組件向子組件通信
  2. 子組件向父組件通信
  3. 非嵌套組件間通信
  4. 跨級組件之間通信

1.父組件向子組件通信
父組件通過向子組件傳遞 props,子組件得到 props 後進行相應的處理。
演示代碼:
父組件 parent.js:


import React,{ Component } from "react";

export default class App extends Component{

    render(){
        return(
            <div>
                <Sub title = "111111" />
            </div>
        )
    }
}
子組件 child.js:

import React from "react";

class Child extends React.component{


construtor(props){
 super(props)
 this.state = {}
}
render(){
    return(
        <h1>
            { props.title}
        </h1>
    )
}

}

export default Child;


**2.子組件向父組件通信**
利用回調函數,實現子組件向父組件通信:父組件將一個函數作為 props 傳遞給子組件,子組件調用該回調函數.即可
演示代碼:
child.js

import React from "react";

class Child extends React.component{


construtor(props){
 super(props)
 this.state = {}
}
cb = (msg) => {
      return () => {
        props.callback(msg);
    }
}
render(){
    return(
         <div>
            <button onClick = { this.cb("通信") }>點擊我</button>
        </div>
    )
}

}

export default Child;


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>
    );
}

}

原文地址:https://segmentfault.com/a/1190000016647850

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