如何将函数中的逻辑动态地注入脚本元素

问题描述 投票:0回答:1

我有一个脚本,该脚本会动态添加到文档中,我想执行的逻辑位于React组件的useEffect钩子中。

这里是逻辑示例:

const getiTunes = results => {
  if (!isMounted.current) return
  else if (results.errorMessage) throw Error(results.errorMessage)
  else setITunes(results)
}

以及如何将脚本添加到文档中:

const handleResults = document.createElement("script")
handleResults.type = "text/javascript"
handleResults.text = "function getItunes(response) { //type out function here as a string };"

[当前,我可以将结果从getItunes函数保存到window,然后在我的React组件中检索它们,但是想知道是否可以将我的逻辑直接注入到要添加到文档中的脚本中。

我已经尝试了诸如handleResults.text = getiTuneshandleResults.text = String(getiTunes)之类的一些操作,但均无济于事。

这可能吗?还是我必须继续使用window对象之类的东西在document上的脚本和React组件之间传递数据?

javascript reactjs dom
1个回答
0
投票

由于脚本的基本目的是处理jsonp响应,因此我从this code pen中找到了以下代码。它通过创建一个函数,然后将对响应的响应传递给回调函数来完美解决此问题。

export const fetchJSONP = (url, callback) => {
  var callbackName = "jsonp_callback_" + Math.round(100000 * Math.random())
  window[callbackName] = function (data) {
    delete window[callbackName]
    document.body.removeChild(script)
    callback(data)
  }

  var script = document.createElement("script")
  script.src = url + (url.indexOf("?") >= 0 ? "&" : "?") + "callback=" + callbackName
  document.body.appendChild(script)
}

然后我以下列方式使用它:

const handleResponse = response => {
  //do stuff with response
}
fetchJSONP("https://itunes.apple.com/lookup?id=98754654", handleResponse)
© www.soinside.com 2019 - 2024. All rights reserved.