如何将 JSX 文件引用到 HTML 页面

How to refer JSX file to an HTML Page

我在 HTML 页面中引用了 JSX 文件,但该页面未显示任何内容。

HTML (Index.html)

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>My First React Example</title>
  </head>
  <body>
    <div id="container"></div>
    <script src="https://***/react-15.0.0.js"></script>
    <script src="https://***/react-dom-15.0.0.js"></script>
    <script type="text/javascript" src="script.js"></script>
  </body>
</html>

JSX (Script.js)

var CommentBox = React.createClass({
  render: function() {
    return (
      <div className="commentBox">
        Hello, world! I am a CommentBox.
      </div>
    );
  }
});


ReactDOM.render(
  <CommentBox />,
  document.getElementById('container')
);

我试过将文件扩展名更改为 .jsx/.js,但还是不行。

使用 babel-standalone 转译你的 JSX 代码。在脚本类型

中也使用 text/babel
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>My First React Example</title>
  </head>
  <body>
    <div id="container"></div>
    <script src="https://***/react-15.0.0.js"></script>
    <script src="https://***/react-dom-15.0.0.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <script type="text/babel" src="script.js"></script>
  </body>
</html>

script.js

var CommentBox = React.createClass({
  render: function() {
    return (
      <div className="commentBox">
        Hello, world! I am a CommentBox.
      </div>
    );
  }
});


ReactDOM.render(
  <CommentBox />,
  document.getElementById('container')
);

但是我会推荐你​​使用 webpack 来使用 babel-loader

转译你的代码