2016-04-14 141 views
0

有人能解释为什么我必须将“props.children”包裹在一个“div”中才能使react-router工作。使用React渲染props.children

这工作:

export default (props) => { 
     return (
      <div id="main-template"> 
       {props.children} 
      </div> 
     ); 
} 

然而,这并不:

export default (props) => { 
     return (
       {props.children} 
     ); 
} 

任何解释,将不胜感激。

+0

查看[react docs]的相关信息(https://facebook.github.io/react/tips/maximum-number-of-jsx-root-nodes.html) – Uzi

回答

2

如果你有一个子节点,你不需要包装props.children{},你可以只返回props.children

const Component = (props) => { 
    return props.children; 
}; 

Example

,如果你有一个以上的节点,例如

<p>1</p> 
<p>2</p> 
<p>3</p> 

you must wrap children一个根元素,因为组件必须返回只有一个根元素,你不能回几个,这样

return (
    <p>1</p> 
    <p>2</p> 
    <p>3</p> 
) 
2

JSX变换的HTML代码,寻找到JavaScript函数调用。返回多个顶层组件

return (
    <p>text</p> 
    <p>text</p> 
    <p>text</p> 
); 

被转化成

return (
    React.createElement('p', null, 'text'), 
    React.createElement('p', null, 'text'), 
    React.createElement('p', null, 'text') 
); 

这是无效的。由于您需要返回单个值,因此不能渲染多个顶级元素。 React团队一直在试图弄清楚如何处理这个问题,但目前还没有解决方案。