我尝试迁移到新版本的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一样?