简体   繁体   English

如何设计 React-Icons 的样式

[英]How to Style React-Icons

I am trying to figure out how to style icons that I import using react-icons .我想弄清楚如何设置我使用react-icons导入的图标的样式。

In particular, I would like to be able to create a look similar to this:特别是,我希望能够创建类似于这样的外观: 在此处输入图像描述

That is to say, I'd like to add a background color, padding, border-radius, etc. However, I can't find an easy way to do that.也就是说,我想添加背景颜色、填充、边框半径等。但是,我找不到一种简单的方法来做到这一点。

I can add a size and color prop and that will change the actual size and color of the icon.我可以添加一个大小和颜色道具,这将改变图标的实际大小和颜色。 But there is no easy way for me to change the other elements.但是我没有简单的方法来更改其他元素。

Does anyone know how I can do this (or can they recommend a different library that can help me with this)?有谁知道我该怎么做(或者他们可以推荐一个可以帮助我的不同图书馆)?

Use IconContext as mentioned in the Docs .使用文档中提到的IconContext

function BlueLargeIcon() {
  return (
    <IconContext.Provider
      value={{ color: 'blue', size: '50px' }}
    >
      <div>
        <FaBeer />
      </div>
    </IconContext.Provider>
  );
}

在此处输入图像描述

To target specific Icon Components, you can use the style prop or use the same API (see Configurations ) on the component itself:要针对特定​​的图标组件,您可以使用style属性或在组件本身上使用相同的 API(请参阅配置):

const style = { color: "white", fontSize: "1.5em" }
<FaFacebookF style={style} />

// API
<FaFacebookF color="white" fontSize="1.5em" />

To whoever this may be helpful...对任何可能有帮助的人...

Colours of some icons cant be changed.某些图标的颜色无法更改。
For example, I tried to change the colour of { GrClose } icon by doing例如,我尝试通过更改{ GrClose }图标的颜色

<GrClose
    className="icon"
    style={{
      position: 'absolute',
      top: '20px',
      right: '20px',
    }}
    size="50px"
    color="white"
    onClick={handleExit}
/>

It just didn't change, when I replaced my icon with { AiOutlineClose } icon it worked!它只是没有改变,当我用{ AiOutlineClose }图标替换我的图标时它起作用了!

I think the easiest way here would be to just pass the className prop directly to the Icon you'd like to apply styles to.我认为这里最简单的方法是将className道具直接传递给您想要应用样式的图标。 Source Code in a CodeSandbox . CodeSandbox 中的源代码 I've used tailwindcss classes here, but you could use your own just as easily.我在这里使用了tailwindcss类,但您也可以轻松地使用自己的类。

import React from "react";
import "./styles.css";
import {
  FaFacebookF,
  FaTwitter,
  FaInstagram,
  FaPinterest
} from "react-icons/fa";

export default function App() {
  let circleClasses = "inline-block p-7 rounded-full w-20 mx-auto";
  let iconStyles = { color: "white", fontSize: "1.5em" };
  return (
    <div className="App grid grid-cols-2 sm:grid-cols-4 gap-2 w-3/4 mx-auto">
      <h1 className="col-span-full">Icon Demo</h1>
      <span style={{ background: "#3B5998" }} className={circleClasses}>
        <FaFacebookF style={iconStyles} />
      </span>
      <span style={{ background: "#1DA1F2" }} className={circleClasses}>
        <FaTwitter style={iconStyles} />
      </span>
      <span style={{ background: "black" }} className={circleClasses}>
        <FaInstagram style={iconStyles} />
      </span>
      <span style={{ background: "#BD081C" }} className={circleClasses}>
        <FaPinterest style={iconStyles} />
      </span>
    </div>
  );
}

If you'd like a little more context as to how this works, we can take a dive into the source code for react-icons.如果您想了解更多有关其工作原理的上下文,我们可以深入研究 react-icons 的源代码。 If you take a look at where the IconContext is defined within react-icons, you can see the allowed props:如果您查看在 react-icons 中定义 IconContext 的位置,您可以看到允许的道具:

export interface IconContext {
  color?: string;
  size?: string;
  className?: string;
  style?: React.CSSProperties;
  attr?: React.SVGAttributes<SVGElement>;
}

export const DefaultContext: IconContext = {
  color: undefined,
  size: undefined,
  className: undefined,
  style: undefined,
  attr: undefined,
};

export const IconContext: React.Context<IconContext> = React.createContext && React.createContext(DefaultContext);

Indeed, you're able to pass in color, size, style, additional svg attributes, and even a className string.实际上,您可以传递颜色、大小、样式、其他 svg 属性,甚至是 className 字符串。 But, this requires that you wrap the Icon component in the context.但是,这需要您将 Icon 组件包装在上下文中。

When you install react-icons, all of the icons are added into the node_modules directory in a format that looks like this:当您安装 react-icons 时,所有图标都以如下格式添加到 node_modules 目录中:

// THIS FILE IS AUTO GENERATED
var GenIcon = require('../lib').GenIcon
module.exports.Fa500Px = function Fa500Px (props) {
  return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 448 512"},"child":[{"tag":"path","attr":{"d":"M103.3 344.3c-6.5-14.2-6.9-18.3 7.4-23.1 25.6-8 8 9.2 43.2 49.2h.3v-93.9c1.2-50.2 44-92.2 97.7-92.2 53.9 0 97.7 43.5 97.7 96.8 0 63.4-60.8 113.2-128.5 93.3-10.5-4.2-2.1-31.7 8.5-28.6 53 0 89.4-10.1 89.4-64.4 0-61-77.1-89.6-116.9-44.6-23.5 26.4-17.6 42.1-17.6 157.6 50.7 31 118.3 22 160.4-20.1 24.8-24.8 38.5-58 38.5-93 0-35.2-13.8-68.2-38.8-93.3-24.8-24.8-57.8-38.5-93.3-38.5s-68.8 13.8-93.5 38.5c-.3.3-16 16.5-21.2 23.9l-.5.6c-3.3 4.7-6.3 9.1-20.1 6.1-6.9-1.7-14.3-5.8-14.3-11.8V20c0-5 3.9-10.5 10.5-10.5h241.3c8.3 0 8.3 11.6 8.3 15.1 0 3.9 0 15.1-8.3 15.1H130.3v132.9h.3c104.2-109.8 282.8-36 282.8 108.9 0 178.1-244.8 220.3-310.1 62.8zm63.3-260.8c-.5 4.2 4.6 24.5 14.6 20.6C306 56.6 384 144.5 390.6 144.5c4.8 0 22.8-15.3 14.3-22.8-93.2-89-234.5-57-238.3-38.2zM393 414.7C283 524.6 94 475.5 61 310.5c0-12.2-30.4-7.4-28.9 3.3 24 173.4 246 256.9 381.6 121.3 6.9-7.8-12.6-28.4-20.7-20.4zM213.6 306.6c0 4 4.3 7.3 5.5 8.5 3 3 6.1 4.4 8.5 4.4 3.8 0 2.6.2 22.3-19.5 19.6 19.3 19.1 19.5 22.3 19.5 5.4 0 18.5-10.4 10.7-18.2L265.6 284l18.2-18.2c6.3-6.8-10.1-21.8-16.2-15.7L249.7 268c-18.6-18.8-18.4-19.5-21.5-19.5-5 0-18 11.7-12.4 17.3L234 284c-18.1 17.9-20.4 19.2-20.4 22.6z"}}]})(props);
};

If we take a look at the source code for GenIcon we can get a bit more context for how this is working.如果我们看一下GenIcon源代码,我们可以得到更多关于它是如何工作的上下文。

import * as React from 'react';

import { IconContext, DefaultContext } from './iconContext';

export interface IconTree {
  tag: string;
  attr: {[key: string]: string};
  child: IconTree[];
}


function Tree2Element(tree: IconTree[]): React.ReactElement<{}>[] {
  return tree && tree.map((node, i) => React.createElement(node.tag, {key: i, ...node.attr}, Tree2Element(node.child)));
}
export function GenIcon(data: IconTree) {
  return (props: IconBaseProps) => (
    <IconBase attr={{...data.attr}} {...props}>
      {Tree2Element(data.child)}
    </IconBase>
  );
}

export interface IconBaseProps extends React.SVGAttributes<SVGElement> {
  children?: React.ReactNode;
  size?: string | number;
  color?: string;
  title?: string;
}

export type IconType = (props: IconBaseProps) => JSX.Element;
export function IconBase(props:IconBaseProps & { attr?: {} }): JSX.Element {
  const elem = (conf: IconContext) => {
    const {attr, size, title, ...svgProps} = props;
    const computedSize = size || conf.size || "1em";
    let className;
    if (conf.className) className = conf.className;
    if (props.className) className = (className ? className + ' ' : '') + props.className;

    return (
      <svg
        stroke="currentColor"
        fill="currentColor"
        strokeWidth="0"
        {...conf.attr}
        {...attr}
        {...svgProps}
        className={className}
        style={{ color: props.color || conf.color, ...conf.style, ...props.style}}
        height={computedSize}
        width={computedSize}
        xmlns="http://www.w3.org/2000/svg"
      >
      {title && <title>{title}</title>}
      {props.children}
    </svg>
    )
  };

  return IconContext !== undefined
    ? <IconContext.Consumer>{(conf: IconContext) => elem(conf)}</IconContext.Consumer>
    : elem(DefaultContext);
}

So, GenIcon is a function that accepts an object with an interface of IconTree which includes tag , attr and child properties.因此, GenIcon是一个函数,它接受具有 IconTree 接口的对象,其中包括tagattrchild属性。 We can see this in action in the generated code above.我们可以在上面生成的代码中看到这一点。 GenIcon returns a function itself. GenIcon返回一个函数本身。 This function accepts props as an argument which implements the IconBaseProps interface.此函数接受 props 作为实现IconBaseProps接口的参数。 The IconBaseProps interface extends React.SVGAttributes which include className and style . IconBaseProps接口扩展React.SVGAttributes ,其中包括classNamestyle Those are then passed as props to the IconBase component here:然后将它们作为道具传递给IconBase组件:

export function GenIcon(data: IconTree) {
  return (props: IconBaseProps) => (
    <IconBase attr={{...data.attr}} {...props}>
      {Tree2Element(data.child)}
    </IconBase>
  );
}

To get a sense of how IconBase actually works with respect to the IconContext let's check out its return statement:为了了解IconBase是如何与IconContext的,让我们看看它的 return 语句:

    return IconContext !== undefined
    ? <IconContext.Consumer>{(conf: IconContext) => elem(conf)}</IconContext.Consumer>
    : elem(DefaultContext);

Here, we can see that IconBase will invoke a function called elem (defined inside the body of IconBase ) either way.在这里,我们可以看到IconBase将调用一个名为elem的函数(在IconBase的主体中定义)。 So, IconBase will use the IconContext if one is defined, wrapping the returned element in IconContext.Consumer and calling elem with the IconContext .因此, IconBase将使用IconContext如果定义了一个,将返回的元素包装在IconContext.Consumer并使用IconContext调用elem But, if IconContext is not defined in this scope, IconBase will use the DefaultContext instead.但是,如果IconContext未在此范围内定义,则IconBase将使用DefaultContext代替。

To understand how this is working, we need to look at the elem function defined inside of IconBase .要了解这是如何工作的,我们需要查看在IconBase中定义的elem函数。 Here's the full source again:这是完整的来源:

  const elem = (conf: IconContext) => {
    const {attr, size, title, ...svgProps} = props;
    const computedSize = size || conf.size || "1em";
    let className;
    if (conf.className) className = conf.className;
    if (props.className) className = (className ? className + ' ' : '') + props.className;

    return (
      <svg
        stroke="currentColor"
        fill="currentColor"
        strokeWidth="0"
        {...conf.attr}
        {...attr}
        {...svgProps}
        className={className}
        style={{ color: props.color || conf.color, ...conf.style, ...props.style}}
        height={computedSize}
        width={computedSize}
        xmlns="http://www.w3.org/2000/svg"
      >
      {title && <title>{title}</title>}
      {props.children}
    </svg>
    )
  };

So, if you take a look at the code relating to className, you can see that we can actually add className to the Context and/or the props directly ( <FaFacebook className="bg-blue" /> ) and they'll actually be combined and applied to the returned svg所以,如果你看一下与 className 相关的代码,你会发现我们实际上可以将 className 添加到 Context 和/或 props 中( <FaFacebook className="bg-blue" /> ),它们实际上会被组合并应用于返回的svg

    let className;
    if (conf.className) className = conf.className;
    if (props.className) className = (className ? className + ' ' : '') + props.className;

Also, the styles defined in either the Context or the props will be combined and applied to the svg此外,在 Context 或 props 中定义的样式将被组合并应用于 svg

 style={{ color: props.color || conf.color, ...conf.style, ...props.style}}

One thing to note here is that all of the styles and classes are being applied directly to the returned svg element.这里要注意的一件事是所有样式和类都直接应用于返回的svg元素。 So, in your case, you'd probably need to have a wrapping element to build out the border-radius and background color and then apply the relevant styles for color and size directly to the svg.因此,在您的情况下,您可能需要一个包装元素来构建边框半径和背景颜色,然后将颜色和大小的相关样式直接应用于 svg。

Simply add "color" property to只需将“颜色”属性添加到

Like This:像这样:

<Icon color="blue" />
import {IconContext} from "react-icons";

class App extends component {

return (

<div>
<IconContext.Provider value={{ className="myReact-icons"}}>
       <FaBeer />
  </IconContext.Provider>
</div>
);  
}

css example below

.myreact-icons { color: red;
                 height: 40px;
               }

There is a simpler way to change the color of a react-icon.you can choose everything inside the svg icon with .icon > * use the css fill to fill the svg path.有一种更简单的方法可以更改 react-icon 的颜色。您可以使用.icon > *选择 svg 图标内的所有内容,使用 css fill来填充 svg 路径。

 ``` .icon > * { fill: #B3B3B3; } .icon > *:hover { fill: #747474; } ```

您可以通过简单地将颜色属性添加到图标来做到这一点,其他属性(如大小)也是如此。

<BiXCircle size={40} color="red" />
function blackReactIcons () {
     return(
             <div>
                 <FaTwitter fill='#000' />
                 <FaLinkedinIn fill='#000' />
                 <FaGithub fill='#000' />
             </div>

        );
}                

Although this is the technically correct answer according to React-Icons docs, it's much easier to just wrap the icon component in a div and add a className from which you can apply your styles like so: jsx尽管根据 React-Icons 文档,这在技术上是正确的答案,但将图标组件包装在 div 中并添加一个 className 可以更容易地应用您的样式,如下所示: jsx

<div className="social-icon twitter">
  <FaTwitter />
</div>

scss scss

.social-icon {
  height: 40px;
  width: 40px;
  border-radius: 50%;
  font-size: 1.5rem;
  &.twitter {
    background-color: $twitter-blue;
    color: $white;
    &:hover {
      color: $twitter-blue;
      background-color: $white;
    }
  }
}

React-Icons will inherit the styles of a parent element, hence why the context provider wraps the icon in a div, and you can't use sass within jsx so just skip all the unnecessary code and wrap it in a div. React-Icons 将继承父元素的样式,因此上下文提供程序将图标包装在 div 中,而您不能在 jsx 中使用 sass,因此只需跳过所有不必要的代码并将其包装在 div 中。

<HiOutlineInformationCircle
size= {40}
color="#777C92"
className = "m-1 cursor-pointer hover: stroke-[#E5765D]"
/>
It is so easy just capsule your **icon** in **span tag**

            <div className="social-icons">
              <span>
                <FaGithub/>
              </span>
            </div>

then style it using **CSS**

.social-icons span{
    margin: 10px;
    font-size: 20px;          
    color: var(--grey);        
}
         
.social-icons span:hover{
    color:black
}

You can export them as an object(s) with other properties and map through them.您可以将它们导出为具有其他属性的对象,并通过它们导出 map。

import { FaInstagram, FaTwitter } from 'react-icons/fa';

export const socialIcons = [
    {
        icon: <FaInstagram
            style={{ height: '30px', width: '30px' }}
        />,
        title: 'Instagram',
        link: '',
        color: '#C13584',
        isOpen: false,
        id: 'instagram',
    },
    {
        icon: <FaTwitter
        style={{ height: '30px', width: '30px' }}/>,
        title: 'Twitter',
        link: '',
        color: '#00acee',
        isOpen: false,
        id: 'twitter',
    },
];

import { socialIcons } from '../';

// ...
        <div>
            {socialIcons.map((social) => (
                <div>
                    <a href={social.link}>
                        <button style={{ color: social.color }}
                        id={social.id}>
                            {social.icon}
                        </button>
                    </a>
                </div>
            ))}
        </div>

Color changes on Grommet Icons don't apply.索环图标上的颜色更改不适用。 You can try with others either by passing a class and target it with css or directly inside <IconExample color={'blue'} />您可以通过传递一个类并使用 css 或直接在 <IconExample color={'blue'} /> 中与其他人一起尝试

In your styles.scss or css在你的 styles.scss 或 css

 .iconFaFacebook { color: blue; font-size: 2.5rem; }
 <FaFacebook className={styles.iconFaFacebook} />

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

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