react的context用法

2017-09-11  本文已影响0人  xiaoaiai

首先在使用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
上一篇 下一篇

猜你喜欢

热点阅读