在React中使用枚举进行条件渲染的好例子



我正在研究React中条件渲染的良好实践,我真的很喜欢ENUM模式,但我正在寻找一些使用它的好例子。我发现的教程有点过于简单/简短,我希望看到一个更充实的例子。

我不知道你是否会认为这是完全相同的模式,但看到没有其他人添加任何东西——这是我通常最能利用类似概念的地方。

假设您有一个数据列表,其中包含具有type属性的对象,该属性具有一定数量的已知值,比如'Car' | 'Boat' | 'Plane'

现在您想向用户显示这些对象,但每种类型的视图都有很大不同,这是ENUM模式可以提供帮助的实例之一。

示例:组件映射

const data = [
{
type: 'Car',
uniqueCarProperty: 'I am a unique car property'
},
{
type: 'Boat',
uniqueBoatProperty: 'I am a unique boat property'
},
{
type: 'Plane',
uniquePlaneProperty: 'I am a unique plane property'
},
{
type: 'Tractor',
uniqueTractorProperty: 'I am a unique tractor property'
}
];
// Component for view unique to vehicles of type 'Car'
const CarComponent = ({ uniqueCarProperty }) => {
return (
<div>
Car: {uniqueCarProperty}
</div>
);
}
// Component for view unique to vehicles of type 'Boat'
const BoatComponent = ({ uniqueBoatProperty }) => {
return (
<div>
Boat: {uniqueBoatProperty}
</div>
);
}
// Component for view unique to vehicles of type 'Plane'
const PlaneComponent = ({ uniquePlaneProperty }) => {
return (
<div>
Plane: {uniquePlaneProperty}
</div>
);
}
// Component mapping used to link vehicle type to appropriate view.
// Property name must match type value (case sensitive)
const componentMapping = {
Car: CarComponent,
Boat: BoatComponent,
Plane: PlaneComponent
}
const ExampleComponent = ({ vehicles }) => {
return (
<div>
{vehicles && vehicles.map((v, i) => {
// retrieve type from vehicle data.
const { type, ...props } = v;
// get component mapping using type.
const Component = componentMapping[type];
// handle unknown types
if (!Component) {
return (
<div key={i}>Unsupported vehicle type: {type}</div>
)
}
// render mapped component
// all vehicle data except type is provided to the component as props.
return (
<Component key={i} {...props} />
)
})}
</div>
)
};
const App = ({}) => {
return (
<ExampleComponent vehicles={data} />
)
}

组件映射不必保持为组件外部的常量。它可以作为道具传入,也可以在组件本身中构造。

安"enum";(实际上更像是一个字典或映射(与switch语句或条件结构完全相同。它提高了可读性,因为它是一个表达式,而不是语句,这很好,但仅此而已。

在本文中解释的所有技术中,高级组件是唯一能够真正帮助您设计视图逻辑的技术。

顺便说一下;嵌套的";文章中的条件句不是嵌套的,它们只是if、else if和else的序列。当您有两个或多个相邻的?序列时,您可以识别嵌套的三进制。

最新更新