简体   繁体   English

我如何在 React 中动态更改 Fontawesome 图标?

[英]How can i change Fontawesome icons dynamically in React?

I am completely beginner at React.我完全是 React 的初学者。 I am working on Dice Project Game.我正在研究骰子项目游戏。 How can I change Fontawesome icons dynamically.如何动态更改 Fontawesome 图标。 Is it possible?是否可以? this is my code.这是我的代码。

Dice.js骰子.js

const Dice = ({ face }) => {
      return (
        <div>
          <FaDiceOne className={`dice ${face}`} />
        </div>
      );
    };
      



  Dices.js
  
    const Dices = (props) => {
      const [face, setFace] = useState["one"];
      const RollDiceHandler = () => {
        const sides = ["one", "two", "three", "four", "five", "six"];
        let side = sides[Math.floor(Math.random() * sides.length)];
        setFace(side);
      };
    
      return (
        <div>
      
            <div className="first_dice">
              
              <Dice face={face} />
            </div>
            <div className="second_dice">
             
              <Dice face={face} />
            </div>
          </div>
            <button onClick={RollDiceHandler}>Roll the Dice</button>
                  
        </div>
      );
    };
 

Something like this will do it, although there are many improvements you can make.像这样的东西就可以了,尽管你可以做很多改进。

const Dice = ({ face }) => {
    if (face === "one") {
      return (
        <div>
          <FaDiceOne className={`dice ${face}`} />
        </div>
      ); 
    }
if (face === "two") {
      return (
        <div>
          <FaDiceTwo className={`dice ${face}`} />
        </div>
      ); 
    }

};

Based on your code, the dice will always be the same value, since you only have one state variable for the face.根据您的代码,骰子将始终具有相同的值,因为您只有一个 state 面部变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM