首页 > 专栏 > 前端 > 文章详情
使用 Context 和默认值进行进一步区分 发布于:2021-03-26 13:17:59   来源:React   查看:3  讨论:0
theme-context.js
import React from 'react'
export const themes = {
  pink: {
    foreground: '#ff65fa',
    background: '#ff65fa'
  },
  light: {
    foreground: '#eeeeee',
    background: '#eeeeee',
  },
  dark: {
    foreground: '#000000',
    background: '#000000',
  },

};
export const ThemeContext = React.createContext(
    themes.dark //默认初始值
)
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;
    // console.log(props);
    console.log(theme);
    return(
        <button {...props} style={{backgroundColor: theme.background, width:'100px', height:'100px', marginBottom: '10px'}}/>
    )
  }
}
//也就是让以后可以使用this.context,此时ThemedButton已经拥有了context属性。
ThemedButton.contextType = ThemeContext;
//挂载在 class 上的 contextType 属性会被重赋值为一个由 React.createContext() 创建
// 的 Context 对象。此属性能让你使用 this.context 来消费最近 Context 上的那个值。
// 你可以在任何生命周期中访问到它,包括 render 函数中。
export default ThemedButton;
App.js
import React from 'react'
import {ThemeContext, themes} from './theme-context';
import ThemedButton from './themed-button'
//一个使用ThemedButton中间组件
function Toolbar (props) {
  return(
      <ThemedButton onClick={props.changeTheme} >
        改变主题
      </ThemedButton>
  )
}
class AppTheme extends React.Component{
  constructor (props) {
    super(props);
    this.state = {
      theme: themes.pink,
    };
    this.toggleTheme = () => {
      this.setState(state => ({
        theme:
          state.theme === themes.dark
            ? themes.light
            : themes.dark,
      }))
    }
  }
  render () {
    //在ThemeProvider内部的ThemedButton按钮组件使用state中的theme的值
    //而外部的组件使用默认的theme的值
    return(
        <div>
          <ThemeContext.Provider value={this.state.theme}>
            <Toolbar changeTheme={this.toggleTheme} />
          </ThemeContext.Provider>
          <div>
            <ThemedButton />
          </div>
        </div>
    )
  }
}
export default AppTheme;
83W易塔云建站-模板下载,web开发资源,技术博客
总结:本文例子是想表达,同一组件可以保存多种状态和数据。83W易塔云建站-模板下载,web开发资源,技术博客
一个button使用context得到的值,另外同一button使用静态初始值。83W易塔云建站-模板下载,web开发资源,技术博客
我觉得重点应该放在同一组件而不是context上。context,也就是个环境而已,执行环境你忘了吗,不就是ES5中的execution context么?83W易塔云建站-模板下载,web开发资源,技术博客
只不过ES5规定是通过作用域链完成的实现。(个人感觉还好)。83W易塔云建站-模板下载,web开发资源,技术博客
而React没有作用域链,直接从环境里找,这条线可能比较长,而且没有连贯顺序性可言。(并不友好)。

评论

  • 匿名