gpt4 book ai didi

css - 如何在 React 中使用样式化组件来获取关键帧动画

转载 作者:行者123 更新时间:2023-11-27 23:20:57 25 4
gpt4 key购买 nike

我是 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;

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

最佳答案

有几件事是错误的:

  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>
);
  • 要为 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 的动画,您需要从 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

    关于css - 如何在 React 中使用样式化组件来获取关键帧动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58001816/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com