如何使用 styled-components 有条件地设置动画
How to conditionally animate with styled-components
我正在尝试在使用 styled-components 检查输入时为线条设置动画。
我试过使用 (a) 和不使用 (b) 关键帧,并且都 return (c):
(a)
import styled, { keyframes } from 'styled-components';
const Input = styled.input``
const NavIconLine = styled.span`
display: block;
position: absolute;
height: 3px;
`;
const Animation = keyframes`
from {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
width: 70%;
}
to {
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
width: 100%;
}
`;
const NavIconLine2 = styled(NavIconLine)`
width: 70%;
${Input}:checked ~ & {
animation: ${Animation} 0.15s ease-in-out;
}
`;
(b)
import styled from 'styled-components';
const Input = styled.input``
const NavIconLine = styled.span`
display: block;
position: absolute;
height: 3px;
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
-webkit-transition: 0.15s ease-in-out;
transition: 0.15s ease-in-out;
`;
const NavIconLine2 = styled(NavIconLine)`
width: 70%;
${Input}:checked ~ & {
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
width: 100%;
}
`;
(c)
function Component {
return (
<Input type="checkbox" id="menu" />
<NavIcon for="menu">
<NavIconLine1 />
</NavIcon>
)
}
我认为问题可能在于“${Input}:checked ~ & {...}”中元素的定位,因为“~ &”指的是同级而不是 parent的姐弟?如果是这样,是否可以针对它?
谢谢!
已解决:
条件不是写在后代上,而是写在 parent 的兄弟上:
const Input = styled.input`
display: whatever;
:checked + ${NavIcon} {
${NavIconLine1} {
animation: whatever;
}
}
`;
我正在尝试在使用 styled-components 检查输入时为线条设置动画。
我试过使用 (a) 和不使用 (b) 关键帧,并且都 return (c):
(a)
import styled, { keyframes } from 'styled-components';
const Input = styled.input``
const NavIconLine = styled.span`
display: block;
position: absolute;
height: 3px;
`;
const Animation = keyframes`
from {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
width: 70%;
}
to {
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
width: 100%;
}
`;
const NavIconLine2 = styled(NavIconLine)`
width: 70%;
${Input}:checked ~ & {
animation: ${Animation} 0.15s ease-in-out;
}
`;
(b)
import styled from 'styled-components';
const Input = styled.input``
const NavIconLine = styled.span`
display: block;
position: absolute;
height: 3px;
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
-webkit-transition: 0.15s ease-in-out;
transition: 0.15s ease-in-out;
`;
const NavIconLine2 = styled(NavIconLine)`
width: 70%;
${Input}:checked ~ & {
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
width: 100%;
}
`;
(c)
function Component {
return (
<Input type="checkbox" id="menu" />
<NavIcon for="menu">
<NavIconLine1 />
</NavIcon>
)
}
我认为问题可能在于“${Input}:checked ~ & {...}”中元素的定位,因为“~ &”指的是同级而不是 parent的姐弟?如果是这样,是否可以针对它?
谢谢!
已解决:
条件不是写在后代上,而是写在 parent 的兄弟上:
const Input = styled.input`
display: whatever;
:checked + ${NavIcon} {
${NavIconLine1} {
animation: whatever;
}
}
`;