美文网首页
React 拾遗之 Context

React 拾遗之 Context

作者: 隐号骑士 | 来源:发表于2018-12-09 16:46 被阅读6次

React 拾遗之 Context

React.js 的 context 其实像就是组件树上某颗子树的全局变量

  • 使用方法

new ( React 16.3 之后的版本适用 )


// context.js
export const ThemeContext = React.createContext({
  background: 'red',
  color: 'white'
});

// App.js
import {ThemeContext} from './context.js'

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

// some child Component
import {ThemeContext} from './context.js'

class ChildComponent extends React.Component {
  render () {
    return (
      <ThemeContext.Consumer>
        {context => (
          <h1 style={{background: context.background, color: context.color}}>
            {this.props.children}
          </h1>
        )}
       </ThemeContext.Consumer>
    )
  }
}

old ( React 17 以后将废除 )


// App.js

import React, { Component } from 'react';
import PropTypes from 'prop-types'

class App extends Component {
  constructor() {
    super()
    this.state = {
      number: 1,
      text: ''
    }
  }

  static childContextTypes = {
    globalNumber: PropTypes.number,
    globalText: PropTypes.string,
  }

  getChildContext() {
    return {
      globalNumber: this.state.number,
      globalText: this.state.text
    }
  }

  render() {
    return (
        <div>
            {/*some extra components*/}
        </div>
    );
  }
}

// some child Component

class ChildComponent extends Component {
    constructor() {
        super()
    }
    static contextTypes = {
        globalNumber: PropTypes.number
    }
    render() {
        <span>{this.context.globalNumber}</span>
    }
}

相关文章

  • React 拾遗之 Context

    React 拾遗之 Context React.js 的 context 其实像就是组件树上某颗子树的全局变量 使...

  • 2018-08-08

    React 高级指南 React 新版上下文(context) context ?答:上下文(Context) 提...

  • React 16 拾遗目录

    React 拾遗 React 拾遗:React 项目脚手架 如何安装 React 项目启动的前置依赖:Node.j...

  • React 之 Context API(二)

    一、前言 在《React 之 Context API(一)[https://www.jianshu.com/p/4...

  • React中不常用的功能——Context

    React中不常用的功能——Context Context React源码版本16.8 基本用法 跨层级通信 Co...

  • 012|React之Context

    假设有层级 A->B->C->D,如果A需要传递一个参数给D,根据前文的知识,只能通过props参数一层一层传递。...

  • react 之Context理解

    通常情况下,在react组件中,我们可以通过props很清楚的知道哪些数据被传递,但是在一些特定的场景下,我们不想...

  • 疑问汇总

    1. react context是怎样实现 跨组件通信的? 从Context源码实现谈React性能优化[http...

  • React扩展之Fragment&Context&PureCom

    Fragment Context PureComponent 点赞加关注,永远不迷路 上一篇:React扩展之懒加...

  • react context

    react context React.createContext, Provider(数据提供者), Consu...

网友评论

      本文标题:React 拾遗之 Context

      本文链接:https://www.haomeiwen.com/subject/nykkhqtx.html