javascript - React:在组件首次安装时停止运行样式化组件动画
问题描述
我有一个styled-component
接收道具来确定要使用的动画。这是控制一个箭头图标,当活动时旋转“打开”,非活动时保持“关闭”。
这是styled-component
和 两个keyframes
动画的样子:
const rotate_down = keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(90deg);
}
`;
const rotate_up = keyframes`
from {
transform: rotate(90deg);
}
to {
transform: rotate(0deg);
}
`;
const OpenUserSettings = styled.div`
cursor: pointer;
width: 20px;
height: 20px;
transition: 0.3s;
animation: ${props => (props.rotate ? rotate_down : rotate_up)} 0.5s ease
forwards;
margin-top: 2px;
box-sizing: border-box;
display: flex;
justify-content: center;
align-items: center;
& > img {
width: 5px;
}
`
传入的rotate
prop 是一个布尔值,通过onClick
React 组件中的处理程序进行切换:
<OpenUserSettings
rotate={arrowDown}
onClick={() => {
this.setState(prevState => ({
arrowDown: !prevState.arrowDown
}));
}}
>
<img src={OpenArrow} alt="menu drop down arrow" />
</OpenUserSettings>
这是有效的,当点击箭头时,rotate
prop 被传入并成功在和OpenUserSettings
之间切换。rotate_up
rotate_down
keyframes
现在我的问题是,当 React 组件第一次挂载时,arrowDown
默认设置为 false,这意味着rotate
prop 将是 false。这会导致将styled-component
动画设置rotate_up
为第一次安装。我认为这很难想象,所以看看这个看看我在描述什么:
您可以看到页面刷新时rotate_up
动画非常快速地触发。我需要箭头保持关闭状态,但我不需要rotate_up
在第一次加载时触发动画来关闭它。这是react-transition-group
我可以控制初始输入的情况还是可以用逻辑处理的情况?
解决方案
我对堆栈溢出的第一个贡献,多么令人兴奋!
为了确保动画不会在挂载时呈现,请将您的状态初始化为真/假,我记得最初将我的状态设置为 null。
在您的样式化组件中,您可以将 null / true / false 作为 prop 传递,并在组件外部定义一个对 null / true / false 执行检查的函数。(我使用了 TypeScript,所以不要复制类型)
function showAnimationOrNot(status: boolean | null) {
if (status === true) {
return `animation: nameAnimationIn 1s ease forwards;`
} else if (status === false) {
return `animation: nameAnimationOut 1s ease-out forwards;`
} else if (status === null) {
return ""
}
}
在您的样式组件中,只需添加一行:
${(props: PropsDisplay) => show(props.show)};
我就是这样做的,我相信还有更优雅的方法,但它确实起到了在安装时预先制作动画的技巧。
作为回报,如果有人知道如何在函数的返回中突出显示样式化的组件语法,例如我在这里使用的函数(来自上面的示例):
return `animation: comeout 1s ease-out forwards;`
一定要告诉我!寻找那个!谢谢你,祝你好运!
继续动画!:)
推荐阅读
- git - Git 将旧提交添加到当前分支并执行 PR
- java - 在 Spring Boot 2.4 中使用我的配置文件 dev 覆盖属性
- python-3.x - PicklingError:无法在 Pyspark 中序列化对象
- linux - 为我的硬件定位以字符串开头的文件
- python - “IndentationError:需要一个缩进块(JSON_Project.py,第 22 行)”。谁能帮我删除这个错误并在 Python 中运行我的代码?
- c# - 无法使用 ResourceManager.GetResourceSet 加载特定于区域性的 RESX
- excel - 当检测到不同的组时,在 excel 中重新启动条件格式
- mysql - MySQL Workbench:迁移向导不可用
- push-notification - “WL.Client.Push”的值未定义
- symfony - Api 平台:实体级联上的订单