首页 > 解决方案 > 在 ReactJS/GatsbyJS 中使用外部脚本中的函数

问题描述

我有一个脚本,它动态插入到表单元素的焦点上的站点头部,这是为了页面加载目的而完成的。负载不使用反应头盔,而是通过做基本的香草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);
    }
};

这工作没有任何问题。我想做的是在提交处理程序中调用 hcaptcha.reset() 函数。我可以确认从浏览器调用该方法确实有效

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

这样做会在 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

如何从反应中调用 hcaptcha 的 .reset() 方法而不会出现错误?

标签: javascriptreactjsgatsbycaptcha

解决方案


假设您没有返回一个空的 JSX 语句,可以通过将它包装在任何标签(甚至是空标签<>)中来修复它:

return (
    <>
        {yourResponse}
    </>

您可能想要:

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

或者使用隐式返回

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

推荐阅读