gpt4 book ai didi

reactjs - 将 Marketo 表单添加到 Gatsby/JSX

转载 作者:行者123 更新时间:2023-12-04 16:28:44 27 4
gpt4 key购买 nike

我正在尝试将 Marketo 表单添加到 Gatsby 站点中,但无法确定脚本注入(inject)页面的顺序。

当我尝试渲染下面的组件时,我收到错误消息“ReferenceError:MktoForms2 未定义”。

我尝试注释掉整个 useEffect 代码块,组件在没有表单的情况下可以很好地呈现到页面。然后,当我将“MktoForms2.loadForm("//app-sj11.marketo.com", "XXX-XXX-XXX", 1608)"粘贴到控制台时,表单会按预期显示。

import React, { useEffect } from "react";
import Helmet from "react-helmet";

import "./form.scss";

const FormContactMkto = () => {
useEffect(() => {
MktoForms2.loadForm("//app-sj11.marketo.com", "XXX-XXX-XXX", 1608);
}, []);

return (
<div>
<Helmet>
<script
src="//app-sj11.marketo.com/js/forms2/js/forms2.min.js"
type="text/javascript"
/>
</Helmet>
<form id="mktoForm_1608"></form>
</div>
);
};

export default FormContactMkto;

如何将这个 Marketo 表单加载到 Gatsby 页面中?非常感谢任何帮助或建议!

最佳答案

我已经为我的项目创建了一个简单的组件。也许它对您的情况有用。

import React, { useState, useEffect } from 'react';

const marketoScriptId = 'mktoForms';

export default function MarketoForm({ formId }) {
const [isLoaded, setIsLoaded] = useState(false);

useEffect(() => {
if (!document.getElementById(marketoScriptId)) {
loadScript();
} else {
setIsLoaded(true);
}
}, []);

useEffect(() => {
isLoaded &&
window.MktoForms2.loadForm(
'//app-XX.marketo.com',
'XXX-XXX-XXX',
formId
);
}, [isLoaded, formId]);

const loadScript = () => {
var s = document.createElement('script');
s.id = marketoScriptId;
s.type = 'text/javascript';
s.async = true;
s.src = '//app-XX.marketo.com/js/forms2/js/forms2.min.js';
s.onreadystatechange = function() {
if (this.readyState === 'complete' || this.readyState === 'loaded') {
setIsLoaded(true);
}
};
s.onload = () => setIsLoaded(true);
document.getElementsByTagName('head')[0].appendChild(s);
};

return (
<div>
<form id={`mktoForm_${formId}`}></form>
</div>
);
}

关于reactjs - 将 Marketo 表单添加到 Gatsby/JSX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56943000/

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