zoukankan      html  css  js  c++  java
  • React 之React.createContext

    使用Context,可以跨越组件进行数据传递

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    const ThemeContext = React.createContext({
      background: 'red',
      color: 'white'
    });

    通过静态方法React.createContext()创建一个Context对象,这个Context对象包含两个组件,<Provider /><Consumer />

    class App extends React.Component {
      render () {
        return (
          <ThemeContext.Provider value={{background: 'green', color: 'white'}}>
            <Header />
          </ThemeContext.Provider>
        );
      }
    }

    <Provider />value相当于现在的getChildContext()

    class Header extends React.Component {
      render () {
        return (
          <Title>Hello React Context API</Title>
        );
      }
    }
     
    class Title extends React.Component {
      render () {
        return (
          <ThemeContext.Consumer>
            {context => (
              <h1 style={{background: context.background, color: context.color}}>
                {this.props.children}
              </h1>
            )}
          </ThemeContext.Consumer>
        );
      }
    }

    <Consumer />children必须是一个函数,通过函数的参数获取<Provider />提供的Context

    参考自:https://www.jianshu.com/p/eba2b76b290b

    此文仅为鄙人学习笔记之用,朋友你来了,如有不明白或者建议又或者想给我指点一二,请私信我。liuw_flexi@163.com/QQ群:582039935. 我的gitHub: (学习代码都在gitHub) https://github.com/nwgdegitHub/
  • 相关阅读:
    Android TTS
    观察者模式(C++实现)
    android 8未知来源app安装
    NotificationChannel
    java底层知识
    Java14
    数据库分区、分库分表
    二叉搜索树的第k大节点
    从上到下按层打印二叉树
    springcloud面试知识点
  • 原文地址:https://www.cnblogs.com/liuw-flexi/p/11652688.html
Copyright © 2011-2022 走看看