1

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

我有一个提供者组件

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旧 API 中的类似方法中访问 c​​onext this.context

4

0 回答 0