[英]Styled Component Button Extension
所以我的目標是擁有一個基本按鈕組件,然后是一個與基本按鈕具有相同標記但顯然具有不同樣式和動畫的變體按鈕。
我的基本文件是 button.js
import React from 'react';
import styled,{ keyframes, ThemeProvider} from 'styled-components';
import theme from '../../theme/default';
// import {rotatecw, rotateccw} from '../../../theme/keyframes';
const ButtonWrapper = styled.button`
position: relative;
color: ${(props) => props.theme.colors.primary};
width: 256px;
height: 64px;
line-height: 64px;
background: none;
border: 1px solid ${(props) => props.theme.colors.primary};
&:hover {
cursor: pointer;
color: ${(props) => props.theme.colors.grey};
border: 1px solid ${(props) => props.theme.colors.grey};
}
}
`;
const ButtonText = styled.span`
// transition: all 0.1s;
// tranform: scale(1, 1);
`;
function Button(props) {
return (
<ThemeProvider theme={theme}>
<ButtonWrapper>
<ButtonText>
{props.text}
</ButtonText>
</ButtonWrapper>
</ThemeProvider>
);
}
export default Button;
到現在為止還挺好。 我的 AnimatedButton 文件就是這樣
import React from 'react';
import Styled, { keyframes, ThemeProvider} from 'styled-components';
import theme from '../../theme/default';
import Button from '../../components/button/button'
// import {rotatecw, rotateccw} from '../../../theme/keyframes';
const rotatecw = keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`
const rotateccw = keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(-360deg);
}
`
const AnimatedButtonWrapper = Styled(Button)`
transition: all 0.3s;
&:before,
&:after {
content: '';
position: absolute;
width: 100%;
height: 100%;
bottom: 0;
left: 0;
z-index: 1;
transition: all 0.3s;
border: 1px solid ${(props) => props.theme.colors.primary};
}
&:hover {
cursor: pointer;
&:after {
animation-name: ${rotatecw};
animation-duration: 2s;
}
&:before {
animation-name: ${rotateccw};
animation-duration: 3s;
}
&:before,
&:after {
left: 96px;
width: 64px;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
`;
function AnimatedButton(props) {
return (
<ThemeProvider theme={theme}>
<AnimatedButtonWrapper>
</AnimatedButtonWrapper>
</ThemeProvider>
);
}
export default AnimatedButton;
讓我困惑的是底部。 似乎是重復......我如何確保它生成與 Button 相同的標記? 我希望我的動畫按鈕擴展標記和 css。 最終,有沒有辦法以這種方式調用我的按鈕
<Button animatedButton text="test"></Button>
當您使用styled(Button)
擴展Button
時,您實際上是在創建它的一個更具體的版本,並計划使用新的特定版本。
但是當您想將按鈕用作:
<Button animatedButton text="test"></Button>
這是一個將animatedButton
按鈕作為道具傳遞的變體,您希望將這些更改合並到ButtonComponent
本身中。
const ButtonWrapper = styled.button`
All the normal button stuff
${props.animated && `
All the animation stuff goes here
`}
`
function Button(props) {
return (
<ThemeProvider theme={theme}>
<ButtonWrapper animated={props.animatedButton}>
<ButtonText>
{props.text}
</ButtonText>
</ButtonWrapper>
</ThemeProvider>
);
}
如果您有很多這樣的變體,那么為這些創建樣式可能會令人痛苦。 這就是為什么styled-components
有一個輔助庫styled-theming
可以提供幫助。 (這對animated
部分沒有多大幫助,因為這幾乎是添加代碼而不是更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.