reactjs - 在类组件中使用多个上下文
问题描述
如何在 React 类组件中使用多个 Context?就像您如何在功能组件中使用多个上下文一样,例如在要使用的上下文上调用 useContext 两次或更多次?
export default class Component extends React.Component{
static contextType = LocalizationContext;
constructor(props){
super(props);
this.imageModule = new ImageModule();
this.state = {
}
}
componentDidMount = () => console.log(this.context);
render(){
return(
<React.Fragment>
{}
</React.Fragment>
);
}
}
解决方案
如果您需要多个,静态 contextType 属性将不起作用,因此您需要使用上下文使用者。当您只需要渲染函数中的值时,这是最简单的:
export class Example extends React.Component {
render() {
<LocalizationContext.Consumer>
{(translate) => (
<SomeOtherContext.Consumer>
{(value) => (
<div>{translate(value)}</div>
)}
</SomeOtherContext.Consumer>
)}
</LocalizationContext.Consumer>
}
}
如果您需要其他生命周期挂钩中的值,例如 componentDidMount,那么您最好的选择是将此组件包装在一个可以从上下文中读取值的组件中,然后将它们作为 props 传递:
export const Example = (props) => (
<LocalizationContext.Consumer>
{(translate) => (
<SomeOtherContext.Consumer>
{(value) => (
<InnerComponent translate={translate} value={value} {...props} />
)}
</SomeOtherContext.Consumer>
)}
</LocalizationContext.Consumer>
)
class InnerComponent extends React.Component {
componentDidMount() {
// something with props.translate or props.value
}
}
推荐阅读
- mongodb - 更新具有最大值的 n 个元素
- odbc - MariaDB ODBC 连接器 3.1.4(32 位),带有 BEGIN NOT ATOMIC
- python - 在 GPIO 中断上写入/读取 SPI 失败并出现 OSError:[Errno 9] 文件描述符错误
- java - Jpype 中的多处理内存泄漏
- react-transition-group - 如何将 css 模块中的类包含到 react-transition-group 组件中?
- angular - 从节点模块覆盖样式
- java - 使用数据结构在 Java 中实现 Excel 工作表功能
- activecollab - ActiveCollab API v1 无法更改项目的 hourly_rates
- swiftui - 视图在模态演示中从左右边缘压缩
- flutter - 如何在 Flutter 中构建自定义圆圈范围?