javascript - 在 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() 方法而不会出现错误?
解决方案
假设您没有返回一个空的 JSX 语句,可以通过将它包装在任何标签(甚至是空标签<>
)中来修复它:
return (
<>
{yourResponse}
</>
您可能想要:
const formSubmit = async (e) => {
return window.hcaptcha.reset();
}
或者使用隐式返回
const formSubmit = async (e) => return window.hcaptcha.reset();
推荐阅读
- lua - 我需要帮助来修复此代码,有人能说为什么这不起作用吗?
- plotly - 如何在 plotly express 中显示多个 y 轴
- c# - 为什么我的结构要花费这么多性能?
- python - 您如何避免错误执行自动评分脚本?
- amazon-web-services - 使用假定角色配置文件构建 Docker
- huggingface-transformers - roberta-large 模型的训练损失没有减少,但对于 roberta-base、bert-base-uncased 来说工作得很好
- javascript - 如何用 .js 文件中的字符串替换变量的名称?
- kubernetes - 如何使用 java 在我的集群中找到所有 HelmRelease?
- mysql - 如何使用 PHP 显示带有 MIN、MAX 和 AVG 值(变量 2)的 SQL SUM 查询结果(变量 1)?
- ssl - 将 SSL 证书添加到入口控制器与将其添加到入口资源