我在 React 中有以下组件:
const Button = styled.div`
width: 30px;
height: 30px;
position: absolute;
right: 2em;
top: 50%;
transform: translateY(-50%);
padding: 0;
margin: 0;
&::before,
&::after {
content: "";
position: absolute;
background-color: #3d3935;
transition: transform 0.25s ease-out;
}
&::before {
top: 0;
left: 50%;
width: 4px;
height: 100%;
margin-left: -2px;
}
&::after {
top: 50%;
left: 0;
width: 100%;
height: 4px;
margin-top: -2px;
}
`;
它只是渲染一个带有库 Styled-components 的组件。它基本上显示了一个 +
符号。
但是,我想分别旋转每一行,使用:
&::before {
transform: rotate(${this.state.expanded ? '0' : '45'}deg);
}
&::after {
transform: rotate(${this.state.expanded ? '0' : '135'}deg);
}
并且它工作得很好,但不幸的是没有转换(它立即发生)。尝试在每一行中包含转换,但它仍然不会影响更改。
我尝试过的另一个解决方案是添加一个类,例如旋转
:
&.rotated::before {
transform: rotate(45deg);
}
但是样式组件并没有提供仅使用它的逻辑动态更改类的实际可能性。
期待任何形式的帮助,谢谢。
最佳答案
您可以尝试将条件 Prop 传递给组件。
import styled, { css } from 'styled-components';
<Button expanded={ this.state.expanded } />
然后在你的 SC 中:
const Button = styled.div`
transform: rotate(0deg);
transition: transform .2s ease-out;
${ props => props.expanded && css`
transform: rotate(45deg);
`};
`;
关于javascript - 向样式化组件添加过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44459813/