[英]React - Uncaught Invariant Violation:
在瀏覽器上運行代碼時,出現此錯誤消息。
未捕獲的不變違規:MyComponent.render():必須返回有效的React元素(或null)。 您可能返回了undefined,數組或其他無效對象。
我使用Atom作為代碼編輯器,並在chrome網絡服務器上運行。 這是我的代碼。
<body>
<div id="react-comp"></div>
<script type="text/babel">
var MyComponent = React.createClass({
render: function() {
return
<div>
<h1>{this.props.text}</h1>
</div>;
}
});
ReactDOM.render(
<div>
<MyComponent text="Hello World"/>
<MyComponent text="Hello"/>
</div>
, document.getElementById('react-comp'));
</script>
</body>
可能是jsx轉換問題? 還是其他東西?
return
后,您可能會遇到JavaScript自動分號插入的問題。 只需在div之前刪除換行符即可。
var MyComponent = React.createClass({
render: function() {
return <div> // Change this line
<h1>{this.props.text}</h1>
</div>;
}
});
只需將渲染功能更改為
var MyComponent = React.createClass({
render: function() {
return (
<div>
<h1>{this.props.text}</h1>
</div>
);
}
});
丹尼爾的建議也是正確的。
我不知道您使用的是哪個版本的React,因為我知道如果JSX語法未使用()包裝,則某些舊版本會出錯。 嘗試在MyComponent的render方法上執行此操作:
render: function() {
return (
<div>
<h1>{this.props.text}</h1>
</div>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.