gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:11:53 27 4
gpt4 key购买 nike

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

   <!--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 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>
);
}

关于reactjs - 如何从网站上正确删除或卸载 React App,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72187310/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com