我的 ReactApp 中有以下代碼用于打開一個具有特定大小的新視窗:
<button
type="button"
style={{ height: '20px', width: '50px' }}
className="btn btn-primary"
onClick={() => {
window.open(
"",
"Popup",
"width=975, height=92, top=30"
);
}}
/>
當用戶單擊按鈕時,我想加載另一個組件。我怎樣才能做到這一點?我試圖加載該組件,然后像下面這樣使用它,但沒有奏效:
import component from "./component"
<button
type="button"
style={{ height: '20px', width: '50px' }}
className="btn btn-primary"
onClick={() => {
window.open(
"{<component />}",
"Popup",
"width=975, height=92, top=30"
);
}}
/>
最好的方法是什么?
這是我的組件:
export default function component(props) {
return (
<div className="container">
<div className="cabinet"><img src={image} />
<div className="devices"> <img src={image2} />
</div>
</div>
);
}
uj5u.com熱心網友回復:
在主頁面添加狀態并將其傳遞給組件
const [open, setOpen] = useState[false];
const onClickHandle = () => {
setOpen(true);
};
return (
<>
<button
type="button"
style={{ height: '20px', width: '50px' }}
className="btn btn-primary"
onClick={onClickHandle}
/>
<component open={open} />
</>
);
添加一個新的 props 來控制組件
export default function component(props) {
const { open } = props;
return (
<>
{open && (
<div className="container">
<div className="cabinet">
<img src={image} />
<div className="devices">
{' '}
<img src={image2} />
</div>
</div>
</div>
)}
</>
);
}
uj5u.com熱心網友回復:
使用狀態掛鉤和條件渲染,您可以在按鈕 onClick 上加載反應組件。
const [visible, setVisible] = React.useState(false);
function click(e) {
e.preventDefault();
setVisible(true);
}
return (
<div>
<button onClick={(event) => {
click(event)
}} />
{isVisible && (
<YourComponent />
)
}
</div>
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/422159.html
標籤:
