我想在 React 中渲染一个元素,只是通过调用一个函数。
通常您会使用一个组件(假设是一个Popup
),它从状态中获取一个 bool 值以使其显示或不显示,并使用一些回调处理程序更改它。像这样:
import React, { useState } from "react";
import Popup from "somecomponentlibrary";
import { Button } from "pathtoyourcomponents";
export const SomeComponent = () => {
const [open, setOpen] = useState(false);
return (
<>
<Button onClick={() => { setOpen(true); }}>
this opens a modal
</Button>
<Popup type={"info"} open={open} timeout={1000}>
text within modal
<Button onClick={() => { setOpen(false); }}></Button>
</Popup>
</>
);
};
我想知道是否可以像上面那样调用一些方法在屏幕上显示它,而不是像上面那样在组件中返回它:
import React from "react";
import { Button, popup } from "pathtoyourcomponents";
export const SomeComponent = () => {
return (
<>
<Button onClick={() => { popup.info("text within modal", 1000); }}>
this opens a modal
</Button>
</>
);
};
如何编写 popup
函数以便以这种方式在 DOM 中呈现 Popup
组件?
最佳答案
您可以使用 ReactDOM.render在调用函数时呈现弹出窗口:
const node = document.createElement("div");
const popup = (message, {type, timeout}) => {
document.body.appendChild(node);
const PopupContent = () => {
return (
<Popup type={type} open={true} timeout={timeout}>
{message}
<button
onClick={clear}
>Close</button>
</Popup >
);
};
const clear = () => {
ReactDOM.unmountComponentAtNode(node);
node.remove();
}
ReactDOM.render(<PopupContent/>, node);
};
然后调用弹窗函数:
<Button onClick={() => { popup("text within modal", {type: "info", timeout: 1000}); }}>
this opens a modal
</Button>
关于javascript - 如何通过调用函数呈现弹出窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67008939/