【react】---context的基本使用新版---【巷子】


一、全局定義context對象


  globalContext.js

import React from "react";
const GlobalContext = React.createContext();
export default GlobalContext;

 

二、根組件引入GlobalContext,並使用GlobalContext.Provider(生產者)

 

import React, { Component ,Fragment} from 'react';
import One from "./components/one";
import GlobalContext from "./globalContext";

class App extends Component {
  render() {
    return (
      <GlobalContext.Provider
        value={{
          name:"zhangsan",
          age:19
        }}
      >
      <One/>
      </GlobalContext.Provider>
    );
  }
}

export default App;

 三、組件引入GlobalContext並調用context,使用GlobalContext.Consumer

  

import React, { Component } from 'react'
import GlobalContext from "../globalContext";
export default class One extends Component {
 
  render() {
    return (
      <GlobalContext.Consumer>
      {
        context => {
            console.log(context)
          return (
            <div>
                <h2>{context.name}</h2> 
                <h2>{context.age}</h2>
            </div>
          )
        }
      }
      </GlobalContext.Consumer>
    )
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM