【问题标题】:Style a styled-components within a wrapper在包装器中设置样式组件的样式
【发布时间】:2019-07-24 16:36:42
【问题描述】:

我想为一个样式化的 Button 添加一个动画和一个特定的高度。问题是,我的StyledButton 是一个包装器,它可以根据type 属性呈现多个预先设置样式的按钮之一,这些属性的样式为React Semantic UI Buttons

在此处查看带有复制的 CodeSandbox:

https://codesandbox.io/embed/practical-haibt-oz9sl

问题是它确实从ActionButton 获取样式,但它不应用我在const AnimatedButton = styled(StyledButton) 上放置的任何样式。

但是,如果我在没有包装器的情况下尝试同样的事情,直接通过导入BaseButton,并创建一个AnimatedBaseButton,这个可行但 删除了具有返回预样式按钮的 type 属性的模块化。

我在此处和 google/github 上进行了搜索,但没有反映此问题的问题。我知道我可以在StyledButton 上添加一个animation 属性并传递它,但是对于真正的代码库,这是不可能的。

提前致谢!

编辑:添加了 Codesandbox 而不是代码示例。

【问题讨论】:

    标签: javascript css reactjs styled-components


    【解决方案1】:

    快速修复:

    StyledButton.js:

    render() {
      const {
        content,
        icon,
        iconPosition,
        onClick,
        type,
        ...otherProps // take base props passed through wrapper
      } = this.props;
    
      // ...
    
      return (
        <ButtonToDisplay
          {...otherProps} // spread it firstly here so below props can override
          onClick={onClick}
          content={content}
        />
      );
    }
    

    为什么有效:

    如您所见,我们用于设置组件样式的styled(comp)'' 语法实际上是底层的 HOC 组件,它接收一个组件并返回另一个组件。

    因此,当您制作一个在styled componentreal component 之间进行拦截的包装器时,您需要允许库生成的props 通过该包装器。

    【讨论】:

    • 谢谢@DatLe,就是这样!!不知道我们必须通过道具,但它似乎合乎逻辑,因为它通过了className 道具!
    【解决方案2】:

    您在破坏 this.props 时忘记了 ...(扩展运算符)

    export default class StyledButton extends React.Component {
      render() {
        //     added ... (spread operator) 
        const {type, ...additionalProps} = this.props
        if (type === 'normal') return <NormalButton {...aditionalProps} />
        else if (type === 'action') return <ActionButton {...aditionalProps} />
      }
    }
    

    这里发生的情况是styled-component 传递了style 属性中的样式,但是如果没有展开运算符,您并没有传递它,您只是得到了一个名为additionalProps 的属性。

    【讨论】:

    • 感谢您指出这一点!根据您的评论,我决定花时间创建一个 Codesandbox 以避免 stackoverflow 编辑器出现代码格式问题。
    猜你喜欢
    • 2018-08-05
    • 1970-01-01
    • 2020-10-19
    • 2018-07-30
    • 2021-10-21
    • 2019-02-07
    • 2021-02-23
    • 2018-05-09
    • 1970-01-01
    相关资源
    最近更新 更多