[英]In React, component inside of a modal to be ready/rendered before the modal is open
我有一個打開模式窗口的反應組件,在該模式窗口內,有第二個組件,一個表單。
表單在加載 iframe 時需要與外部服務通信。
頁面加載時,表單組件不存在,所以當我打開modal時,表單組件被渲染,然后它與外部服務通信,並返回iframe,所以加載需要幾秒鍾。
有沒有辦法在頁面首次加載時准備好這個組件? 在模態實際打開之前?
編碼:
const HubspotForm = ({ id, redirect = false }) => {
const script = document.createElement('script');
script.src = 'https://js.hsforms.net/forms/v2.js';
document.body.appendChild(script);
const jqScript = document.createElement('script');
jqScript.src =
'https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js';
document.body.appendChild(jqScript);
const base_url = window.location.origin;
script.addEventListener('load', () => {
if (window.hbspt) {
window.hbspt.forms.create({
portalId: 'xxx',
formId: 'xxx',
target: '#hubspotForm',
inlineMessage:
"<p style='text-align:center;padding:100px 30px'>Redirecting, please wait...</p>",
onFormSubmit: function ($form) {
let redirect_url = `${base_url}/thank-you/?goal=1`;
setTimeout(function () {
window.location = redirect_url;
}, 250);
},
});
}
});
return (
<div>
<div
id="hubspotForm"
css={css`
input[type='submit'] {
background-color: var(--primary) !important;
}
`}
></div>
</div>
);
};
return (
<StyledDialog
onClose={handleClose}
aria-labelledby="simple-dialog-title"
open={open}
>
<div className="modal-close" onClick={handleClose}>
<GrClose color="red" />
</div>
<h3>{demoRequest.demoRequestFormTitle}</h3>
<p>{demoRequest.demoRequestFormText}</p>
<HubspotForm redirect={true} />
</StyledDialog>
);
...
export default function SimpleDialogDemo({
btnText = 'Talk To An Expert',
variant = 'contained',
white = false,
}) {
const classes = useStyles();
const [open, setOpen] = React.useState(false);
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = (value) => {
setOpen(false);
};
return (
<>
<Button
variant="contained"
color="primary"
className={white ? classes.btnWhite : classes.btn}
disableElevation={white ? true : false}
onClick={handleClickOpen}
>
{btnText}
</Button>
<SimpleDialog open={open} onClose={handleClose} />
</>
);
}
您可以嘗試在 css 中使用 display:none 和 zIndex: -1... 並在默認情況下將您的 openModal 屬性設置為 true
看來你有兩份工作。
我最初會在加載函數的其他地方獲取信息並將其存儲在狀態中。 因此,當模式打開時,狀態將已經設置,並且不會增加加載時間的開銷。
模式打開時是否有任何特定原因發起通信?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.