[英]how to change color of a svg source in a img tag?
当提供颜色道具时,我试图将 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 组件并更改它?
我不相信有一种方法可以通过图像标签放置 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>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.