在React组件中添加脚本或内联标签的教程

899 阅读1分钟

有时,我们想把脚本标签添加到单个组件中。这篇文章讲述了为单个组件添加脚本或内联脚本的多种方法

  • 使用useHook的功能组件
  • 使用 componentWillMount 的 React 类组件
  • React-helmet npm包

如何给反应组件添加脚本标签

本节介绍了为类和功能组件添加脚本标签的方法。

React类组件

有一个回调方法componentWillMount ,它将在反应组件的每次渲染中被调用。在回调中。

  • 使用创建脚本标签的文档createElement函数来创建脚本标签
  • 改变创建的脚本标签的属性srcasync
  • 最后将脚本标签添加到document.body或document.head中。

示例代码:

   componentWillMount() {
        const scriptTag = document.createElement("script");
        scriptTag.src = "https://use.typekit.net/hello.js";
        scriptTag.async = true;
        document.body.appendChild(scriptTag);
    }

同样的代码可以使用useEffect()钩子替换为功能组件。useEffect 钩子对反应组件的每一次渲染都进行调用。

如果你在useEffect()钩子中传递一个空数组来返回,它将只加载和运行一次:

import React from 'react';
import { useEffect } from 'react';

function InlineStyleComponent(props) {

    useEffect(() => {
        const scriptTag = document.createElement('script');

        scriptTag.src = "https://use.typekit.net/foobar.js";
        scriptTag.async = true;

        document.body.appendChild(scriptTag);
        return () => {
            document.body.removeChild(scriptTag);
        }
    }, []);

    return (
        
            Adding inline styles to functional component
        
    );
}

export default InlineStyleComponent;

react-helmet在head标签内添加脚本标签

React helmet是一个管理浏览器头部管理器的npm库,在头部标签内改变网页的代码行是非常容易的。

首先用npm install命令安装 react-helmet

npm install react-helmet

它将依赖性添加到package.json中

"dependencies": {
        "react-helmet": "^6.1.0",
}

使用react-helment ,完成组件代码,为组件添加脚本标签:

import React, { Component } from 'react';
import { Helmet } from 'react-helmet';

class AddingScriptExample extends Component {


    render() {
        return (