【发布时间】:2018-11-15 02:02:37
【问题描述】:
我正在使用 React 来帮助管理我的 SVG 图标:
const Trash = ({
fill, width, height,
}) => (
<svg width={ `${width}px` } height={ `${height}px` } xmlns="http://www.w3.org/2000/svg" id="Layer_1" data-name="Layer 1" viewBox="0 0 17.92 20.42">
<path style={ { fill } } d="M14,20.3H3.91a0.5,0.5,0,0,1-.5-0.47l-0.89-14A0.5,0.5,0,0,1,3,5.35H14.9a0.5,0.5,0,0,1,.5.53l-0.89,14A0.5,0.5,0,0,1,14,20.3Zm-9.63-1h9.16l0.83-13H3.56Z" />
<rect style={ { fill } } x="5.69" y="5.84" width="1" height="13.98" transform="translate(-0.68 0.35) rotate(-3.1)" />
...
</svg>
);
我根据包装器中的状态管理更改颜色:
const makeIcon = Icon => props => <IconWrapper { ...props }><Icon /></IconWrapper>;
export const TrashIcon = makeIcon(Trash);
包装器看起来像这样(大量删节):
class IconWrapper extends Component {
constructor(props) {
super(props);
this.state = {
isActive: false,
isHovered: false,
};
}
handleClick(e) {
if (this.props.onClick) {
this.props.onClick(e);
}
this.setState({
isActive: !this.state.isActive,
});
}
...
render() {
const Icon = React.cloneElement(
this.props.children,
{
isActive: this.state.isActive,
fill: this.getFill(),
width: this.props.width,
height: this.props.height,
},
);
return (
<button
onClick={ this.handleClick }
ref={ this.setWrapperRef }
width={ this.props.width }
height={ this.props.height }
>
{ Icon }
</button>);
}
}
所以,我希望将我的图标添加到容器组件中。我可以这样添加:
<TrashIcon fill="#fff" activeFill="#000" />
这行得通,但我对在我的容器中设置样式感到很着迷。我想做的是创建一个样式化的组件来下推这些样式属性:
// styled.js
const StyledTrashIcon = styled(TrashIcon).attrs({
fill: colors.white,
activeFill: colors.sushi,
hoverFill: colors.sushi,
})`
// other styles
`;
但是当我尝试使用 StyledTrashIcon 时,我得到:
函数作为 React 子级无效。如果您返回一个组件而不是从渲染中返回,则可能会发生这种情况。或者,也许您打算调用这个函数而不是返回它。
改为:
const StyledTrashIcon = styled(TrashIcon()).attrs({
抛出此错误:
无法为组件创建样式化组件:[object Object]
【问题讨论】:
-
你可以这样试试吗:
const StyledTrashIcon = styled(TrashIcon)().attrs({ -
试试SVGR,它会从SVG文件生成JSX,并允许使用react语法控制
<svg>的props -
如果您的组件使用
const-const StyledTrashIcon = styled(Trash)`...`,您应该在您的组件之后定义样式组件