【问题标题】:Displaying component based on prop value react根据道具值显示组件反应
【发布时间】:2020-10-09 21:48:14
【问题描述】:

我有四个组件 Rectangle、Circle、Triangle、Star。 根据用户在道具中提供的值,我想返回组件。例如,如果用户将道具作为 Rectangle,我想显示 Rectangle 组件。 我不想每次检查所有四个条件时都使用 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;

有人可以帮忙吗?提前致谢。

【问题讨论】:

  • 如果不想使用If-Else,可以考虑switch...

标签: reactjs components react-props conditional-rendering


【解决方案1】:

shape type -&gt; Component 定义一个静态映射。例如。假设 shape 类型在 prop 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" />

【讨论】:

  • 感谢您的回复!我是网络开发新手。你能告诉我这三个点是什么意思吗?
猜你喜欢
  • 2021-06-03
  • 1970-01-01
  • 2020-09-23
  • 2021-11-09
  • 2019-12-27
  • 1970-01-01
  • 2019-01-08
  • 2020-12-25
  • 1970-01-01
相关资源
最近更新 更多