【问题标题】:how to change color of a svg source in a img tag?如何更改 img 标签中 svg 源的颜色?
【发布时间】:2020-05-04 21:57:04
【问题描述】:

当提供颜色道具时,我正在尝试将 svg 图标的颜色从黑色更改为白色。

export class CategoryIconComponent extends React.Component {


static displayName = 'CategoryIcon';

  state = { icon: null };

  static propTypes = {
    title: PropTypes.string,
    color: PropTypes.string,
  };

  static defaultProps = {
    title: null,
    color: '#fff',
  };

  componentDidMount() {
    const { title } = this.props;

    if (getTopCategoryIcon('Concrete Contractors') != null){

    if(typeof getTopCategoryIcon('Concrete Contractors') === 'string'){
      this.setState({ icon: getTopCategoryIcon('Concrete Contractors') });
    }

   else{
      getTopCategoryIcon(title).then((newIcon) => {
        this.setState({ icon: newIcon });
      });
    }
  }
}

  render() {
    const { icon } = this.state;
    const { color } = this.props;

    return (
      icon && (
        <TextIconContainer>

           // I want to be able to change color of the icon from black to white via color prop here
           // something like
          <img src={icon} width={25} height={25} color={color} />
        </TextIconContainer>
      )
    );
  }

有没有 CSS 方法可以做到这一点?或任何其他方式我可以利用 svg 组件并更改它?

【问题讨论】:

    标签: javascript css reactjs svg ecmascript-6


    【解决方案1】:

    我不相信有办法通过图像标签放置 SVG,但我能够通过使用 SVG 作为简单的 React 组件来实现这一点:

    import React from 'react'
    
    export const MySvg = ({ color }) => (
      <svg style={{ fill: color }}>
        ...
        ...
      </svg>
    )
    
    

    然后在你的组件中使用:

    <MySvg color={color} />
    

    我不认为这是一种解决方法,也不是一种黑客行为——恰恰相反。使用这种技术,我已经能够实现一些令人印象深刻的主题化和自定义。

    显然你可以扩展这个方法来直接操作填充:

    export const MySvg = ({ color }) => (
      <svg fill={color}>
        ...
        ...
      </svg>
    )
    

    【讨论】:

    • 所以我需要使用 svg 组件来做到这一点?如何将我的外部 svg 信息传递给它?我正在从不同的位置获取我的 src
    • 为了使这个方法起作用,您需要拥有 SVG 的源代码。 SVG 只是代码——如果它适合你的使用,你可以下载 SVG,用文本编辑器打开,你会看到它只是 HTML。在我的回答中,&lt;svg&gt; ... &lt;/svg&gt; 标签代表 SVG 文件的代码。
    猜你喜欢
    • 2019-07-14
    • 2019-09-08
    • 2019-06-30
    • 2017-03-04
    • 2019-07-11
    • 2015-06-14
    • 2021-11-09
    • 2021-06-01
    • 1970-01-01
    相关资源
    最近更新 更多