码迷,mamicode.com
首页 > 其他好文 > 详细

React Context(一):隐式传递数据

时间:2019-01-26 12:38:34      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:dia   default   alt   分享   without   toggle   port   http   media   

 

一 Context概述

 

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

 

二 项目结构

 

技术分享图片

 

三 代码

 

1 theme-context.js

 

import React from ‘react‘;

// 主题数据
export const themes = {
    gray: {
        background: ‘gray‘,
    },
    gold: {
        background: ‘gold‘,
    },
};

// 创建上下文对象,参数将作为上下文对象的默认值
export const ThemeContext = React.createContext(
    themes.gray // default value
);

 

2 themed-button.js

 

import React from ‘react‘;
import { ThemeContext } from ‘./theme-context‘;

class ThemedButton extends React.Component {
    render() {
        let props = this.props;
        let theme = this.context;
        return (
            <button
                {...props}
                style={{...theme}} />
        )
    }
}

// 给ThemedButton类绑定上下文对象:ThemedButton类的对象的context属性,等于上下文对象的默认值。
ThemedButton.contextType = ThemeContext;

export default ThemedButton;

 

3 app.js

 

import React, { Fragment } from ‘react‘;
import { ThemeContext, themes } from ‘./theme-context‘;
import ThemedButton from ‘./themed-button‘;

// An intermediate component that uses the ThemedButton
// 工具栏组件(中间件)
function Toolbar(props) {
  return (
    <ThemedButton onClick={props.changeTheme}>
      改变上下文对象
    </ThemedButton>
  );
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      theme: themes.gray
    };
    this.toggleTheme = () => {
      this.setState(state => ({
        theme: state.theme === themes.gray ? themes.gold : themes.gray
      }));
    }
  }

  render() {
    return (
      <Fragment>
        {/* 在Provider中,使用Provider提供的值 */}
        <ThemeContext.Provider value={this.state.theme}>
          <Toolbar changeTheme={this.toggleTheme} />
        </ThemeContext.Provider>
        {/* 不在Provider中,使用上下文对象的默认值 */}
        <section>
          <ThemedButton />
        </section>
      </Fragment>
    );
  }
}

export default App;

 

4 index.js

 

import React from ‘react‘;
import ReactDOM from ‘react-dom‘;
import App from ‘./App‘;

ReactDOM.render(<App />, document.getElementById(‘root‘));

 

四 运行效果

 

1 初始化

 

技术分享图片

 

2 点击按钮

 

技术分享图片

 

React Context(一):隐式传递数据

标签:dia   default   alt   分享   without   toggle   port   http   media   

原文地址:https://www.cnblogs.com/sea-breeze/p/10323031.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!