javascript 未捕获的错误:不变违规:React.render():无效的组件元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30600469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught Error: Invariant Violation: React.render(): Invalid component element
提问by wolfgang
I'm a react newbie
我是一个反应新手
and I'm Creating a simple class and function and rendering to the body.
我正在创建一个简单的类和函数并渲染到主体。
However,
然而,
I get an Uncaught Error: Invariant Violation: React.render(): Invalid component element.
我得到一个 Uncaught Error: Invariant Violation: React.render(): Invalid component element.
<script src="https://fb.me/react-0.13.3.js"></script>
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/jsx">
var HelloWorld = React.createClass({
render: function() {
return <div>Hello, world!</div>;
}
});
React.render(new HelloWorld(), document.body);
</script>
<body>
</body>
</html>
Any ideas on what is wrong?
关于什么是错的任何想法?
回答by wolfgang
use <HelloWorld/>
instead of new HelloWorld()
使用<HelloWorld/>
代替new HelloWorld()
回答by brettish
Change React.render(new HelloWorld(), document.body);
to React.render(React.createElement(HelloWorld), document.body);
and it should work. The React.render
function expects a ReactElement
which you can create via React.createElement
.
更改React.render(new HelloWorld(), document.body);
为React.render(React.createElement(HelloWorld), document.body);
它应该可以工作。 The React.render
函数需要 a ReactElement
,您可以通过React.createElement
.
You can see the docs here along with some other useful functions: https://facebook.github.io/react/docs/top-level-api.html
您可以在此处查看文档以及其他一些有用的功能:https: //facebook.github.io/react/docs/top-level-api.html
回答by corlaez
Writting the render method of your component like this will launch the same Error:
像这样编写组件的渲染方法将启动相同的错误:
...
render: function() {
return //you need "return <div>" for this to work.
<div>
<h4>MyComponent message</h4>
</div>;
}
The shown code will trigger the same error because there is now element next to the return (you shouldn't break the line there).
显示的代码将触发相同的错误,因为现在返回旁边有元素(您不应该在那里断行)。