Do you want to fetch and execute the script again and again, every time this component is rendered, or just once when this component is mounted into the DOM?
(您是否想在每次渲染此组件时一次或一次将该组件安装到DOM中时一次又一次地获取并执行脚本?)
Perhaps try something like this:
(也许尝试这样的事情:)
componentDidMount () {
const script = document.createElement("script");
script.src = "https://use.typekit.net/foobar.js";
script.async = true;
document.body.appendChild(script);
}
However, this is only really helpful if the script you want to load isn't available as a module/package.
(但是,这仅在要加载的脚本不能作为模块/软件包提供时才真正有用。)
First, I would always:(首先,我将始终:)
This is likely how you installed the packages react
and react-document-title
from your example, and there is a Typekit package available on npm .
(这可能是您从示例中安装软件包react
和react-document-title
的方式,并且npm上有一个Typekit软件包 。)
Update:
(更新:)
Now that we have hooks, a better approach might be to use useEffect
like so:
(现在我们有了钩子,更好的方法可能是像这样使用useEffect
:)
useEffect(() => {
const script = document.createElement('script');
script.src = "https://use.typekit.net/foobar.js";
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
}
}, []);
Which makes it a great candidate for a custom hook (eg: hooks/useScript.js
):
(这使其成为自定义钩子的理想选择(例如: hooks/useScript.js
):)
import { useEffect } from 'react';
const useScript = url => {
useEffect(() => {
const script = document.createElement('script');
script.src = url;
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
}
}, [url]);
};
export default useScript;
Which can be used like so:
(可以这样使用:)
import useScript from 'hooks/useScript';
const MyComponent = props => {
useScript('https://use.typekit.net/foobar.js');
// rest of your component
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…