简体   繁体   English

在 ReactJS/GatsbyJS 中使用外部脚本中的 Function

[英]Use Function From External Script In ReactJS/GatsbyJS

I have a script which is dynamically inserted into the head of the site onfocus of a form element, this is done for page load purposes.我有一个脚本,它动态插入到表单元素的焦点上的站点头部,这是为了页面加载目的而完成的。 The load does not use react helmet but basic vanilla js by doing负载不使用反应头盔,而是通过做基本的香草js

const handleFocus = () =>
{
    if (!loaded)
    {
        setScriptLoaded(true);
        const script = document.createElement('script');
        script.src = 'https://hcaptcha.com/1/api.js';
        script.async = true;
        script.defer = true;
        document.head.appendChild(script);
    }
};

This works without any problems.这工作没有任何问题。 What I am trying to do is call the hcaptcha.reset() function in an on submit handler which is.我想做的是在提交处理程序中调用 hcaptcha.reset() function 。 I can confirm that that method does work when called from the browser我可以确认从浏览器调用该方法确实有效

const formSubmit = async (e) =>
{
    window.hcaptcha.reset();
}

Doing this is trowing a lot of error in gatsby which are这样做会在 gatsby 中引发很多错误,这些错误是

Unknown Runtime Error

Objects are not valid as a React child (found: [object Response]). If you meant to render a collection of children, use an array instead.
:

No codeFrame could be generated

How can I call the.reset() method of hcaptcha from react without the errors?如何从反应中调用 hcaptcha 的 .reset() 方法而不会出现错误?

Assuming you are not returning an empty JSX statement, which can be fixed by wrapping it in any tag (even empty tag <> ):假设您没有返回一个空的 JSX 语句,可以通过将其包装在任何标签中来修复它(甚至是空标签<> ):

return (
    <>
        {yourResponse}
    </>

You may want to:您可能想要:

const formSubmit = async (e) => {
   return window.hcaptcha.reset();
}

Or using the implicit return或者使用隐式返回

const formSubmit = async (e) =>  return window.hcaptcha.reset();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM