首页 > 解决方案 > 在类组件中使用多个上下文

问题描述

如何在 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>
    );
}

}

标签: reactjs

解决方案


如果您需要多个,静态 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
  }
}

推荐阅读