如何使用 React 风格的组件制作从上到下的动画

How to make top to bottom animation with react styled components

我正在尝试在 Gatsby 的网站上重新创建滑块,但使用的是样式化的组件库,而不是他们使用的情感库。问题是动画没有做任何事情,我传递给组件的字符串列表被连接在一起。

Gatsbyjs.org

Code for their slider component

我的slider.js:

import React from "react"
import styled, { keyframes } from "styled-components"


const topToBottom = keyframes`
  0%: {
    opacity: 0;
  }
  6%: {
    opacity: 0;
    transform: translateY(-30px);
  }
  10%: {
    opacity: 1;
    transform: translateY(0px);
  }
  25%: {
    opacity: 1;
    transform: translateY(0px);
  }
  29%: {
    opacity: 0;
    transform: translateY(30px);
  }
  80%: {
    opacity: 0;
  }
  100%: {
    opacity: 0;
  }
`;

const SliderDiv = styled.div`
  display: inline;
  & span: {
    animation: ${topToBottom} 10s linear infinite 0s;
    opacity: 0;
    position: absolute;

    :nth-child(2) {
      animation-delay: 2.5s;
    }

    :nth-child(3) {
      animation-delay: 5s;
    }

    :nth-child(4) {
      animation-delay: 7.5s;
    }
  }
`;

const Slider = ({ items, color }) => (
  <SliderDiv>
    {items.map(item => (
      <span key={item} css={{ color }}>
        {item}
      </span>
    ))}
  </SliderDiv>
)

export default Slider

结果:

如果您从样式化组件内的 css 代码中删除 :,您的代码将按预期工作:

span {
// not
span : {

0% {
// not
0% : {

我已经在 Codesandbox

中测试了代码

import React from "react";
import styled, { keyframes } from "styled-components";

const topToBottom = keyframes`
  0% {
    opacity: 0;
  }
  6% {
    opacity: 0;
    transform: translateY(-30px);
  }
  10% {
    opacity: 1;
    transform: translateY(0px);
  }
  25% {
    opacity: 1;
    transform: translateY(0px);
  }
  29% {
    opacity: 0;
    transform: translateY(30px);
  }
  80% {
    opacity: 0;
  }
  100% {
    opacity: 0;
  }
`;

const SliderDiv = styled.div`
  display: inline;
  & span {
    animation: ${topToBottom} 10s linear infinite 0s;
    opacity: 0;
    position: absolute;

    :nth-child(2) {
      animation-delay: 2.5s;
    }

    :nth-child(3) {
      animation-delay: 5s;
    }

    :nth-child(4) {
      animation-delay: 7.5s;
    }
  }
`;

const Slider = ({ items, color }) => (
  <SliderDiv>
    {items.map(item => (
      <span key={item} css={{ color }}>
        {item}
      </span>
    ))}
  </SliderDiv>
);

export default Slider;

我知道我找过几次这个错误:)

为了更清楚,在 styled-components 中你写 css,而不是 css-in-js

希望对您有所帮助!