简体   繁体   English

从React组件函数中的另一个文档调用普通javascript函数

[英]Call normal javascript function from another document in a react component function

I am trying to call a normal javascript function inside of a react component function. 我正在尝试在react component函数内部调用普通的javascript函数。

The script tags are nested in the footer as following : 脚本标签嵌套在页脚中,如下所示:

<script src="NORMAL JAVASCRIPT STUFF"></script> // function test(){};
<script src="REACT STUFF"></script>

So the javascript file with the function that I need is being read earlier. 因此,具有我所需功能的javascript文件已在较早之前阅读。 So the function should be available in the whole document. 因此,该功能应该在整个文档中都可用。

Now when I try to call the function within some react component function like that: 现在,当我尝试在像这样的一些react component函数中调用该函数时:

....,
someFunction: function(){
test();
},...

I get Uncaught ReferenceError: test is not defined 我收到了Uncaught ReferenceError: test is not defined

Does anyone know how to access normal functions inside of react? 有谁知道如何在react内部访问常规功能?

That function would belong to the window object, so you would need to call window.test(); 该函数将属于window对象,因此您需要调用window.test(); instead. 代替。

See here: 看这里:

https://jsfiddle.net/7dzdp9rw/ https://jsfiddle.net/7dzdp9rw/

Based on what you've posted my guess is that you have test defined within a function. 基于您发布的内容,我的猜测是您已在函数中定义了test If a variable or function is defined within another function, it is scoped to that function, and only available there. 如果在另一个函数中定义了变量或函数,则该变量或函数的作用域仅限于该函数,并且仅在该函数中可用。 It would not be globally available. 它不会全局可用。 You would need to move the test definition to outside of any function within "NORMAL JAVASCRIPT STUFF". 您需要将测试定义移至“ NORMAL JAVASCRIPT STUFF”中任何函数的外部。

eg if you have 例如,如果你有

function xyz {
    function test() {}
}()

you need to change to 您需要更改为

function xyz() {}
function test() {}

OR 要么

you can explicitly assign the function to the global scope 您可以将函数显式分配给全局范围

function xyz() {
    window.test = function() {}
}

As a general rule, you want to limit what you have in the global javascript "window" object so as to avoid conflicts. 通常,您希望限制全局javascript“窗口”对象中的内容,以避免冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM