将代码从https://reactjs.org/docs/rendering-elements.html复制到我的javascript文件时,我在浏览器控制台中收到此错误。
SyntaxError:期望的表达式,得到了'<'
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(element, document.getElementById('root'));
}
答案 0 :(得分:2)
请勿将元素包装在函数中。
这是给您的小型演示!
https://codesandbox.io/s/upbeat-platform-1w13u
方法1:
import React from "react";
import ReactDOM from "react-dom";
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
const rootElement = document.getElementById("root");
ReactDOM.render(element, rootElement);
OR
方法2:
import React from "react";
import ReactDOM from "react-dom";
function Tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
return element;
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Tick />, rootElement);
您可以采用任何一种方法。
希望这对您有帮助!
答案 1 :(得分:1)
element
必须是一个反应组件:
function tick() {
const Element = () => ( // Make it a functional component
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(<Element/>, document.getElementById('root')); // Render as component
}
还要确保您具有适当的transform plugin设置。