最近,我已经开始为我的自定义JavaScript应用程序的特定部分使用React。它运行良好,但我不太明白我如何“卸载”或“停止渲染”或“清理”一个反应组件,当我不再需要它?
请考虑以下打开作为React组件的模态的示例。然后,我如何关闭它和清理反应方面的事情适当?
MyApp.js (仅限JavaScript,无反应)
import { renderReactModal } from "./ReactModal.jsx";
class MyApp {
// I call this when I want to show my React component
openReactModal() {
// Create an empty div and append it to the DOM
this.modalDomElem = document.createElement("div");
document.append(this.modalDomElem);
// Render the React component into the div
renderReactModal(this.modalDomElem);
}
// I call this method when I want to hide my React component
closeReactModal() {
// Is it enough to do this to unmount / stop the React component from rendering?
// Or is there any other React-specific clean-up code required?
this.modalDomElem.remove();
}
}
ReactModal.jsx (反应转到这里)
import React from "react";
import ReactDOM from "react-dom";
class ReactModal extends React.Component {
render() {
return <h2>React Modal</h2>
}
}
export const renderReactModal = (domElem) => {
// NB: This syntax is for React 16 (different in 18).
ReactDOM.render(
<ReactModal />,
domElem
);
}
发布于 2022-06-10 01:01:32
我搜索了更多,最终找到了React:https://reactjs.org/docs/react-dom.html#unmountcomponentatnode的这一部分
使用ReactDOM.unmountComponentAtNode(container)
似乎是实现这一目标的推荐方法:
从DOM中删除已挂载的React组件,并清理其事件处理程序和状态。
使用这个想法,我可以如下所示修改我的初始代码。
MyApp.js (仅限JavaScript,无反应)
import { mountReactModal, unmountReactModal } from "./ReactModal.jsx";
class MyApp {
// I call this method when I want to show my React component
openReactModal() {
// Create an empty div and append it to the DOM
this.modalDomElem = document.createElement("div");
document.append(this.modalDomElem);
// Mount the React component into the div
// NB: This causes the React component to render
mountReactModal(this.modalDomElem);
}
// I call this method when I want to hide my React component
closeReactModal() {
// Unmount the React component from the div
// NB: This cleans up the React component's event handlers and state
unmountReactModal(this.modalDomElement);
// Remove the div from the DOM
this.modalDomElem.remove();
}
}
ReactModal.jsx (反应转到这里)
import React from "react";
import ReactDOM from "react-dom";
class ReactModal extends React.Component {
render() {
return <h2>React Modal</h2>
}
}
// Mount
export const mountReactModal = (domElem) => {
// NB: This syntax is for React 16 (different in 18).
ReactDOM.render(
<ReactModal />,
domElem
);
}
// Unmount
export const unmountReactModal = (domElem) => {
// NB: This syntax is for React 16 (different in 18).
ReactDOM.unmountComponentAtNode(domElem);
}
https://stackoverflow.com/questions/72568969
复制相似问题