zoukankan      html  css  js  c++  java
  • 【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>
        )
      }
    }
  • 相关阅读:
    jQuery源码笔记——四
    jQuery源码笔记——三
    jQuery源码笔记——二
    深度理解作用域链和闭包
    事务的传播机制
    Jvm的运行时数据区
    SpringBoot 工程结构
    MyBatis的<if>标签判空
    Redis学习
    MyBatis调用Oracle的存储过程
  • 原文地址:https://www.cnblogs.com/nanianqiming/p/10714477.html
Copyright © 2011-2022 走看看