首页 > reactjs怎么从外部引入组件?

reactjs怎么从外部引入组件?

平时用reactjs写页面时我会将组件写在script标签包裹中,但这样写好的一个组件只能用于这一个页面,于是我在想是否我可以将组件提取到一个.js文件中,这样就可以用一个组件可以很方便的用于多个页面中,但是这样确实行不通的,为什么呢?

比如我想在有一个index.html文件

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script src="react.js"></script>
        <script src="react-dom.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
    </head>
    <body>
        <div id="wrap"></div>
        <script src="index.js"></script>
    </body>
    </html>

在index.js文件中这样写道

ReactDOM.render(<div>HelloWorld</div>,document.getElementById("wrap")); 

这样写为什么不行呢???


可以看下官方文档,jsx的语法浏览器默认是不支持,需要引入额外的库来完成从 jsx --> js 的编译。
https://facebook.github.io/react/docs/getting-started.html#separate-file

此外,楼主的写法,即使不抽取出单独的文件,也是运行不了的(是在线下做了编译?)

【热门文章】
【热门文章】