react的context用法

首先在使用context时使用 getChildContext 吧this.state return出来

getChildContext = () => {
    return {
      themeColor: this.state.themeColor,
      onMainClick: this.state.onMainClick
    }
  }

然后使用static childContextTypes验证属性

  • 属性必须验证
static childContextTypes = {
    themeColor: PropTypes.string,
    onMainClick: PropTypes.func
  }

在子组件中 这个必须再次验证一遍能用 (否则 不生效也不能用)

   static contextTypes = {
      themeColor: PropTypes.string,
      onMainClick: PropTypes.func
    }

子组件中的使用方法

<div className="main">
    main-content
    <br />
    {this.context.themeColor}
    <bt />
    <button onClick={this.context.onMainClick}>btn</button>
</div>

在子子组件中使用方法也一样

以下是全部代码
父组件

import React,{Component} from 'react';
import PropTypes from 'prop-types'

class Header extends Component {
  constructor(props){
    super(props);
    this.state = {};
  }
  render() {
    const {themeColor}  = this.props
    return (
        <div className="header">
            header
            {themeColor}
        </div>
    );
  }
}

Header.propTypes = {
 themeColor: PropTypes.string
}
export default Header

子组件

import React,{Component} from 'react';
import PropTypes from 'prop-types'

class Main extends Component {
    static contextTypes = {
      themeColor: PropTypes.string,
      onMainClick: PropTypes.func
    }
    constructor(props){
        super(props);
        this.state = {};
    }
    render() {
        return (
<div className="main">
    main-content
    <br />
    {this.context.themeColor}
    <bt />
    <button onClick={this.context.onMainClick}>btn</button>
</div>
        );
    }
}
export default Main
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,796评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,115评论 6 342
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,856评论 25 709
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,162评论 18 399
  • 青石板,小格窗,粉黛青眉,人未央。 岁月静好,时间在这儿停滞,小猫慵懒地打着盹,不问世事。 百年前,谁为谁亲手栽下...
    何辄鱼阅读 3,089评论 1 11