从反应组件调用外部 Javascript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35082047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call external Javascript function from react components
提问by mr.b
Im not sure if this has been asked before or anybody has encountered the same issue on reactjs. So the scenario is like this, I have an index.htmlfile that includes some javascript. Now on my react component, I have a condition that will render only if the condition is true. This means that initially when my page loaded the component has not been rendered yet. When I toggle a button this is where that component gets rendered. That child component needs to call a javascript method that was included on my index.html. How should I do this?
我不确定之前是否有人问过这个问题,或者有人在 reactjs 上遇到过同样的问题。所以场景是这样的,我有一个包含一些 javascript的index.html文件。现在在我的 react 组件上,我有一个条件,只有在条件为真时才会呈现。这意味着最初当我的页面加载时,组件尚未呈现。当我切换按钮时,这是该组件被渲染的地方。该子组件需要调用包含在我的 index.html 中的 javascript 方法。我该怎么做?
Any help is greatly appreciated.
任何帮助是极大的赞赏。
回答by Made in Moon
In index.html
在 index.html
<script type="text/javascript">
function test(){
alert('Function from index.html');
}
</script>
In your component
在您的组件中
componentWillMount() {
window.test();
}
回答by Dmytro Bondarenko
Try this solution to call global functions from React with TypeScript enabled:
试试这个解决方案,在启用 TypeScript 的情况下从 React 调用全局函数:
Either in index.html or some_site.js
在 index.html 或 some_site.js 中
function pass_function(){
alert('42');
}
Then, from your react component:
然后,从你的反应组件:
window["pass_function"]();
And, of course, you can pass a parameter:
而且,当然,您可以传递一个参数:
//react
window["passp"]("react ts");
//js
function passp(someval) {
alert(`passes parameter: ${someval}`);
}
回答by gor181
So either you define the method on global scope (aka window). And then you can use it from any methods, being React or not.
因此,要么您在全局范围(又名窗口)上定义该方法。然后你可以从任何方法中使用它,无论是否是 React。
Or you can switch to module based paradigm and use require/import to get the module and use the function.
或者您可以切换到基于模块的范例并使用 require/import 来获取模块并使用该功能。
For bigger projects the latter is better as it's scales, while if you need a demo or POC you can certainly hook all to global scope and it will work.
对于更大的项目,后者更好,因为它的规模更大,而如果您需要演示或 POC,您当然可以将所有内容挂钩到全局范围,它会起作用。
More information about modules is at: http://exploringjs.com/es6/ch_modules.html
有关模块的更多信息,请访问:http: //exploringjs.com/es6/ch_modules.html