You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

未用create-react-app,在HTML中引入React遇Unexpected token '<'错误

解决React手动引入时JSX语法报错问题

问题原因

你在states_clock.js里用了JSX语法(就是那些<div>、<Clock />类似HTML的标签),但浏览器根本认不出JSX,它只懂原生JavaScript,所以直接加载的话就会报Unexpected token '<'的语法错误。

解决方法

方法1:引入Babel转译JSX

修改main.html,在加载你的JS文件前引入Babel的CDN,并且把你的JS文件对应的<script>标签的type设为text/babel:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>Add React in One Minute</title>
      </head>
    <body>
        <div id="root"></div>
        <!-- Load React. -->
        <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
        <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
        <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
        <!-- 引入Babel用于转译JSX -->
        <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
        <!-- Load our React component. 注意type设为text/babel -->
        <script type="text/babel" src="states_clock.js"></script>
    </body>
</html>

这样浏览器加载你的JS文件时,Babel会自动把JSX转成原生JavaScript,就能正常运行了。

方法2:改用React.createElement替代JSX

如果不想额外引入Babel,可以直接用React的原生API React.createElement替换所有JSX语法,这是浏览器能直接解析的原生写法:
修改states_clock.js为:

// states_clock.js
'use strict';

const domContainer = document.getElementById('root');
const root = ReactDOM.createRoot(domContainer);

class Clock extends React.Component {
  render() {
    return React.createElement(
      'div',
      null,
      React.createElement('h1', null, 'Hello, world!'),
      React.createElement('h2', null, 'It is ', this.props.date.toLocaleTimeString(), '.')
    );
  }
}

function tick() {
  root.render(React.createElement(Clock, { date: new Date() }));
}

setInterval(tick, 1000);

用这个修改后的JS文件,配合原来的main.html就能正常显示时钟了。

内容的提问来源于stack exchange,提问作者An old man in the sea.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 23:54:41