从React组件中调用外部Javascript函数

41

我不确定之前是否有人在Reactjs上遇到过这个问题。情况是这样的,我有一个包含一些JavaScript的 index.html 文件。现在,在我的React组件中,如果条件为真,则只呈现该组件。这意味着最初加载页面时,该组件尚未呈现。当我切换按钮时,该组件将被呈现。该子组件需要调用被包含在我的index.html文件中的JavaScript方法。我应该如何处理?

非常感谢任何帮助。

5个回答

92

在index.html中

<script type="text/javascript">
  function test(){
    alert('Function from index.html');
  }
</script>

在你的组件中

componentWillMount() {
  window.test();
}

2022年 TypeScript 编辑:

创建一个名为global.d.ts的文件,内容如下(详情请见文档):

interface Window {
  test: () => void;
}


请告诉我如何调用外部方法。 - Santhosh
3
这个不起作用。 "window.test()" 被 TypeScript 标记为未知,无法编译。 - Brain2000
刚刚工作得非常完美! - Orici
窗口在 TypeScript 中未被识别。 - rahulnikhare
要在 TypeScript 中使此代码正常工作,请在 TypeScript 不喜欢的任何 JavaScript 代码行上方添加 //@ts-ignore(例如,在其范围内未定义 window 的类型),TypeScript 编译器将忽略这些代码/程序应该无问题运行。 - Treadmeister

14

尝试使用以下解决方案,在启用TypeScript的情况下从React调用全局函数:

无论是在index.html还是some_site.js中都可以实现。

function pass_function(){
  alert('42');
}

然后,从你的 React 组件:

window["pass_function"]();

当然,你也可以传递参数:

//react
window["passp"]("react ts");

//js
function passp(someval) {
  alert(`passes parameter: ${someval}`);
}

2
我在尝试实现这个功能时收到了以下错误:Element implicitly has an 'any' type because index expression is not of type 'number'。要解决此问题,您需要将 window 强制转换为 (window as { [key: string]: any})["pass_function"]() - Ikeem Wilson

3

因此,您可以在全局范围(即窗口)上定义该方法。然后,您可以从任何方法中使用它,无论是React还是其他。

或者,您可以切换到基于模块的范例,并使用require/import获取模块并使用函数。

对于大型项目,后者更好,因为它可以扩展,而如果您需要演示或POC,则可以将所有内容挂钩到全局范围中,它将起作用。

有关模块的更多信息,请访问:http://exploringjs.com/es6/ch_modules.html


0

对于 TypeScript 用户,请尝试以下方法:

declare global {
    interface Window {
        externalMethod: (params: any) => void;
    }
}

然后你就可以在你的React组件中像这样调用它

window.externalMethod(params)

0
你可以将你的方法附加到全局的 window 对象上,然后在组件中像这样使用它:
<button onClick={this.howItWorks} type="button" className='btn'>How it Works</button>

howItWorks = () => {
  window.HowItWorksVideo();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接