简体   繁体   中英

Can React class components and functional components access the same context?

I am working on a React project that was built primarily using React Class Components. Recently, the team decided to begin pivoting to functional components with hooks.

Is there a way for functional and class components to access the same contexts? In other words, if I have a context provider that is set up as a class/consumed by class components, can I then use a down-stream functional component to access and update that context?

The same question goes the other way (setting up provider to use useContext() hook and accessing it through a class component)

I have seen a lot online about "how to use context api," but have yet to see one that combines them instead of simply explaining the two ways to use context.

You can still use context in class based components.

Better still, just turn the particular component you're trying to refractor to a function based component.

Doesn't necessarily mean to rewrite the code.. just change things like the the class to const and the name of the component. Next remove the render method and leave only the return. Every other thing like the creating functions can be done above the return and inside the component body like regular functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM