【问题标题】:React useEffect appended script not triggeringReact useEffect 附加脚本未触发
【发布时间】:2020-01-19 21:22:52
【问题描述】:

我正在尝试加载一个脚本,该脚本一旦触发就会生成一个 iframe 和一个天气小部件。我可以正确附加脚本,但它不会被调用并且不会生成 iframe

我试过直接在渲染中添加脚本,它会短暂加载 iframe 然后切换回脚本标签

const City = ({ content, schema }) => {
  useEffect(() => {
    let script = document.createElement("script");
    script.src =
  "https://darksky.net/widget/graph-bar/32.7174,-117.1628/us12/en.js?width=100%&height=400&title=Full Forecast&textColor=333333&bgColor=FFFFFF&transparency=false&skyColor=undefined&fontFamily=Default&customFont=&units=us&timeColor=333333&tempColor=ff8200&currentDetailsOption=true";
    script.async = true;

    document.getElementById("widget").appendChild(script);
  }, [])

  return (<div id="widget"></div>);
};

export default City;

【问题讨论】:

  • 既然是追加到widget div,为什么不直接在return里面写script标签呢?
  • @Chris 我试过了,它会触发,但会闪烁并恢复为脚本

标签: javascript reactjs react-hooks use-effect


【解决方案1】:

注意控制台中显示的警告:

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

Execute write on doc: It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

【讨论】:

    猜你喜欢
    • 2021-03-29
    • 2021-04-16
    • 1970-01-01
    • 2022-11-11
    • 2021-03-05
    • 1970-01-01
    • 2020-01-07
    • 2018-03-20
    • 1970-01-01
    相关资源
    最近更新 更多