【问题标题】:Have to render a react component based on props that changes a js variable必须基于改变 js 变量的 props 渲染一个反应组件
【发布时间】:2021-03-10 17:03:41
【问题描述】:

我已经从 react-icons 导入了 Dice 图标组件,但我希望它们根据从 Dice 组件传递的道具进行渲染。所以,我在 Dice.js 中创建了一个 js 变量来获取图标名称,但是在尝试渲染图标组件时,图标没有显示,而只有名称显示。下面是代码:

App.js:

import "./styles.css";
import Dice from './Dice';

export default function App() {
  return (
    <div className="App">
      Roll the Dice
      <Dice dice='One'/>
    </div>
  );
}

骰子.js:

import React, { Component } from "react";
import {
  FaDiceOne,
  FaDiceTwo,
  FaDiceThree,
  FaDiceFour,
  FaDiceFive,
  FaDiceSix
} from "react-icons/fa";

class Dice extends Component {
  constructor(props) {
    super();
    
  }

  render() {

    let randomDice = `FaDice${this.props.dice}`;
    console.log(randomDice);
    
    return (
      <div className="Dice">
        <randomDice/>
        <FaDiceTwo/>
        <FaDiceThree/>
        <FaDiceFour/>
        <FaDiceFive/>
        <FaDiceSix/>
        
      </div>
    );
  }
}

export default Dice;

我无法将 randomDice 变量呈现为 react-icon 组件。谁能帮我解决这个问题?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你可以创建一个对象,例如:

    const IconsByDice = {
      one: <FaDiceOne />,
      two: <FaDiceTwo />
      .....ans so on ....
    };
    

    并渲染一个组件:

    <div className="Dice">
     {IconsByDice[this.props.dice]}
      <FaDiceTwo/>
     ..... and so on ....
    </div>
    

    【讨论】:

    • 感谢您的回复。它正在工作?。你能帮我找出我的代码中的错误吗
    • 您正在尝试渲染一个名为 randomDice 的组件,该组件不存在。 randomDice 被视为字符串,而不是变量。
    • 哦,现在知道了。谢谢?
    • 很高兴为您提供帮助 :) 如果对您有帮助,请接受我的回答 :)
    猜你喜欢
    • 1970-01-01
    • 2019-07-26
    • 2023-04-03
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 2018-10-02
    • 2021-05-24
    • 2019-01-07
    相关资源
    最近更新 更多