React JS如何在dangerouslySetInnerHTML中执行脚本 [英] React JS how to get script inside dangerouslySetInnerHTML executed

查看:1110
本文介绍了React JS如何在dangerouslySetInnerHTML中执行脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 dangerouslySetInnerHTML 内执行脚本?

How to get script inside dangerouslySetInnerHTML get executed?

class Page extends Component {

  render() {
    return (
      <script
        dangerouslySetInnerHTML={{ __html: `
          console.log('hello world');
          window.dataLayer = window.dataLayer || [];
          window.dataLayer.push({
            event: 'viewCart'
          });
        ` }}
      />
    );
  }
}

我无法获得 console.log('hello world')已执行。有人可以帮忙吗?谢谢

I can't get console.log('hello world') executed. Anybody can help? Thank you

推荐答案

您不能因为安全性而自动删除脚本标记。

You can't because script tags are removed automatically for security.

使用javascript的最佳方法是单独获取字符串并从 componentWillMount componentDidMount <执行(或评估)它/ em>

The best way to work with javascript is to get the string separately and execute (or eval) it from componentWillMount or componentDidMount

class Page extends Component {

  componentDidMount() {
    const jsCode = `
      console.log('hello world');
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({
        event: 'viewCart'
      })
    `;
    new Function(jsCode)();
  }

  // you can do something else here
  render() {
    return (
      <noscript />
    );
  }
}

您显然可以使用任何字符串。我猜你可能正在从服务器上加载它。

You can obviously use any string. I presume you might be loading it from the server.

在上面的例子中,我使用了 new Function()()这与 eval()非常相似,但效果更快。

In the example above I used new Function()() which is very similar to eval() but works faster.

我使用 componentDidMount 所以我确定在显示视图后脚本会执行。 Will和Did mount之间的另一个区别是Will mount会在通用(同构)应用程序的服务器端和客户端执行,而Did mount只会在通用应用程序的客户端执行。

I used componentDidMount so i'm certain the script executes after the view is shown. Another difference between Will and Did mount is that Will mount executes on both server and client sides of universal (isomorphic) apps, whereas Did mount will only execute on the client side of universal apps.

这篇关于React JS如何在dangerouslySetInnerHTML中执行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆