[英]adding two classes (active class) using 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;
`;
我的 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;
}
}
有誰知道如何使用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} />
...
參考這里
要添加關鍵幀動畫,您需要使用keyframes
導入:
import { keyframes } from "styled-components";
const activeAnim = keyframes`
0% {
background-color: transparent;
}
50% {
background-color: #fff;
}
100% {
background-color: transparent;
}
`;
參考這里
您可以 擴展樣式以覆蓋某些屬性並保持其他屬性不變:
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>
)
}
您需要從 props 傳遞額外的className
:
const StyledDiv = sytled.div`
&.active {
border: blue;
}
`
class Example extends React.Component {
constructor(props) {
super(props)
}
render() {
const isActive = true; // you can dynamically switch isActive between true and false
return (
<StyledDiv
className={`button ${isActive ? 'active': ''} ${this.props.className}`}
onClick={ this.pressNumber }
>
<Number>{ this.props.number }</Number>
</StyledDiv>
)
}
}
const Number = styled.div`
color: #fff;
font-size: 26px;
font-weight: 300;
`;
祝你好運...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.