【问题标题】:How to add eternal script tag in Gatsby body ? With conditional rendering of script in body Tag?如何在 Gatsby 正文中添加永恒的脚本标签?在正文标签中有条件渲染脚本?
【发布时间】:2021-12-29 08:57:59
【问题描述】:

例如:-

  const country = "USA" 
    import chat = ('./utils/script'); // script can be imported  from a file
     if(country ="USA")   //  used in component conditionally  
{chat}
else
{ console.log("Not USA")}

告诉我不要使用 html.js 或 gatsby

【问题讨论】:

    标签: javascript reactjs gatsby


    【解决方案1】:

    你有很多方法可以做到这一点:

    如果你需要一些 UI 逻辑,你可以这样做:

    const IndexPage = () => (
      <div>
        <Helmet>
          {country === "USA" && <script src={withPrefix('./utils/script')} type="text/javascript" />
         }
        </Helmet>
    
      </div>
    )
    export default IndexPage
    

    更多关于withPrefix的详细信息(可能不需要)助手:https://www.gatsbyjs.com/docs/reference/built-in-components/gatsby-link/#add-the-path-prefix-to-paths-using-withprefix

    您可以通过使用gatsby-ssr.jsonRenderBody API 以及公开的setPostBodyComponents 函数来实现相同的结果:

    export const onRenderBody = ({ setPostBodyComponents }) => {
      if(country ==="USA"){
        setPostBodyComponents([
            <script src='./utils/script' />,
        ])
      }
    }
    

    有关gatsby-ssr.jsonRenderBody API 的更多详细信息:https://www.gatsbyjs.com/docs/reference/config-files/gatsby-ssr/

    【讨论】:

      猜你喜欢
      • 2020-09-04
      • 2012-12-08
      • 1970-01-01
      • 2019-05-17
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      相关资源
      最近更新 更多