使用组件
现在你已经定义了 Profile
组件,你可以在其他组件中使用它。例如,你可以导出一个内部使用了多个 Profile
组件的 Gallery
组件:
function Profile() {
return (
<img
src="https://i.imgur.com/MK3eW3As.jpg"
alt="Katherine Johnson"
/>
);
}
export default function Gallery() {
return (
<section>
<h1>了不起的科学家</h1>
<Profile />
<Profile />
<Profile />
</section>
);
}
浏览器所看到的
注意下面两者的区别:
<section>
是小写的,所以 React 知道我们指的是 HTML 标签。<Profile />
以大写P
开头,所以 React 知道我们想要使用名为Profile
的组件。
然而 Profile
包含更多的 HTML:<img />
。这是浏览器最后所看到的:
<section>
<h1>了不起的科学家</h1>
<img src="https://i.imgur.com/MK3eW3As.jpg" alt="Katherine Johnson" />
<img src="https://i.imgur.com/MK3eW3As.jpg" alt="Katherine Johnson" />
<img src="https://i.imgur.com/MK3eW3As.jpg" alt="Katherine Johnson" />
</section>
嵌套和组织组件
组件是常规的 JavaScript 函数,所以你可以将多个组件保存在同一份文件中。当组件相对较小或彼此紧密相关时,这是一种省事的处理方式。如果这个文件变得臃肿,你也可以随时将 Profile
移动到单独的文件中。你可以立即在 关于引入的页面 中学习如何做到这些。
因为 Profile
组件在 Gallery
组件中渲染——甚至好几次!——我们可以认为 Gallery
是一个 父组件,将每个 Profile
渲染为一个“孩子”。这是 React 的神奇之处:你可以只定义组件一次,然后按需多处和多次使用。
组件可以渲染其他组件,但是 请不要嵌套他们的定义:
export default function Gallery() {
// 🔴 永远不要在组件中定义组件
function Profile() {
// ...
}
// ...
}
上面这段代码 非常慢,并且会导致 bug 产生。因此,你应该在顶层定义每个组件:
export default function Gallery() {
// ...
}
// ✅ 在顶层声明组件
function Profile() {
// ...
}