我不确定之前是否有人在Reactjs上遇到过这个问题。情况是这样的,我有一个包含一些JavaScript的 index.html 文件。现在,在我的React组件中,如果条件为真,则只呈现该组件。这意味着最初加载页面时,该组件尚未呈现。当我切换按钮时,该组件将被呈现。该子组件需要调用被包含在我的index.html文件中的JavaScript方法。我应该如何处理?
非常感谢任何帮助。
我不确定之前是否有人在Reactjs上遇到过这个问题。情况是这样的,我有一个包含一些JavaScript的 index.html 文件。现在,在我的React组件中,如果条件为真,则只呈现该组件。这意味着最初加载页面时,该组件尚未呈现。当我切换按钮时,该组件将被呈现。该子组件需要调用被包含在我的index.html文件中的JavaScript方法。我应该如何处理?
非常感谢任何帮助。
在index.html中
<script type="text/javascript">
function test(){
alert('Function from index.html');
}
</script>
在你的组件中
componentWillMount() {
window.test();
}
创建一个名为global.d.ts
的文件,内容如下(详情请见文档):
interface Window {
test: () => void;
}
✔
尝试使用以下解决方案,在启用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}`);
}
Element implicitly has an 'any' type because index expression is not of type 'number'
。要解决此问题,您需要将 window
强制转换为 (window as { [key: string]: any})["pass_function"]()
。 - Ikeem Wilson因此,您可以在全局范围(即窗口)上定义该方法。然后,您可以从任何方法中使用它,无论是React还是其他。
或者,您可以切换到基于模块的范例,并使用require/import获取模块并使用函数。
对于大型项目,后者更好,因为它可以扩展,而如果您需要演示或POC,则可以将所有内容挂钩到全局范围中,它将起作用。
有关模块的更多信息,请访问:http://exploringjs.com/es6/ch_modules.html
对于 TypeScript 用户,请尝试以下方法:
declare global {
interface Window {
externalMethod: (params: any) => void;
}
}
然后你就可以在你的React组件中像这样调用它
window.externalMethod(params)
<button onClick={this.howItWorks} type="button" className='btn'>How it Works</button>
howItWorks = () => {
window.HowItWorksVideo();
}