[英]Parse Error: Line 9: Unexpected identifier in react
這有什么錯誤,我只是在關注新的波士頓教程,在執行此操作時我不知道為什么會出現此錯誤
我現在編輯了代碼,它仍然無法正常工作
代碼:
<!Doctype html>
<html>
<head>
<title>React Practice</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
</head>
<body>
<script type="text/jsx">
class Basics extends React.Component {
constructor () {
super();
this.state = {checked: true}
}
render(this.state.checked) {
var msg;
if () {
msg = 'checked';
} else {
msg = 'unchecked';
}
return (
<div>
<input type="checkbox" />
<h2>Checkbox is {msg}</h2>
</div>
)
}
}
ReactDOM.render(<Basics />, document.getElementById('example'));
</script>
<div id="example"></div>
</body>
對我來說很奇怪,我會這樣寫:
getInitialState() {
return {checked:true}
}
render() {
var msg;
if (this.state.checked) {
msg = 'checked';
} else {
msg = 'unchecked';
}
return (
<div>
<input type="checkbox" />
<h2>Checkbox is {msg}</h2>
</div>
)
}
}
你有空if()
,而render()
不應該接受任何參數,我不知道你為什么使用msg: checked
而不是msg = 'checked'
(也許是一些我以前沒見過的 JS 轉譯器)。 我還將初始狀態移動到構造函數:
constructor () {
super();
this.state = {checked: true}
}
並刪除getInitialState()
方法。 在構造函數之外,您應該始終使用setState()
方法。 而且,正如您在評論部分指出的,您不應該在方法聲明后使用逗號,它在對象聲明中是必需的,但在 ES 6 類聲明中是禁止的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.