【问题标题】:How to use a plain JS widget in React app如何在 React 应用程序中使用纯 JS 小部件
【发布时间】:2020-03-17 01:33:52
【问题描述】:

我需要将一个普通的 JS 组件嵌入到我的 React 应用程序中,该组件是一个带有它自己的方法的输入。 我有一个缩小的 .js.css 文件及其 .map 文件。

我将它们放入我的静态文件夹中,并尝试通过 ref 将它们附加到 componentDidMount() 中我的一个组件中的 <div /> 上。但它似乎没有将它与我的应用程序捆绑在一起。我看到的只是一个带有<script /><link /> 标签的空div。

  componentDidMount () {
    const script = document.createElement('script')
    const link = document.createElement('link')

    script.type = 'text/javascript'
    script.src = 'static/my-component.js'
    script.async = true

    link.href = 'static/my-component.css'
    link.rel = 'stylesheet'

    this.el.appendChild(script)
    this.el.appendChild(link)
  }

render () {
    return (
      <div ref={el => (this.el = el)} />
    )
}

【问题讨论】:

    标签: javascript reactjs widget embed


    【解决方案1】:

    我不明白为什么你不能将 vanilla JS 组件放入你的 React 应用程序中。主要原因是什么?

    【讨论】:

      【解决方案2】:

      我通过以下方式实现了一个插件(ics.js)

      1) 我在以下位置创建了一个新模块:

      /utilities/ics.js

      export const ics = () => {
      // plugin code here
      }
      

      2) 从我的组件中,我已经导入了我的插件

      import { ics } from './utilities/ics' // use the right path
      

      3) 在我的组件中,我在需要的地方使用了插件:

      const cal = ics() // works
      

      如果这有帮助,请告诉我。

      当涉及到 css 时,我会简单地导入它。

      【讨论】:

        猜你喜欢
        • 2021-04-01
        • 2022-06-14
        • 1970-01-01
        • 1970-01-01
        • 2020-03-04
        • 2021-05-13
        • 2021-09-15
        • 2019-01-30
        • 1970-01-01
        相关资源
        最近更新 更多