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

React JS使用JSX编写首个组件时报错Unexpected token '<'如何解决

报错原因

浏览器原生不支持JSX语法,你代码中直接书写的<h1>标签属于JSX语法,未经过转译就直接交给浏览器解析,因此会将<识别为非法字符,抛出语法错误。

修复步骤
  • 引入Babel浏览器端转译脚本:在<head>标签的脚本引入区块,新增Babel standalone的引入,用于在浏览器中实时转译JSX代码。
  • 修改脚本类型:将你书写JSX代码的<script>标签的type属性从text/javascript改为text/babel,告知Babel需要对这段代码进行转译处理。
  • 修复代码其余隐藏错误:
    1. 基类拼写错误:React.component需改为React.Component,Component首字母必须大写
    2. 生命周期方法拼写错误:reder()需改为render()

提示:浏览器端实时转译JSX仅适合本地学习调试使用,正式生产项目需要使用Vite、Webpack等构建工具提前完成JSX转译,提升运行性能。

修复后完整代码
<!DOCTYPE html>
<html>
 <head>
<script src="js/react.js"></script>
<script src="js/react-dom.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
 </head>
 <body>
   <div id="content"></div>
<script type="text/babel">
let helloWorldReactElement = <h1>Hello world! </h1>
class HelloWorld extends React.Component {
  render() {
    return <div>
      {helloWorldReactElement}
      {helloWorldReactElement}
      </div>
  }
}
ReactDOM.render(
  <HelloWorld />,
  document.getElementById('content')
)
</script>
 </body>
</html>

内容的提问来源于stack exchange,提问作者Ismail Zaidi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 11:24:03