Javascript 在包装器中设置已设置样式的组件的样式
我想添加一个动画和一个特定的高度按钮的样式。问题是,我的Javascript 在包装器中设置已设置样式的组件的样式,javascript,css,reactjs,styled-components,Javascript,Css,Reactjs,Styled Components,我想添加一个动画和一个特定的高度按钮的样式。问题是,我的StyledButton是一个包装器,它可以根据已设置样式的类型道具呈现多个预先设置样式的按钮之一 请参见此处的代码沙盒和复制: 问题是它确实从ActionButton获取了样式,但它不应用我在const AnimatedButton=styled(StyledButton)上设置的任何样式 但是,如果我在没有包装器的情况下尝试同样的事情,直接导入BaseButton,并创建一个AnimatedBaseButton,这一个就可以了 删除了
StyledButton
是一个包装器,它可以根据已设置样式的类型
道具呈现多个预先设置样式的按钮之一
请参见此处的代码沙盒和复制:
问题是它确实从ActionButton
获取了样式,但它不应用我在const AnimatedButton=styled(StyledButton)
上设置的任何样式
但是,如果我在没有包装器的情况下尝试同样的事情,直接导入BaseButton
,并创建一个AnimatedBaseButton
,这一个就可以了
删除了使用返回预设样式按钮的类型
道具的模块性
我在这里和google/github上搜索过,但没有反映这一点的问题。我知道我可以在StyledButton
上添加animation
属性并传递它,但是使用真正的代码库,这是不可能的
提前谢谢
编辑:添加了一个代码沙盒而不是代码示例。您在销毁
此道具时忘记了..
(扩展运算符)
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} />
}
}
导出默认类StyledButton扩展React.Component{
render(){
//添加…(排列运算符)
const{type,…additionalProps}=this.props
如果(类型==‘正常’)返回
else if(type==“action”)返回
}
}
这里发生的是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}
/>
);
}
render(){
常数{
内容,,
偶像
iconPosition,
onClick,
类型,
…其他道具//通过包装器获取基本道具
}=这是道具;
// ...
返回(
);
}
工作原理:
正如您所看到的,styled(comp)“
我们用来设置组件样式的语法实际上是一个隐藏的HOC组件,它接收一个组件并返回另一个组件
因此,当您制作一个在样式化组件
和真实组件
之间拦截的包装器时,您需要允许库生成的道具
通过该包装器。感谢您指出这一点!根据您的评论,我决定花时间创建一个Codesandbox,以避免stackoverflow编辑器的代码格式问题。谢谢@DatLe,正是这样!!我不知道我们必须通过道具,但它通过className
prop!!