乐闻世界logo
搜索文章和话题

How can I make React Portal work with React Hook?

1个答案

1

React Portal allows rendering child components into a DOM node outside the parent component's hierarchy. This is commonly used when child components need to be positioned outside the parent component's hierarchy, such as in modals or tooltips.

Using React Hooks in React Portal is identical to using them in standard components. Below, I'll demonstrate how to use React Hooks in React Portal by creating a simple modal component.

First, assume we have a modal root element in the HTML file:

html
<!-- public/index.html --> <body> <div id="app"></div> <!-- Root node for React application --> <div id="modal-root"></div> <!-- Root node for Portal --> </body>

Next, we create a Modal component that uses useState and useEffect hooks, along with ReactDOM.createPortal to render content into modal-root:

jsx
import React, { useState, useEffect } from 'react'; import ReactDOM from 'react-dom'; // Modal component const Modal = ({ children }) => { // Create a div element to render the modal content const [container] = useState(() => document.createElement('div')); useEffect(() => { const modalRoot = document.getElementById('modal-root'); modalRoot.appendChild(container); // Cleanup function when component unmounts return () => { modalRoot.removeChild(container); }; }, [container]); // The dependency array ensures the effect runs only when the component mounts and unmounts // Use React Portal to render children into a new DOM node return ReactDOM.createPortal( children, container ); }; // Using the Modal component const App = () => { const [modalVisible, setModalVisible] = useState(false); return ( <div> <button onClick={() => setModalVisible(true)}>Show modal</button> {modalVisible && ( <Modal> <div style={{ backgroundColor: 'white', padding: '20px' }}> <p>This is the content of the modal</p> <button onClick={() => setModalVisible(false)}>Close modal</button> </div> </Modal> )} </div> ); }; export default App;

In the above Modal component:

  1. Using useState, a container DOM element is created, which remains unchanged throughout the component's lifecycle.
  2. useEffect handles mounting and unmounting logic, ensuring container is appended to modal-root and removed when the component unmounts.
  3. The ReactDOM.createPortal method renders the child elements of the Modal component into container.

The App component includes a button to toggle the modal's visibility and a conditionally rendered Modal component, demonstrating how to implement a basic modal. In this example, useState is used to control the modal's visibility state.

This is how to use React Hooks in React Portal. You can use hooks such as useState, useEffect, useContext, and useReducer in the Portal just as you would in regular components.

2024年6月29日 12:07 回复

你的答案