问题
Consider this example which won't compile:
/** @jsx React.DOM */
var Hello = React.createClass({
render: function() {
return <div>Hello</div>;
}
});
var World = React.createClass({
render: function() {
return <div>World</div>;
}
});
var Main = React.createClass({
render: function() {
return (
<Hello />
<World />
);
}
});
React.renderComponent(<Main />, document.body);
But any of these combinations does work:
<div>
<Hello />
<World />
</div>
<Hello />
//<World />
//<Hello />
<World />
Wanted to know if multiple components should always be surrounded by div tags.
回答1:
I think the render function should return only one component.
From the docs: http://facebook.github.io/react/docs/component-specs.html
The render() method is required.
When called, it should examine this.props and this.state and return a single child component
回答2:
There's a simple way to get around this limitation:
var Hello = React.createClass({
render: function() {
return <div>Hello</div>;
}
});
var World = React.createClass({
render: function() {
return <div>World</div>;
}
});
var HelloWorld = [Hello, World];
var Main = React.createClass({
render: function() {
return (
{HelloWorld}
);
}
});
React.renderComponent(<Main />, document.body);
回答3:
React components can only render a single root node. If you want to return multiple nodes they must be wrapped in a single root.
As specified on the Official React Site: React Docs
来源:https://stackoverflow.com/questions/22280315/when-multiple-react-dom-components-are-used-without-outer-div-then-jsx-wont-com