unmountComponentAtNode

弃用

这个 API 将在 React 的未来主要版本中被删除。

¥This API will be removed in a future major version of React.

在 React 18 中,unmountComponentAtNoderoot.unmount() 取代。

¥In React 18, unmountComponentAtNode was replaced by root.unmount().

unmountComponentAtNode 从 DOM 中移除一个已挂载的 React 组件。

¥unmountComponentAtNode removes a mounted React component from the DOM.

unmountComponentAtNode(domNode)

参考

¥Reference

unmountComponentAtNode(domNode)

调用 unmountComponentAtNode 以从 DOM 中删除已挂载的 React 组件并清理其事件处理程序和状态。

¥Call unmountComponentAtNode to remove a mounted React component from the DOM and clean up its event handlers and state.

import { unmountComponentAtNode } from 'react-dom';

const domNode = document.getElementById('root');
render(<App />, domNode);

unmountComponentAtNode(domNode);

请参阅下面的更多示例。

¥See more examples below.

参数

¥Parameters

  • domNodeDOM 元素。 React 将从该元素中删除已挂载的 React 组件。

    ¥domNode: A DOM element. React will remove a mounted React component from this element.

返回

¥Returns

如果组件已卸载,则 unmountComponentAtNode 返回 true,否则返回 false

¥unmountComponentAtNode returns true if a component was unmounted and false otherwise.


用法

¥Usage

调用 unmountComponentAtNode 以从 浏览器 DOM 节点 中移除一个挂载的 React 组件 并清除其事件处理程序和状态。

¥Call unmountComponentAtNode to remove a mounted React component from a browser DOM node and clean up its event handlers and state.

import { render, unmountComponentAtNode } from 'react-dom';
import App from './App.js';

const rootNode = document.getElementById('root');
render(<App />, rootNode);

// ...
unmountComponentAtNode(rootNode);

从 DOM 元素中删除 React 应用

¥Removing a React app from a DOM element

有时,你可能希望在现有页面或未完全用 React 编写的页面上进行 “sprinkle” React。在这些情况下,你可能需要 “stop” React 应用,方法是从渲染它的 DOM 节点中删除所有 UI、状态和监听器。

¥Occasionally, you may want to “sprinkle” React on an existing page, or a page that is not fully written in React. In those cases, you may need to “stop” the React app, by removing all of the UI, state, and listeners from the DOM node it was rendered to.

在此示例中,单击 “渲染 React 应用” 将渲染一个 React 应用。点击 “卸载 React 应用” 销毁它:

¥In this example, clicking “Render React App” will render a React app. Click “Unmount React App” to destroy it:

import './styles.css';
import { render, unmountComponentAtNode } from 'react-dom';
import App from './App.js';

const domNode = document.getElementById('root');

document.getElementById('render').addEventListener('click', () => {
  render(<App />, domNode);
});

document.getElementById('unmount').addEventListener('click', () => {
  unmountComponentAtNode(domNode);
});


React 中文网 - 粤ICP备13048890号