基于 prop 值反应显示组件
Displaying component based on prop value react
我有四个组成部分:矩形、圆形、三角形、星形。
根据用户在 props 中给出的值,我想 return 该组件。例如,如果用户将道具作为矩形提供,我想显示矩形组件。
我不想每次检查所有四个条件时都使用 If-Else 语句。还有更好的选择吗?
例如:矩形组件
import React from "react";
function Rectangle(props) {
return (
<div className="term">
<svg width="400" height="110">
<rect
width="300"
height="100"
stroke="black"
stroke-width="3"
/>
</svg>
</div>
);
}
export default Rectangle;
有人可以帮忙吗?提前致谢。
为 shape type -> Component
定义一个静态映射。例如。假设形状类型在道具 shape
:
中提供
const Shapes = {
rectangle: Rectangle,
circle: Circle,
triangle: Triangle,
star: Star,
};
const Shape = ({shape, ...props}) => {
const ActualShape = Shapes[shape];
return <ActualShape {...props} />;
};
用法示例:
<Shape shape="circle" r="10" stroke="red" />
<Shape shape="rectangle" stroke="black" width="300" height="100" />
我有四个组成部分:矩形、圆形、三角形、星形。 根据用户在 props 中给出的值,我想 return 该组件。例如,如果用户将道具作为矩形提供,我想显示矩形组件。 我不想每次检查所有四个条件时都使用 If-Else 语句。还有更好的选择吗?
例如:矩形组件
import React from "react";
function Rectangle(props) {
return (
<div className="term">
<svg width="400" height="110">
<rect
width="300"
height="100"
stroke="black"
stroke-width="3"
/>
</svg>
</div>
);
}
export default Rectangle;
有人可以帮忙吗?提前致谢。
为 shape type -> Component
定义一个静态映射。例如。假设形状类型在道具 shape
:
const Shapes = {
rectangle: Rectangle,
circle: Circle,
triangle: Triangle,
star: Star,
};
const Shape = ({shape, ...props}) => {
const ActualShape = Shapes[shape];
return <ActualShape {...props} />;
};
用法示例:
<Shape shape="circle" r="10" stroke="red" />
<Shape shape="rectangle" stroke="black" width="300" height="100" />