[英]Uncaught SyntaxError: Unexpected token < with React
我对 React 非常陌生。 以下是我的第一个脚本。
但我收到以下错误。
未捕获的语法错误:意外的标记 <
我什至通过 google/SO 进行了搜索。 但我无法让它工作。
<!DOCTYPE html>
<html>
<head>
<title>First React App</title>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
const name = 'John doe'
const handle = '@john_doe'
function NameComponent (props){
return <h1>{props.name}</h1>;//The problem is here using JSX syntax
}
function HandleComponent(props){
return <h3>{props.handle}</h3>;
}
function App(){
return (
<div id="container">
<NameComponent name={name}/>
<HandleComponent handle={handle}/>
</div>
);
}
ReactDOM.render(<App />,document.getElementById('app'));
</script>
</body>
</html>
要使您的代码按目前的方式工作,您只需要在包含要使用babel进行转换的代码的script标记中添加type="text/babel"
。
从babel文档 :
在加载到浏览器中时,@ babel / standalone将自动编译并执行所有类型为text / babel或text / jsx的脚本标签。
只需进行此更改即可工作的代码
<html> <head> <title>First React App</title> <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> </head> <body> <div id="app"> </div> <script type="text/babel"> const name = 'John doe' const handle = '@john_doe' function NameComponent (props){ return <h1>{props.name}</h1>;//The problem is here using JSX syntax } function HandleComponent(props){ return <h3>{props.handle}</h3>; } function App(){ return ( <div id="container"> <NameComponent name={name}/> <HandleComponent handle={handle}/> </div> ); } ReactDOM.render(<App />,document.getElementById('app')); </script> </body> </html>
尽管这可行 ,但是对于初学者来说,使用create-react-app
或codesandbox通常更简单。
为了使用React进行最低限度的设置(没有编译步骤),您需要使用React.createElement语法而不是JSX标签(请检查https://reactjs.org/docs/add-react-to-a- website.html ),或使用类似htm的名称
我个人只是使用Create React App来帮助进行初始设置。 这将为您配置babel(还有许多其他功能),并进行正确的JSX转换。 尽管将来对您完全了解create-react-app的作用,并且可能进行自己的设置会很有帮助。
//bro 只需使用 npm 安装 babel
// npm install --save @babel/standalone
//在你下面的HTML文件中包含这些行之后
// src="like_button.js 把你放在 JS 文件中。
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel" src="like_button.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.