我使用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" />

这是有效的,但我是关于造型在我的容器中的OCD . 我想要做的是创建一个样式组件来推送这些样式属性:

// styled.js
const StyledTrashIcon = styled(TrashIcon).attrs({
  fill: colors.white,
  activeFill: colors.sushi,
  hoverFill: colors.sushi,
})`
 // other styles
`;

但是当我尝试使用 StyledTrashIcon 时,我得到:

函数作为React子函数无效 . 如果返回Component而不是render,则可能会发生这种情况 . 或许你打算调用这个函数而不是返回它 .

改为:

const StyledTrashIcon = styled(TrashIcon()).attrs({

抛出此错误:

无法为组件创建样式组件:[object Object]