React組件間通信

在 React.js 中,數(shù)據(jù)是從上自下流動(傳遞)的,也就是一個父組件可以把它的 state / props 通過 props 傳遞給它的子組件,但是子組件不能修改 props - React.js 是單向數(shù)據(jù)流,如果子組件需要修改父組件狀態(tài)(數(shù)據(jù)),是通過回調(diào)函數(shù)方式來完成的。

1.父級向子級通信

把數(shù)據(jù)添加子組件的屬性中,然后子組件中從props屬性中,獲取父級傳遞過來的數(shù)據(jù)。

2.子級向父級通信

在父級中定義相關(guān)的數(shù)據(jù)操作方法(或其他回調(diào)), 把該方法傳遞給子級,在子級中調(diào)用該方法父級傳遞消息。

3.跨組件通信

1.創(chuàng)建context對象

React.createContext(defaultValue);
{ Consumer, Provider } = createContext(defaultValue)

context.js

import {createContext} from "react";

const context = createContext();
const {Provider,Consumer} = context;

export {Provider,Consumer}
export default context;

2.在父組件調(diào)用 Provider 傳遞數(shù)據(jù)

Context.Provider,使用value傳遞數(shù)據(jù)

import { Component } from "react";
import Contatiner from "./container";
import context,{Provider} from "./context";
class App extends Component {
  render() {
    const {showName,nub} = this.state;
    return <div>
        <Provider
          value={{
            showName,nub
          }}
        >
          <Contatiner />
        </Provider>
    </div>
  }
}
export default App;

3.接收數(shù)據(jù)
方法一:使用類屬性contextType

class.contextType = Context;
static contextType = Context;
從this.context中獲取;

import { Component } from "react";
import context from "./context";
class Name extends Component {
  static contextType = context;
  render(){
    const {showName} = this.context;
    return <>
        <p>{showName}</p>
    </>
  }
}

export default Name;

方法二:使用Consumer

Context.Consumer,從參數(shù)中獲取

import { Component } from "react";
import {Consumer} from "./context";
export default class Nub extends Component {
  render(){
    return <Consumer>
        {({nub})=>{
          return <p>{nub}</p>
        }}
      </Consumer>
  }
}

注意:在使用不熟練時,最好不要在項(xiàng)目中使用 context,context一般給第三方庫使用

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 父子間組件通信 父結(jié)點(diǎn)數(shù)據(jù)傳遞給子組件 通過 props進(jìn)行傳遞,子組件只能用于展示或者判斷,但不能進(jìn)行更新當(dāng)子組...
    郭仙人不是閑人閱讀 792評論 0 0
  • 不借助redux等狀態(tài)管理工具的React組件間的通信解決方法 組件通信分類 React組件間通信分為2大類,3種...
    Lethe35閱讀 272評論 0 0
  • React 開發(fā)模式是組件化開發(fā), 所以組件間的信息傳遞就尤為重要,React傳遞數(shù)據(jù)的方式主要有3種。 prop...
    蠻吉大人123閱讀 133評論 0 0
  • 1. 組件間通信1.1.父組件向子組件通信1.2.子組件向父組件通信1.3.跨級組件間通信1.4.無嵌套關(guān)系組件間...
    愛吃芋圓的小w閱讀 469評論 0 2
  • 組件間不同的嵌套關(guān)系,會導(dǎo)致不同的通信方式。常見的有:父組件向子組件通信、子組件向父組件通信、沒有嵌套關(guān)系的組件之...
    南風(fēng)知我意ZD閱讀 1,362評論 0 0

友情鏈接更多精彩內(nèi)容