如何使用Styled-Components触发动画?

问题描述 投票:0回答:1

目前我使用以下方法来触发动画。我将状态设置为 true,一段时间后,使用 setTimeout 将其设置为 false。有没有办法在不使用 setTimeout 的情况下做到这一点?

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

const growAnimation = keyframes`
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
`;

const StyledButton = styled.button`
  padding: 10px 20px;
  font-size: 16px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  animation: ${props => (props.animate ? `${growAnimation} 1s ease-in-out` : 'none')};
`;

const AnimatedButton = () => {
  const [animate, setAnimate] = useState(false);

  const handleClick = () => {
    setAnimate(true);
    setTimeout(() => {
      setAnimate(false);
    }, 1000);
  };

  return (
    <StyledButton animate={animate} onClick={handleClick}>
      Click me!
    </StyledButton>
  );
};

export default AnimatedButton;
javascript css reactjs styled-components
1个回答
0
投票

有没有什么方法可以在不使用 setTimeout 的情况下做到这一点?

您可以将 animation

fill-mode
设置为
forwards
,这样动画只会触发一次,并保持新状态。

`${growAnimation} 1s ease-in-out forwards`
                             // ^^^^^^^^^
© www.soinside.com 2019 - 2024. All rights reserved.