新的Context API要求使用者从创建它的位置导入上下文。
那么为什么消费者需要定义contextType
?我可以使用导入的值。
import ThemeContext from './context/theme';
class Component {
render() {
return (
<div>{this.context}</div>
);
}
}
Consumer.contextType = ThemeContext; // why?
如果我在包ComponentA
中有一个组件PackageA
,它需要一个上下文。如何为它定义上下文?
// PackageA/ComponentA.js, managed by npm/yarn
import PackageContext from './context';
class ComponentA {}
ComponentA.contextType = PackageContext;
// ===========================================
// src/App.js
import ComponentA from 'PackageA/ComponentA';
const MyContext = React.createContext();
function App() {
return (
<MyContext.Provider value="app context">
<ComponentA />
</MyContext.Provider>
);
}
我出现的唯一方法就是这样。但我真的不喜欢它。
// src/ComponentA.js
import ComponentA from 'PackageA/ComponentA';
ComponentA.contextType = MyContext;
export default ComponentA;
// And just import this component instead of the one in `PackageA`,
// although we can still use it because it's modified.
contextType
static property应该与context
实例属性一起用于类组件,并作为ThemeContext.Consumer
的替代。如果功能组件没有任何影响,则不需要Consumer.contextType
。
功能组件中contextType
的对应物是useContext
hook,因为React 16.8:
function Consumer() {
const theme = React.useContext(ThemeContext);
return (
<div>{theme}</div>
);
}