首页 > 解决方案 > 如何在 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;

任何有助于理解如何让关键帧和动画工作的帮助都会非常有帮助。

标签: cssreactjscss-animationsstyled-componentskeyframe

解决方案


有几件事是错误的:

  1. 您实际上并没有使用由styled-component. 当你这样做
const Div = styled.div`
  background-color: blue;
`

你刚刚创建了一个新的 React 组件,你可以在任何渲染方法中使用它。所以你的Home组件变成了我大写的(react 期望自定义组件是大写的)并重命名了一些组件以避免重复变量):

const Home = () => (
  <HomeDiv>
    <HomeHeader>
      <h1>Welcome to Freight Mule</h1>
    </HomeHeader>
  </HomeDiv>
);
  1. 要为属性设置动画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;
`;
  1. 可选:要实际看到从 -3.125em 到 3em 的动画,您需要justify-content:center;HomeDivcss 声明中删除 。否则,您将看到从 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>
);

这是一个活生生的例子


推荐阅读