<script src =“X”> </script>里面返回render |应对

时间:2016-09-14 18:41:19

标签: javascript reactjs

在React中我应该如何声明我的脚本?

HTML上的

看起来像:

    <!-- jQuery -->
    <script src="../assets/vendors/jquery/dist/jquery.min.js"></script>
    <!-- Bootstrap -->
    <script src="../assets/vendors/bootstrap/dist/js/bootstrap.min.js"></script>

但是它如何在React上工作?

export default class Footerjq extends React.Component {
  render () {
    return (
    {/* jQuery */}
      script.src = "../assets/vendors/jquery/dist/jquery.min.js",
      {/* Bootstrap */}
      script.src = "../assets/vendors/bootstrap/dist/js/bootstrap.min.js",
    );
  }
}

我试过这样,但是给我一个错误...

Module build failed: SyntaxError: Unexpected token (9:6)

   7 |       script.src = "public/bundle.js",
   8 |       {/* jQuery */}
>  9 |       script.src = "../assets/vendors/jquery/dist/jquery.min.js",
     |       ^

1 个答案:

答案 0 :(得分:1)

React不允许你这样做,但你应该能够在你的组件中执行此操作:

componentWillMount() {
  ['../jquery.js', '../bundle.js'].forEach((src) => {
    const script = document.createElement('script');
    script.src = src;
    script.async = true;
    document.body.appendChild(script);
  });
}

但为什么不把它们简单地嵌入你的index.html呢?