您好,我在React中弄乱了context,我想知道是否有一种方法可以使用static消耗同一类中的2个上下文。我知道我可以对2个使用者使用它,并返回它们的值,返回一个doc所说的函数,但是我想像使用static contextType = HomeContext一样在整个类中访问两个上下文。有没有办法做这样的事情?

FormControl.contextType = {
  HomeContext,
  FormContext
}

最佳答案

使用contextType Api无法访问多个上下文。相反,您需要使用Render props模式

<HomeContext.Consumer>
   {(homeContext) => (
      <FormContext.Consumer>
         {(formContext) => (
             <YourComponent homeContext={homeContext} formContext={formContext} />
         )}
      </FormContext.Consumer>
   )}
</HomeContext.Consumer>

09-27 10:57