如何访问新的react context API的`context`

时间:2018-05-23 13:56:55

标签: reactjs react-context

我尝试迁移到新版本的React(16.3.2)并遇到了在新的上下文API中访问context的问题。

我有一个提供者组件

Provide.js

export const Context = React.createContext();

export default class Provider extends Component {
constructor(props) {
    super(props);

    this.state = {
      selection: new Selection({
        defaultSelection: props.defaultSelection,
        onChange: props.onChange,
      }),
    };
  }
}

render() {
    const { children } = this.props;

    return (
      <Context.Provider value={this.state}>
        {children}
      </Context.Provider>
    );
  }

Consumer组件中,我可以通过render方法访问上下文。

import { Context } from '../Provider';

export default class Consumer extends Component {
  constructor(props, context) {
    super(props, context);

   // `this.context` is empty Object
    if (this.context.selection) {
      context.selection.register(props.tabFor);
    }

    this.handleClick = this.handleClick.bind(this);
  }

  componentDidMount() {
    // `this.context` is empty Object
    if (this.context.selection) {
      this.context.selection.subscribe(this.update);
    }
  }

  handleClick(event) {
    // `this.context` is undefined
    if (this.context.selection) {
      this.context.selection.select(this.props.tabFor);
    }

    if (this.props.onClick) {
      this.props.onClick(event);
    }
  }

  render() {
    return (
      <Context.Consumer>
        //context from `Provider`
        {(selection) => {
          return (<button
            default={selection.defaultSelection}
            onChange={selection.onChange}
          >
            {children}
          </button>);
        }}
      </Context.Consumer>
    );
  }
}

但是如何在组件方法或constructor中访问conext,就像this.context中的旧API一样?

0 个答案:

没有答案