簡體   English   中英

如何將樣式應用於一組 SVG 元素

[英]How to apply style to an array of SVG elements

我有一組.svg圖標,其中每個圖標都有一些我需要覆蓋的屬性:

<svg width="24" height="24" viewBox="0 0 24 24"> ... </svg>
import styled from 'styled-components';

import Github from 'assets/github.svg';
import Facebook from 'assets/facebook.svg';
import Twitter from 'assets/twitter.svg';
...

const icons = [
  <Github />,
  <Facebook />,
  <Twitter />,
  ...
];

我想為每個圖標應用相同的樣式,而無需重復代碼和使用CSS-in-JS

到目前為止,我的解決方案有一些問題:

// Works but,
// I want to use CSS-in-JS like styled-components
// for easier maintenance
const iconStyle = {
  width: 50,
  height: 50
};

const SocialBar = () => (
  <IconBar as={FlexBox}>
    {icons.map((icon, key) => (
      <div key={key}>{React.cloneElement(icon, iconStyle)}</div>
    ))}
  </IconBar>
);
// Works but,
// there are too many icons
const SocialBar = () => (
  <IconBar as={FlexBox}>
    <Github style={iconStyle} />
    <Facebook style={iconStyle} />
    ...
  </IconBar>
);

像這樣的樣式svg組件將不起作用:

// Won't override the width="24" height="24" properties
const StyledIcon = styled(Github)`
  width: 50;
  height: 50;
`;

您可以用一個元素(如i )包裹 SVG 並使用在樣式組件中定義的一些 CSS 為其中的任何svg子項設置樣式(您也可以以gpath為目標)。 不幸的是,SVG 使用起來非常棘手,因此您可能需要手動將 SVG xml 復制/粘貼到 JS 文件中(如果您使用的是CRA ,則可以從 SVG導入ReactComponent )。

工作示例(將 SVG 復制/粘貼到 JS 文件中——第一個示例是默認值,第二個示例傳入 props,第三個示例傳入多個 props):

編輯樣式化 SVG 組件


圖標/ Icon.js(此組件接受生成的風格的部件className和任何children放在它里面)

import React from "react";
import PropTypes from "prop-types";

const Icon = ({ className, children }) => (
  <i className={className}>{children}</i>
);

Icon.propTypes = {
  className: PropTypes.string.isRequired,
  children: PropTypes.node.isRequired
};

export default Icon;

Icon/index.js (這將為上面的Icon組件設置樣式;隨后它將為children組件設置樣式)

import styled from "styled-components";
import Icon from "./Icon";

const StyledIcon = styled(Icon)`
  margin: 0 20px;
  svg {
    fill: ${({ fill }) => fill || "#03a9f3"};
    height: ${({ dimension }) => dimension || "50px"};
    width: ${({ dimension }) => dimension || "50px"};
  }
`;

export default StyledIcon;

這是一種方法。

//Github.js
import React from "react";
export default function Github({height, width}) {
    return (
        <svg width={width} height={height} viewBox="0 0 24 24"> ...  </svg>
    );
}

然后你想在哪里使用它。

<Github height={24} width={24} />

相對於您已有的代碼示例,我不完全確定您的要求是什么。 你想避免使用React.cloneElement嗎? 將圖標數組作為函數,而不是 jsx 元素。 mapmap到 jsx 版本並將樣式應用於每個

const icons = [
  Github,
  Facebook,
  Twitter,
]

buildIcons() {
  const style = {
    //..
  }
  return icons.map((icon, idx) => (
    <icon style={style} key={idx}/>
  ))

}

使用索引作為鍵是可行的,但如果您能找到每個圖標獨有的不同屬性,那就更好了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM