n Toolbar(props) { return ( <div>
<ThemedButton />
</div>
); } class ThemedButton extends React.Component { // 指定 contextType 读取当前的 theme context。
// React 会往上找到最近的 theme Provider,然后使用它的值。
// 在这个例子中,当前的 theme 值为 “dark”。
static contextType = ThemeContext; render() { return <Button theme={this.context} />;
} }
但 context 的使用会极大的增强组件之间的耦合性,项目中并不建议直接使用
所以我直接复制粘贴了官方文档的代码,仅为了解 context 这个概念
小型项目中,如果有深层次的传参,应当从组件设计上解决问题,比如直接将组件传下去
而大型项目中,如果需要用到 context,更推荐使用 redux 和 mobx 这些成熟的状态管理工具
参考资料:
《React 状态提升》
《React.js 的 context》
|