Daily harvest
  • Introduction
  • First Chapter
  • vue初次尝试
  • Chrome Performance Tools
  • React
    • react摸索之context
    • ant design 自定义form双向绑定组件
  • Npm
    • 【译】如何防止权限错误
    • Npm-rebuild
  • 基础概念
    • my blind spot of console.log()
    • 从别人那儿新学到的关于 require 和 import 的隐藏知识
    • LRUCache.ts
    • foobar variables
  • Nodejs
    • 【译】使用JSON Web Tokens保护Node.js的RESTful Api
  • Tools
    • 新学到的linux命令
    • webstorm eslint8 报错
  • Python
    • Mac python 虚拟环境
  • Algorithm
    • LeetCode 第 1 题
Powered by GitBook
On this page

Was this helpful?

  1. React

react摸索之context

PreviousChrome Performance ToolsNextant design 自定义form双向绑定组件

Last updated 5 years ago

Was this helpful?

使用react过程中,经常有深层组件需要祖先组件的数据,但是中间层组件又不需要care这些数据,所以层级传递数据显得啰嗦,当然使用redux的话可以很明确的解决这个问题,本文讲述在不使用状态管理机的情况下的react的解决方法之——contex。并且在v16.3的react也会正式推出context的使用。

v16.3版本之前的contex一直被人诟病,而且官方文档也是三令五申谨慎使用contex。

而且用了context会违背redux单向管理数据流的理念。并且还会导致shouldComponentUpdate失效。

context的使用姿势:

import PropTypes from 'prop-types';

class Button extends React.Component {
  render() {
    return (
      <button style={{background: this.context.color}}>
        {this.props.children}
      </button>
    );
  }
}

Button.contextTypes = {
  color: PropTypes.string
};

class Message extends React.Component {
  render() {
    return (
      <div>
        {this.props.text} <Button>Delete</Button>
      </div>
    );
  }
}

class MessageList extends React.Component {
  getChildContext() {
    return {color: "purple"};
  }

  render() {
    const children = this.props.messages.map((message) =>
      <Message text={message.text} />
    );
    return <div>{children}</div>;
  }
}

MessageList.childContextTypes = {
  color: PropTypes.string
};

VS

16.3的context:

const MyContext = React.createContext({
  name: 'context'
})

class MyName extends React.component {
  render() {
    return(
      <MyContext.Consumer>
        {
          context => {
            <p>{context.name}</p>
          }
        }
      </MyContext.Consumer>
    )
  }
}

class App extends React.component {
  render() {
    return (
      <MyContext.Provider value={name: 'darren'}>
        <MyName />
      </MyContext.Provider>
    )
  }
}

那以后是不是就遍地的context.Provider了。。 摆不摆脱redux再研究吧。

参考:

Why Not To Use Context
0002-new-version-of-context
React 16.3来了:带着全新的Context API
Context