如何从网站上正确删除或卸载 React App

How remove or unmount React App from a website properly

在我的网站中,我有一个按钮可以在特定 div 中启动 React 应用程序。当我点击它时,我创建了一个反应根 div 并在里面渲染反应应用程序。 关闭它的正确方法是什么?

   <!--HTML from the website -->
  <body>
    <button id="btn">Launch React App</button>
    
    <script type="module" src="/src/main.tsx"></script>
  </body>
//main.js from the react App
import React from "react";
import ReactDOM from "react-dom/client";
import "./global.scss";
import App from "./App";

const btn = document.getElementById("btn");

btn.onclick = () => {
  const root_div = document.createElement("div");
  root_div.id    = "root";
  document.body.appendChild(root_div);

  const root = ReactDOM.createRoot(root_div);

  root.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );
};

如果您需要做的只是删除整个 React 应用程序 div,请使用 removeChild - 您将获得对父项的引用,然后调用 removeChild 并引用子项元素作为参数。

你有上面的那些参考资料,所以你应该能够做类似的事情:

document.body.removeChild(root_div)

或者您可能需要先获取对根 div 的引用,例如:

const root_elem = document.getElementById("root");
document.body.removeChild(root_elem)

要以 React 方式卸载组件(甚至是根组件),似乎建议这样做:

unmountComponentAtNode(document.getElementById('root'));

最后我为 React v18 做了这个:

  <!--HTML from the website -->
  <body>
    <button id="btn">Launch React App</button>
    
    <script type="module" src="/src/main.tsx"></script>
  </body>
//main.js
/*Librairies*/
import React from 'react';
import ReactDOM from 'react-dom/client'; //React 18
/*Components*/
import App from './App';
import CloseApp from './components/CloseApp/CloseApp';
/*CSS*/
import './global.scss';

const btn = document.getElementById('btn');

/*CREATE ROOT ELEMENT & RENDER IT with React 18*/
btn.onclick = () => {

  const div_root = document.createElement('div');
  div_root.id    = 'div_root';

  const root = ReactDOM.createRoot(div_root);
  document.body.appendChild(div_root);

  root.render(
    <React.StrictMode>
      <App />
      <CloseApp root={root} />
    </React.StrictMode>
  );
};
//CloseApp.js
import ReactDOM from 'react-dom/client'; //React 18
export default function CloseApp({ root }) {
  const close = () => {
    const div_root = document.getElementById('div_root');
    root.unmount(); //React 18
    div_root.remove();
  };

  return (
    <button onClick={close}>CLOSE</button>
  );
}