为了账号安全,请及时绑定邮箱和手机立即绑定

在包装器中设置样式组件的样式

在包装器中设置样式组件的样式

qq_笑_17 2021-08-20 17:45:39
我想向样式化的按钮添加动画和特定高度。问题是,myStyledButton是一个包装器,可以根据type样式为React Semantic UI Buttons的道具呈现多个预样式按钮之一。在此处查看带有复制的 CodeSandbox:https://codesandbox.io/embed/practical-haibt-oz9sl事情是它得到从样式ActionButton,但它并不适用于任何风格我穿上const AnimatedButton = styled(StyledButton)。但是,如果我在没有包装器的情况下尝试同样的事情,直接通过导入BaseButton, 并创建 a AnimatedBaseButton,这个可以工作,但删除了具有type返回预样式按钮的道具的模块化。我在这里和 google/github 上搜索过,但没有反映这一问题的问题。我知道我可以在 上添加一个animation属性StyledButton并传递它,但是对于真正的代码库,这是不可能的。提前致谢!编辑:添加了 Codesandbox 而不是代码示例。
查看完整描述

2 回答

?
不负相思意

TA贡献1777条经验 获得超10个赞

快速修复:

在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 组件,它接收一个组件并返回另一个组件。


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


查看完整回答
反对 回复 2021-08-20
?
ITMISS

TA贡献1871条经验 获得超8个赞

您...在破坏时忘记了(扩展运算符)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在styleprop中传递样式,但是如果没有扩展运算符,你不会传递它,你只是得到一个名为additionalProps.


查看完整回答
反对 回复 2021-08-20
  • 2 回答
  • 0 关注
  • 240 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号