css 如何< FontAwesomeIcon/>在按钮悬停时改变React颜色?

pgccezyw  于 2023-06-25  发布在  React
关注(0)|答案(4)|浏览(158)

我是React的新手,无法解决这个问题。基本上,我只想在悬停按钮时更改“FontAwesomIcon”标记的颜色,而不更改“span”标记内文本的颜色。我也在使用react-bootstrap。这是我的代码

<div class="tab">
   <Link to="/dataset-upload">
      <button class="tablinks" onClick={this.handleClick}>
            <FontAwesomeIcon icon={faCloudUploadAlt} size="lg"/> 
            <span>Dataset Upload</span>
      </button>
  </Link>
</div>

这是FontAwesomeIcon的CSS,

.tab button FontAwesomeIcon:hover{
    color: #86BC25;
}

如果我在CSS中用span替换FontAwesomeIcon,它就能工作。
我会很感激任何建议或忠告。

xesrikrc

xesrikrc1#

因为CSS可以做很多事情,所以我不会加倍。
但是,如果你想编写纯JSX而不使用styled-components或其他东西。
您可以使按钮mouseOver事件完全受控:

import React, { useState } from "react";
import "./styles.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCloudUploadAlt } from "@fortawesome/free-solid-svg-icons";

export default function App() {
  const [over, setOver] = useState(false);
  return (
    <div className="App">
      <button
        onMouseOver={() => setOver(true)}
        onMouseLeave={() => setOver(false)}
      >
        <FontAwesomeIcon
          icon={faCloudUploadAlt}
          size="lg"
          style={over ? { color: "red" } : {}}
        />
        <span>Dataset Upload</span>
      </button>
    </div>
  );
}

kpbpu008

kpbpu0082#

可以在FontAwesomeIcon组件上使用className属性。
所以只要写一个CSS规则:

.tablinks:hover .fa-icon {
  color: red;
}

然后将这个类赋予组件:

<FontAwesomeIcon icon={faCloudUploadAlt} size="lg" className="fa-icon" />
luaexgnf

luaexgnf3#

使用CSS你可以达到的结果,

**HTML:**在父div中添加一个className,比如upload-iconclassName,比如font-upload,比如FontAwesomeIcon

<div className="tab upload-icon">
 <Link to="/dataset-upload">
   <button className="tablinks" onClick={this.handleClick}>
   <FontAwesomeIcon
     icon={faCloudUploadAlt}
     size="lg"
     className="font-upload"
      />
    <span>Dataset Upload</span>
    </button>
  </Link>
</div>

**CSS:**悬停在父div upload-icon上时,更改font-upload的颜色,如,

.upload-icon:hover .font-upload {
  color: green;
}

Working sandbox

**注意:**请考虑使用className,而不是classRef Link

ttisahbt

ttisahbt4#

//as component, take value as prop, if we pass color as prop, then its value will be immutable

<FaTimesCircle className="fa-icon" />

//css file

.fa-icon{color:蓝紫色;}
.fa-icon:hover {color:rgb(255,72,72);}

相关问题