css - 如何在 React 中使用样式化组件来获取关键帧动画
问题描述
我是 React 的新手,特别是尝试使用样式化的组件和关键帧。
我试图让主页标题 h1 滑入。
我遵循了一些文档,但我觉得缺少某些东西或者我有问题。
这是代码:
//首页.js
import React from "react";
import styled, { keyframes } from 'styled-components';
const Heading = keyframes`
0% { top: -3.125em; }
100% { top: 3em;
`;
const home = styled.div`
min-height: 95vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: 1.5em;
color: white;
`;
const homeHeader = styled.div`
h1 {
font-weight: lighter;
animation: Heading;
animation-duration: 3s;
animation-fill-mode: forwards;
}
// Animation
animation: ${Heading}
animation-duration: 3s;
animation-fill-mode: forwards;
`;
export const Home = () => (
<div className="home">
<header className="homeHeader">
<h1>Welcome to Freight Mule</h1>
</header>
</div>
);
export default Home;
任何有助于理解如何让关键帧和动画工作的帮助都会非常有帮助。
解决方案
有几件事是错误的:
- 您实际上并没有使用由
styled-component
. 当你这样做
const Div = styled.div`
background-color: blue;
`
你刚刚创建了一个新的 React 组件,你可以在任何渲染方法中使用它。所以你的Home
组件变成了我大写的(react 期望自定义组件是大写的)并重命名了一些组件以避免重复变量):
const Home = () => (
<HomeDiv>
<HomeHeader>
<h1>Welcome to Freight Mule</h1>
</HomeHeader>
</HomeDiv>
);
- 要为属性设置动画
top
,您需要将初始top
信息添加到 Header。此外,我认为您不想在 上应用动画,h1
所以我将其删除
const HomeHeader = styled.div`
h1 {
font-weight: lighter;
}
position: relative;
top: 0;
animation: ${Heading};
animation-duration: 3s;
animation-fill-mode: forwards;
`;
- 可选:要实际看到从 -3.125em 到 3em 的动画,您需要
justify-content:center;
从HomeDiv
css 声明中删除 。否则,您将看到从 div 中心到 3em 的动画。
这里是完整的代码:
const Heading = keyframes`
0% { top: -3.125em; }
100% { top: 3em;}
`;
const HomeDiv = styled.div`
min-height: 95vh;
display: flex;
flex-direction: column;
align-items: center;
font-size: 1.5em;
`;
const HomeHeader = styled.div`
h1 {
font-weight: lighter;
}
position: relative;
top: 0;
animation: ${Heading};
animation-duration: 3s;
animation-fill-mode: forwards;
`;
const Home = () => (
<HomeDiv>
<HomeHeader>
<h1>Welcome to Freight Mule</h1>
</HomeHeader>
</HomeDiv>
);
这是一个活生生的例子
推荐阅读
- javascript - 有 EventListener 时如何不触发视频结束事件
- c++ - GCC 8 无法编译 make_shared
() - python - 从 CuDNNLSTM 到密集层的麻烦
- chef-infra - OpsWorks for Chef Automate 和 Chef 验证器密钥
- javascript - 对象不支持属性或方法“forEach”IE 11
- javascript - 使用 PHP 或 JavaScript 绘制矢量头像
- php - 如何使用 php curl 和简单的 html dom 解析器获取 span 标签值?未显示确切值
- javascript - div 的调整大小被忽略
- javascript - 菜单设计 - 添加更多菜单选项
- python - 如何对列中的特定值进行分组?