[英]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.