可以在一个组件内声明其他组件吗? [英] It's okay to declare other components inside a component?
问题描述
想象一下,我的 React 应用程序中有一个卡片列表.所以我将有两个组件,
和
.我的疑问是,在我工作的地方,当我们遇到这样的事情时,我们通常会在 <ListCard/>
中声明一个名为 Card
的变量来接收 JSX,但是我不知道这是不是一件好事.最近我在使用这种方法时遇到了一些问题,但我没有发现有人说要不要这样做.
想象一下,我没有在应用程序的任何地方使用
我们声明ListCard
的方式const ListCard = () =>{常量卡 = [{ 标题: '1', id: 1 },{标题:'2',ID:2},];const Card = ({ title }) =><div>{title}</div>;返回 (<div><h1>卡片列表</h1>{cards.map(card => (<卡片标题={card.title} key={card.id}/>))}
);};
我想知道像这样在 ListCard 之外声明是否更好.
const Card = ({ title }) =><div>{title}</div>;const ListCard = () =>{常量卡 = [{ 标题: '1', id: 1 },{ 标题: '2', id: 2 },];返回 (<div><h1>卡片列表</h1>{cards.map(card => (<卡片标题={card.title} key={card.id}/>))}
);};
在同一个文件中声明另一个 Component
是完全没问题的,但是在另一个函数中声明它是低效的.想象一下您的应用在每次 render
期间重新创建"第二个 Component
.
所以,请随意在同一个文件中声明它,但不要在另一个Component
的函数中声明.
Imagine that I have a List of Cards on my react application. So I will have two components, the <ListCard />
and <Card />
.
My doubt is that where I work, when we have something like this, we usually declare a variable inside the <ListCard />
named Card
that receives a JSX, but I don't know if this is a good thing to do. Recently I faced some problems with this approach, but I didn't find anyone saying to do it or not.
Imagine that I'm not using the <Card />
anywhere in the application
The way we would declare the ListCard
const ListCard = () => {
const cards = [
{ title: '1', id: 1 },
{ title: '2', id: 2 },
];
const Card = ({ title }) => <div>{title}</div>;
return (
<div>
<h1>List of Cards</h1>
{cards.map(card => (
<Card title={card.title} key={card.id} />
))}
</div>
);
};
I want to know if it's better to declare outside of the ListCard, like this.
const Card = ({ title }) => <div>{title}</div>;
const ListCard = () => {
const cards = [
{ title: '1', id: 1 },
{ title: '2', id: 2 },
];
return (
<div>
<h1>List of Cards</h1>
{cards.map(card => (
<Card title={card.title} key={card.id} />
))}
</div>
);
};
It is totally fine to declare another Component
in the same file, but declaring it inside another one's function would be inefficient. Imagine your app 'recreating' the second Component
during each render
.
So, feel free to declare it in the same file, but don't do it inside another Component
's function.
这篇关于可以在一个组件内声明其他组件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!