我已经看到组件似乎总是包含在HTML标签中的模式。
我搜索the docs以检查这是否是强制性的,但未在主题上找到任何内容。
如果上述情况不正确,为什么我会在第一个代码示例上出错,而不是在第二个代码示例上出错?
const App = (props) => {
return (
<Header />
{props.children}
);
};
const App = (props) => {
return (
<div>
<Header />
{props.children}
</div>
);
};
答案 0 :(得分:2)
不,不需要将渲染包装在div
或其他html元素中,您可以使用Component作为根元素进行渲染。但是,您不能有多个根元素,这就是您在第一个示例中收到错误的原因。但是,以下内容可行:
render() {
<Header>
<h1>Hello World</h1>
<p>Lorem ipsum</p>
</Header>
}
最后,您仍然可能必须在Header组件中使用某种包装器div
,因为您不能有超过1个根元素。
我确实读过React团队正在研究的内容,并且新的协调程序支持多个根元素,但它还远没有完成。
答案 1 :(得分:2)
You don't have to wrap them specifically in HTML tags. You could wrap them in a custom component instead.
The error you're getting is because a component has to return a single node, which is why you can't do this:
// WRONG
const App = (props) => {
return (
<Header />
{props.children}
);
};