最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Call normal javascript function from another document in a react component function - Stack Overflow

programmeradmin6浏览0评论

I am trying to call a normal javascript function inside of a react ponent function.

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. So the function should be available in the whole document.

Now when I try to call the function within some react ponent function like that:

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

I get Uncaught ReferenceError: test is not defined

Does anyone know how to access normal functions inside of react?

I am trying to call a normal javascript function inside of a react ponent function.

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. So the function should be available in the whole document.

Now when I try to call the function within some react ponent function like that:

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

I get Uncaught ReferenceError: test is not defined

Does anyone know how to access normal functions inside of react?

Share Improve this question asked Aug 13, 2015 at 13:16 noa-devnoa-dev 3,6419 gold badges36 silver badges73 bronze badges 2
  • I tried what you have done, and call that test function in some ponents' render, it get called, can you post the code in that NORMAL JAVASCRIPT STUFF? – fuyushimoya Commented Aug 13, 2015 at 13:25
  • Hello, thanks for your help - I had to declare a window variable function to attach it to the window scope in order to use that in my react ponents – noa-dev Commented Aug 13, 2015 at 14:30
Add a ment  | 

2 Answers 2

Reset to default 7

That function would belong to the window object, so you would need to call window.test(); instead.

See here:

https://jsfiddle/7dzdp9rw/

Based on what you've posted my guess is that you have test defined within a function. 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".

e.g. 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.

发布评论

评论列表(0)

  1. 暂无评论