React Portal能否在无状态函数组件(SFC)中使用?
Absolutely! ReactDOM.createPortal() works perfectly in functional components—you don't need a class component to use it at all.
Portals are just a React API for rendering a component's output into a different DOM node outside the parent component's DOM hierarchy, and this capability isn't tied to component type (class vs. functional). You can use it directly in the return statement of your functional component, just like you did in your class component example.
Example of a functional component using createPortal:
import React from 'react'; import ReactDOM from 'react-dom'; // Functional component const MyFunctionalComponent = () => { // Grab the target DOM node (make sure it exists in your HTML!) const portalTarget = document.getElementById('dom-location'); // Guard clause in case the target node isn't loaded yet if (!portalTarget) { return <div>Loading...</div>; } return ( <Wrapper> {ReactDOM.createPortal( <FOO />, portalTarget )} </Wrapper> ); };
A quick note:
Always make sure the target DOM element (dom-location in your case) exists in the DOM before trying to render a portal into it. Adding a simple check like the one above prevents errors if your component mounts before the target node is available.
内容的提问来源于stack exchange,提问作者JoeTidee

