英文:
How to load and use functions from a js script?
问题
我正在加载一个外部的 JavaScript 文件在一个 React Next.js 页面上。
如何访问 init.js
中的函数 (FooInit
)?
export default function Home() {
useEffect(() => {
FooInit() // 如何访问 FooInit?
}, [])
return (
<>
<Script beforeInteractive src="https://foo.boo/js/init.js" />
</>
)
}
英文:
I am loading an external js file on aReact Next js page.
How to access the function (FooInit
) of init.js
?
export default function Home() {
useEffect(() => {
FooInit() // how to access FooInit?
}, [])
return (
<>
<Script beforeInteractive src="https://foo.boo/js/init.js"
/>
</>
)
}
答案1
得分: 1
要在React Next.js组件中的外部JavaScript文件中访问FooInit
函数,您可以按照以下步骤进行:
- 确保在调用该函数之前已加载外部脚本。您可以使用
Script
组件的onLoad
事件处理程序。 - 从
window
对象中访问FooInit
函数,因为它是一个全局函数。
以下是一个示例实现:
import React, { useEffect } from 'react';
import Script from 'next/script';
export default function Home() {
useEffect(() => {
if (typeof window !== 'undefined' && window.FooInit) {
window.FooInit();
}
}, []);
const handleScriptLoad = () => {
if (typeof window !== 'undefined' && window.FooInit) {
window.FooInit();
}
};
return (
<>
<Script
beforeInteractive
src="https://foo.boo/js/init.js"
onLoad={handleScriptLoad}
/>
</>
);
}
在这个示例中,handleScriptLoad
函数将在外部脚本加载后调用。在此函数中,我们检查window
对象中是否存在FooInit
函数,如果存在则调用它。我们还在useEffect
钩子中执行相同的检查和调用,以处理脚本已经被浏览器加载和缓存的情况。
通过按照这些步骤操作,您可以成功地在Next.js React组件中访问并调用外部JavaScript文件中的FooInit
函数。
英文:
To access the FooInit
function from the external JavaScript file in your React Next.js component, you can follow these steps:
- Make sure the external script has loaded before calling the function.
You can use theonLoad
event handler of theScript
component. - Access the
FooInit
function from thewindow
object since it's a global
function.
Here's an example implementation:
import React, { useEffect } from 'react';
import Script from 'next/script';
export default function Home() {
useEffect(() => {
if (typeof window !== 'undefined' && window.FooInit) {
window.FooInit();
}
}, []);
const handleScriptLoad = () => {
if (typeof window !== 'undefined' && window.FooInit) {
window.FooInit();
}
};
return (
<>
<Script
beforeInteractive
src="https://foo.boo/js/init.js"
onLoad={handleScriptLoad}
/>
</>
);
}
In this example, the handleScriptLoad
function will be called once the external script has loaded. Inside this function, we check if the FooInit
function is available in the window object and call it if it exists. We also do the same check and call in the useEffect
hook for cases when the script is already loaded and cached by the browser.
By following these steps, you can successfully access and call the FooInit
function from the external JavaScript file within your Next.js React component.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论