網頁

2021/7/26

React Context傳遞參數

React使用Context在Components間傳遞參數。


簡介

React 16.3新增的Context API可將資料放入Context讓Component tree中各層Components直接取用,不用再透過props層層傳遞。

React原本從上層Component傳遞資料到下層Component得經過層層Components的props傳遞非常麻煩。例如下面有三個Component,從上到下為CharacterIntroStand。未使用Context從最上層Character傳遞名稱name到最下層Stand要透過Component的props。

App.js

mport "./App.css";

function App() {
  const name = 'DIO'
  return <Character name={name} />;
}

const Character = (props) => {
  return (
    <div>
      <h1>{props.name}</h1>
      <Intro name={props.name} />
    </div>
  );
};

const Intro = (props) => {
  return (
    <div>
      <p>{props.name} is the main antagonist of JoJo's Bizarre Part 3.</p>
      <Stand name={props.name}/>
    </div>
  )
};

const Stand = props => {
  return <div>{props.name}'s stand is <strong>The World</strong>.</div>
}

export default App;


使用Context


Class Component

下面改用Context在Class Components間共享資料。使用React.createContext(defaultValue)建立Context,傳入參數為Context的預設值。

使用Context.Providervalue設定要傳入Context的值。

在Component中設定static contextType為要取用的Context,則該Component中可以this.context取得Context傳遞的值。

App.js

import React from "react";

import "./App.css";

const CharacterContext = React.createContext(""); // default value is empty string

function App() {
  return (
    <CharacterContext.Provider value='DIO'>
      <Character />
    </CharacterContext.Provider>
  );
}

class Character extends React.Component {
  static contextType = CharacterContext;
  render() {
    return (
      <div>
        <h1>{this.context}</h1>
        <Intro />
      </div>
    );
  }
}

class Intro extends React.Component {
  static contextType = CharacterContext;
  render() {
    return (
      <div>
        <p>{this.context} is the main antagonist of JoJo's Bizarre Part 3.</p>
        <Stand />
      </div>
    );
  }
}

class Stand extends React.Component {
  static contextType = CharacterContext;
  render() {
    return (
      <div>
        {this.context}'s stand is <strong>The World</strong>.
      </div>
    );
  }
}

export default App;


Function Component

Function Component則用Hooks API useContext(Context)取得Context值。

App.js

import React, {useContext} from "react";

import "./App.css";

const CharacterContext = React.createContext("");

function App() {
  return (
    <CharacterContext.Provider value='DIO'>
      <Character />
    </CharacterContext.Provider>
  );
}

const Character = (props) => {
  const name = useContext(CharacterContext);
  return (
    <div>
      <h1>{name}</h1>
      <Intro />
    </div>
  );
};

const Intro = (props) => {
  const name = useContext(CharacterContext);
  return (
    <div>
      <p>{name} is the main antagonist of JoJo's Bizarre Part 3.</p>
      <Stand />
    </div>
  );
};

const Stand = (props) => {
  const name = useContext(CharacterContext);
  return (
    <div>
      {name}'s stand is <strong>The World</strong>.
    </div>
  );
};

export default App;



沒有留言:

張貼留言