gpt4 book ai didi

reactjs - 在类组件中使用多个上下文

转载 作者:行者123 更新时间:2023-12-03 16:20:39 27 4
gpt4 key购买 nike

如何在React Class组件中使用多个Contex?像您如何在功能组件中使用多个顶点,例如在要使用的顶点上调用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属性,它将无法正常工作,因此您需要使用上下文使用者。当您只需要render函数中的值时,这是最简单的:

export class Example extends React.Component {
render() {
<LocalizationContext.Consumer>
{(translate) => (
<SomeOtherContext.Consumer>
{(value) => (
<div>{translate(value)}</div>
)}
</SomeOtherContext.Consumer>
)}
</LocalizationContext.Consumer>
}
}
如果您需要其他生命周期 Hook 中的值,例如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
}
}

关于reactjs - 在类组件中使用多个上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63431873/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com