when multiple React DOM components are used without outer div then JSX won't compile

烈酒焚心 提交于 2020-01-03 15:57:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!