我是初学者。当我使用createElement
渲染元素时,它可以正常工作。但是使用JSX进行以下渲染时,会抛出错误并说Uncaught SyntaxError: Unexpected token <
const { createElement } = React;
const { render } = ReactDOM;
const style = {
fontFamily: 'Arial',
color: 'White',
backgroundColor: 'Red',
padding: '10px',
border: '10px solid black'
}
render(
<h1 id="emp-title" className="header" style={style}>Full time Employee</h1>,
document.getElementById('react-container-jsx')
);
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<title>React 101</title>
</head>
<body>
<div id="react-container-jsx"></div>
<script src="index.js"></script>
</body>
</html>
尝试:尝试过但没用
<script src="index.js" type = "text/babel"></script>
也
<script src="index.js" type = "text/jsx"></script>
没用。非常感谢您的帮助。
答案 0 :(得分:1)
您还需要链接babel-standalone
然后将type="text/babel"
添加到脚本标签。
工作片段:
const { createElement } = React;
const { render } = ReactDOM;
const style = {
fontFamily: 'Arial',
color: 'White',
backgroundColor: 'Red',
padding: '10px',
border: '10px solid black'
}
render(
<h1 id="emp-title" className="header" style={style}>Full time Employee</h1>,
document.getElementById('react-container-jsx')
);
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6.26.0/babel.min.js"></script>
<title>React 101</title>
</head>
<body>
<div id="react-container-jsx"></div>
<script src="index.js" type="text/babel"></script>
</body>
</html>