• React手稿


    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 手稿》

  • 相关阅读:
    Qt中的 Size Hints 和 Size Policies
    __declspec,__cdecl,__stdcall区别和作用
    深入理解DLL文件
    TCP/IP TIME_WAIT状态原理
    Linux 网络编程 高级套接字
    OpenCV 图像处理学习笔记(一)
    C++运算符重载的规则
    WinSock异步IO模型之Select
    ASSER、VERIFY、TRACE详解
    VC++ 网络编程总结(二)
  • 原文地址:https://www.cnblogs.com/datiangou/p/10156266.html
Copyright © 2020-2023  润新知