【问题标题】:Dynamic Component Name in ReactJSReactJS 中的动态组件名称
【发布时间】:2021-03-31 00:10:36
【问题描述】:

我正在使用react-icons 导入六个不同的骰子图标,如下所示:

import {
  FaDiceOne as DiceOne,
  FaDiceTwo as DiceTwo,
  FaDiceThree as DiceThree,
  FaDiceFour as DiceFour,
  FaDiceFive as DiceFive,
  FaDiceSix as DiceSix,
} from "react-icons/fa";

目前我在Dice 组件中使用这六个组件如下:

function Dice({num}) {
<div>
 {num === 'one' && <DiceOne />}
 {num === 'two' && <DiceTwo />}
 {num === 'three' && <DiceThree />}
 {num === 'four' && <DiceFour />}
 {num === 'five' && <DiceFive />}
 {num === 'six' && <DiceSix />}
</div>

}

export default Dice

这行得通——意思是,我可以做到以下几点:

import Dice from "./Dice";

...

<Dice num="four" />

这将使用我从react-icons 导入的FaDiceFour 图标

但是,在我看来,这并不是理想的情况。我真正想做的是使组件名称动态化。毕竟,每个组件的名称基本相同——只是编号不同。

本质上,我想要的是这样的:

// Dice.js
const function Dice() {

 <Dice{num} />

}

export default Dice

// other file
import Dice from './Dice'

<Dice num="Four" />

现在,我知道这行不通,但这是我试图传达的想法。我想要的是一种使用来自num prop 的 prop 值并使用它来动态生成组件名称的方法(然后必须像我目前拥有的那样进行一些条件检查)。

我想知道是否有办法通过反应来做到这一点。即,有没有办法根据传递给该组件的 prop 的值使组件名称动态化?如果有,怎么做?

谢谢。

【问题讨论】:

  • 你不应该从上面第一个 Dice 函数中的道具中解构num
  • 您将Dice 定义为函数表达式,并且同时使用const
  • @fortunee 我凭记忆写了这个问题,因此有一些错别字。我确实解构了num 属性,并且constfunction 没有重复。这些只是我的错别字(我更新了我的问题以删除这些错别字)。我的问题的重点是我是否可以用一行代码替换对num 属性值的六个条件检查,这将根据传递给num 属性的值呈现正确的图标组件。

标签: reactjs react-component


【解决方案1】:

我认为您正在寻找一种使 Dice 成为呈现组件的方法,该组件接受道具(即:num)并根据 num 的值呈现任何这些 React 图标:

您的 Dice 函数应该如下所示。

const Dice = ({ num }) => {
  return (
    <>
      {num === 'one' && <DiceOne />}
      {num === 'two' && <DiceTwo />}
      {num === 'three' && <DiceThree />}
      {num === 'four' && <DiceFour />}
      {num === 'five' && <DiceFive />}
      {num === 'six' && <DiceSix />}
    </>
  )
}

export default Dice; // if it's a different file

像这样使用它:

<Dice num={num} />

在此处查看工作示例https://stackblitz.com/edit/react-kwg3p9

【讨论】:

  • 实际上,这只是我刚刚修复的错字。我并不打算将{num} 排除在 Dice 组件的参数之外。我要做的是用一行代码替换所有num === "x" 参数,该代码根据传递的道具呈现正确的组件。想象一下,我有 1000 种不同的选择,而不是只有 6 种。我不想写 1000 个不同的条件检查。
猜你喜欢
  • 1970-01-01
  • 2015-05-04
  • 2015-07-04
  • 2016-11-19
  • 2021-01-02
相关资源
最近更新 更多