除render()函数外如何触发ReactDOM.createPortal?非有状态组件可行吗?
Great question! Let's clear up some misconceptions here—React's portal functionality is way more flexible than the class component example in older docs might suggest.
Can you trigger ReactDOM.createPortal outside a class component's render() method?
Absolutely! ReactDOM.createPortal() is just a way to create a special React element that renders its content into a different DOM node. You don't need to restrict it to a class component's render() method. Anywhere you can return or render React elements works, including:
- Function components (with or without Hooks)
- Custom Hooks that return portal elements
- Conditional rendering logic
- Nested components
Do you need a stateful parent component to use portals?
Nope! You don't need a class component (or even a stateful function component) to implement portals. Pure stateless function components work perfectly fine.
Example: Stateless Function Component Portal
Here's a simple implementation using a function component—no class or state required:
import React from 'react'; import ReactDOM from 'react-dom'; // A reusable portal component (stateless!) const Portal = ({ children, targetId = 'portal-root' }) => { const targetNode = document.getElementById(targetId); // Fallback to document.body if target doesn't exist const renderTarget = targetNode || document.body; return ReactDOM.createPortal(children, renderTarget); }; // Using the portal in your app const App = () => { return ( <div className="app-container"> <h1>Main App Content</h1> {/* Portal content will render into the #portal-root node */} <Portal> <div className="portal-toast"> This is a portal-rendered element! No stateful parent needed. </div> </Portal> </div> ); };
Example: Conditional Portal with Hooks
Even if you need dynamic behavior (like showing/hiding the portal), you can use function components with Hooks instead of class components:
import React, { useState } from 'react'; import ReactDOM from 'react-dom'; const ToggleablePortal = ({ children }) => { const [isVisible, setIsVisible] = useState(false); const portalRoot = document.getElementById('portal-root'); return ( <> <button onClick={() => setIsVisible(!isVisible)}> Toggle Portal </button> {isVisible && ReactDOM.createPortal(children, portalRoot)} </> ); };
Key Takeaway
The class component example in the docs is just one way to use portals, not the only way. ReactDOM.createPortal() works wherever you can render React elements, and you don't need a stateful parent component to make it work. Function components (stateless or stateful with Hooks) are fully supported and are the modern preferred approach.
内容的提问来源于stack exchange,提问作者JoeTidee

