在包装器中设置样式化组件的样式
Style a styled-components within a wrapper
我想向已设置样式的按钮添加动画和特定高度。问题是,我的 StyledButton
是一个包装器,可以根据样式为 React Semantic UI Buttons.
的 type
道具呈现多个预样式按钮之一
在此处查看带有复制的 CodeSandbox:
https://codesandbox.io/embed/practical-haibt-oz9sl
问题是它确实从 ActionButton
获取了样式,但它不应用我放在 const AnimatedButton = styled(StyledButton)
上的任何样式。
但是,如果我在没有包装器的情况下尝试同样的事情,直接通过导入 BaseButton
,并创建一个 AnimatedBaseButton
,这个可以工作但是
移除了 type
prop 的模块化,returns 是一个预先设置样式的按钮。
我在这里和 google / github 上搜索过,但没有反映这一问题的问题。我知道我可以在 StyledButton
上添加一个 animation
属性 并传递它,但是对于真正的代码库,这是不可能的。
提前致谢!
编辑:添加了 Codesandbox 而不是代码示例。
你在析构 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
。
快速修复:
在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 组件,它接收一个组件和 returns 另一个组件。
因此,当您创建一个在 styled component
和 real component
之间进行拦截的包装器时,您需要允许库生成的 props
通过该包装器。
我想向已设置样式的按钮添加动画和特定高度。问题是,我的 StyledButton
是一个包装器,可以根据样式为 React Semantic UI Buttons.
type
道具呈现多个预样式按钮之一
在此处查看带有复制的 CodeSandbox:
https://codesandbox.io/embed/practical-haibt-oz9sl
问题是它确实从 ActionButton
获取了样式,但它不应用我放在 const AnimatedButton = styled(StyledButton)
上的任何样式。
但是,如果我在没有包装器的情况下尝试同样的事情,直接通过导入 BaseButton
,并创建一个 AnimatedBaseButton
,这个可以工作但是
移除了 type
prop 的模块化,returns 是一个预先设置样式的按钮。
我在这里和 google / github 上搜索过,但没有反映这一问题的问题。我知道我可以在 StyledButton
上添加一个 animation
属性 并传递它,但是对于真正的代码库,这是不可能的。
提前致谢!
编辑:添加了 Codesandbox 而不是代码示例。
你在析构 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
。
快速修复:
在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 组件,它接收一个组件和 returns 另一个组件。
因此,当您创建一个在 styled component
和 real component
之间进行拦截的包装器时,您需要允许库生成的 props
通过该包装器。