pet*_*gan 8 javascript css reactjs styled-components
我正在从css迁移到styled-components
.
我的反应组件如下所示:
class Example extends React.Component {
........code here
render() {
return (
<div
className={ this.state.active ? "button active" : "button" }
onClick={ this.pressNumber }
>
<Number>{ this.props.number }</Number>
</div>
)
}
}
const Number = styled.div`
color: #fff;
font-size: 26px;
font-weight: 300;
`;
Run Code Online (Sandbox Code Playgroud)
我的CSS看起来像这样:
.button {
height: 60px;
width: 60px;
}
.active {
animation-duration: 0.5s;
animation-name: highlightButton;
}
@keyframes highlightButton {
0% {
background-color: transparent;
}
50% {
background-color: #fff;
}
100% {
background-color: transparent;
}
}
Run Code Online (Sandbox Code Playgroud)
有谁知道如何使用styled-components
?添加活动类/添加两个类到元素?从文档中没有任何东西向我跳出来.
如果有任何不清楚或需要进一步的信息,请告诉我.
样式化组件中的模板文字可以访问props:
const Button = styled.button`
height: 60px;
width: 60px;
animation: ${
props => props.active ?
`${activeAnim} 0.5s linear` :
"none"
};
`;
...
<Button active={this.state.active} />
...
Run Code Online (Sandbox Code Playgroud)
参考这里
要添加关键帧动画,您需要使用keyframes
导入:
import { keyframes } from "styled-components";
const activeAnim = keyframes`
0% {
background-color: transparent;
}
50% {
background-color: #fff;
}
100% {
background-color: transparent;
}
`;
Run Code Online (Sandbox Code Playgroud)
参考这里
您可以扩展样式以覆盖某些属性并保持其他属性不变:
render() {
// The main Button styles
const Button = styled.button`
height: 60px;
width: 60px;
`;
// We're extending Button with some extra styles
const ActiveButton = styled(Button)`
animation-duration: 0.5s;
animation-name: highlightButton;
`;
const MyButton = this.state.active ? ActiveButton : Button;
return (
<MyButton onClick={this.pressNumber}>
<Number>{ this.props.number }</Number>
</MyButton>
)
}
Run Code Online (Sandbox Code Playgroud)