【问题标题】:How to use styled components in React in order to get keyframe animations如何在 React 中使用样式化组件来获取关键帧动画
【发布时间】:2020-01-19 22:41:09
【问题描述】:

我是 React 新手,专门尝试使用样式化组件和关键帧。

我正在尝试让主页标题 h1 滑入。

我遵循了一些文档,但我觉得有些东西丢失了或者我有问题。

代码如下:

//Home.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;

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

【问题讨论】:

    标签: css reactjs css-animations styled-components keyframe


    【解决方案1】:

    有几处是错误的:

    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 信息添加到标题中。此外,我认为您不想在 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 的动画,您需要从 HomeDiv css 声明中删除 justify-content:center;。否则,您会看到从 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>
    );
    
    

    这里是live example

    【讨论】:

      猜你喜欢
      • 2019-12-25
      • 2021-05-13
      • 1970-01-01
      • 2021-11-21
      • 2017-03-14
      • 2019-11-08
      • 2019-01-14
      • 1970-01-01
      • 2020-06-11
      相关资源
      最近更新 更多