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

How to use ReactDOM.createPortal in React 16?

1个答案

1

ReactDOM.createPortal() is a higher-level API in React, primarily used to render child nodes outside the parent component's DOM hierarchy while keeping them logically within the parent component's component tree. This is typically used when you need child components to visually detach from their parent component, such as when building modals, floating cards, or any components that should be displayed elsewhere on the page.

Usage:

  1. Create a container element: First, define a DOM node as the portal's container in index.html or any other base HTML file.
html
<div id="portal-root"></div>
  1. Using ReactDOM.createPortal: In a React component, use ReactDOM.createPortal to render a component into the previously defined container.
jsx
import React from 'react'; import ReactDOM from 'react-dom'; class MyPortalComponent extends React.Component { render() { // Use createPortal to render this div into the portal-root container return ReactDOM.createPortal( <div>{'This is rendered in a portal'}</div>, document.getElementById('portal-root') ); } } export default MyPortalComponent;

Example Usage:

Assume we need to build a modal that appears when a user clicks a button and should cover other page content.

jsx
class App extends React.Component { constructor(props) { super(props); this.state = { showModal: false }; } handleOpenModal = () => { this.setState({ showModal: true }); } handleCloseModal = () => { this.setState({ showModal: false }); } render() { return ( <div> <button onClick={this.handleOpenModal}>Open Modal</button> {this.state.showModal && ( <Modal onClose={this.handleCloseModal}> <p>This is modal content</p> <button onClick={this.handleCloseModal}>Close</button> </Modal> )} </div> ); } } function Modal({ onClose, children }) { return ReactDOM.createPortal( <div className="modal-backdrop"> <div className="modal-content"> {children} <button onClick={onClose}>Close Modal</button> </div> </div>, document.getElementById('portal-root') ); } export default App;

In this example, the Modal component is rendered to a DOM node independent of the main application's UI hierarchy using ReactDOM.createPortal. This allows the modal to cover other parts of the application while still being managed within the React component tree, enabling state and lifecycle handling just like any other React component.

2024年7月29日 20:20 回复

你的答案