提供颜色道具时,我试图将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>
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句