React手稿 - Context

Context

Context供应了除props以外的传参数的体式格局。

Context是全局跨组件通报数据的。

API

  • React.createContext

    const {Provider, Consumer} = React.createContext(defaultValue);
  • Provider

    <Provider value={/* some value */}>
  • Consumer

    <Consumer>
      {value => /* render something based on the context value */}
    </Consumer>

Example

ThemeContext.js

import React from 'react';

export const themes = {
  light: {
    foreground: '#000000',
    background: '#eeeeee',
  },
  dark: {
    foreground: '#ffffff',
    background: '#222222',
  },
};

export default React.createContext(
  themes.dark // default value
);

ThemedButton.jsx

import React from 'react';
import ThemeContext, {themes} from './ThemeContext';

export default ({children}) => {
  const styles = {
            color: themes[theme].foreground,
            backgroundColor: themes[theme].background
          };
  return (
    <ThemeContext.Consumer>
      {theme => {
        return (
          <button style={styles}>{children}</button>
        )
      }}
    </ThemeContext.Consumer>
  );
}

App.js

import React, {PureComponent} from 'react';
import ThemeContext from './ThemeContext';
import ThemeButton from './ThemedButton';

export default class extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {theme: 'dark'};
  }

  render() {
    return (
      <ThemeContext.Provider value={this.state.theme}>
        <ThemeButton>
          <div onClick={() => {
            this.setState({theme: this.state.theme === 'dark' ? 'light' : 'dark'})
          }}>Themed Button</div>
        </ThemeButton>
      </ThemeContext.Provider>
    );
  }
}

在线示例

引荐浏览《React 手稿》

    原文作者:小翼
    原文地址: https://segmentfault.com/a/1190000017070519
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞