在 reactjs 功能组件中实现 contextType 的正确方法是什么?

what is the right way to implement contextType in reactjs functional components?

在reactjs 16...版本中,增加了contextType属性,同时也鼓励使用函数式组件。但出于某种原因,似乎没有任何关于同时使用它们的文档。找到的唯一示例是将 contextType 与 class 组件结合使用的示例。 有没有人有在功能组件结构中使用 contextType 的例子?

使用 useContext() 钩子。来自 React 文档:

Tip

If you’re familiar with the context API before Hooks, useContext(MyContext) is equivalent to static contextType = MyContext in a class, or to <MyContext.Consumer>.

useContext(MyContext) only lets you read the context and subscribe to its changes. You still need a <MyContext.Provider> above in the tree to provide the value for this context.