在组件中使用React微动画:将"display none"转换为动画效果

3

当我点击按钮时,会出现这个组件。我想知道是否有一种简单的缓动效果来展开或弹出动画。让它在转换过程中看起来更加顺畅,而不是突然出现?

const CardExample = () => {
  const [show, setShow] = useState(false);

  const handleClick = () => {
    setShow(!show);
  };

  return (
    <div>
      <Button onClick={handleClick} type="primary">
        Show Card
      </Button>
      <Card style={{ display: show && "none" }}>This is my card</Card>
    </div>
  );
};

Edit lucid-star-fs6zi

2个回答

5
你可以尝试使用透明度代替显示,如下所示,并使用过渡添加动画。
const CardExample = () => {
  const [show, setShow] = useState(false);

  const handleClick = () => {
    setShow(!show);
  };

  const cardStyle = {
    opacity: show ? 0 : 1,
    transition: "all 1s ease-in"
  };

  return (
    <div>
      <Button onClick={handleClick} type="primary">
        Show Card
      </Button>
      <Card style={cardStyle}>This is my card</Card>
    </div>
  );
};

Edit confident-morse-phg31


我已经更新了我的沙盒。我试图逐步推进并扩展。你知道怎样使它更加流畅吗?https://codesandbox.io/s/lucid-star-fs6zi - Freddy.
这是您要找的吗?https://codesandbox.io/s/rough-flower-xj8k9 - Sumit Surana

1
之前的答案似乎可以完成工作,但我想提供另一种使用CSS而不是内联样式的方法。您可以有条件地应用一个className,然后在CSS文件中处理过渡效果。沙盒网址在本帖子底部。
import './CardExample.css';

const CardExample = () => {
  const [show, setShow] = useState(false);

  const handleClick = () => {
    setShow(!show);
  };

  return (
    <div className='card-example'>
      <button onClick={handleClick} type="primary">
        Show Card
      </button>
      <Card className={show ? 'showing' : 'not-showing'}>
          This is my card
      </Card>
    </div> 
  );
};

然后在CSS文件中,您可以使用以下代码,在1秒的动画间隔内有条件地应用可见性属性。

.not-showing {
  visibility: hidden;
  opacity: 0;
  transition: visibility 1s, opacity 0.5s linear;
}
.showing {
  visibility: visible;
  transition: visibility 1s, opacity 0.5s linear;
  opacity: 1;

}

我创建了一个沙盒来演示这个:

https://codesandbox.io/s/react-hooks-playground-boih3?fontsize=14&hidenavigation=1&theme=dark


取第一个答案和你的。 你知道如何使“ease in”和“expand”更加平滑吗? https://codesandbox.io/s/lucid-star-fs6zi - Freddy.
@Freddy。是的,我的代码示例有1秒钟的过渡时间,这使得它更加平滑。 - SlimPDX

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接