单击按钮时,Material UI 如何实现过渡效果的淡出和淡入?

17
在 Material UI Transitions doc 中,有一些例子展示了一个按钮触发过渡效果。我有一个情况是当一个按钮触发状态改变时,我想让旧数据过渡出去,然后新数据过渡进来。我唯一找到的方法是使用setTimeout。是否有更好的方法? 在 CodeSandbox 中
import React from "react";
import Slide from "@material-ui/core/Slide";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";

const words = ["one", "two", "three"];
const transitionDuration = 500;

class TransitionCycle extends React.Component {
  state = {
    activeIndex: 0,
    elementIn: true
  };

  onClick = () => {
    this.setState({
      elementIn: false
    });
    setTimeout(() => {
      this.setState({
        elementIn: true,
        activeIndex: (this.state.activeIndex + 1) % words.length
      });
    }, transitionDuration);
  };

  render() {
    const { activeIndex, elementIn } = this.state;

    return (
      <div>
        <Button onClick={this.onClick}>Cycle</Button>
        <Slide
          in={this.state.elementIn}
          timeout={transitionDuration}
          direction="right"
        >
          <Typography variant="h1">{words[this.state.activeIndex]}</Typography>
        </Slide>
      </div>
    );
  }
}

export default TransitionCycle;

这是在Material UI中实现连续转换的最佳方法吗?使用setTimeout感觉有些奇怪。

2个回答

1

可以直接使用CSS过渡,并使用事件侦听器而不是setTimeout来检测过渡发生的时间,Mozilla在此提供了文档:https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions#Detecting_the_start_and_completion_of_a_transition

class MyComponent extends React.Component {
  updateTransition = () => {
    this.setState({
      elementIn: true,
      activeIndex: (this.state.activeIndex + 1) % words.length
    });
  }

  componentDidMount() {
    elementRef.addEventListener("transitionend", updateTransition, true);
  }
}

不要忘记在组件挂载时添加事件监听器,并在卸载组件时将其删除。

0

我认为有条件地渲染所有3个Slides可以解决你的问题,在这里

我还检查了Transition源代码,它也在最后使用了setTimeout,所以我认为使用它并不那么“奇怪”,但如果组件已经为我们封装了低级API(我指的是setTimeout),那么我们肯定不想使用它。


编辑:

根据OP的评论,我发现我误读了他的示例,并没有注意到退出转换,所以我修改了我的代码以满足要求。现在先前的Slide完全退出,然后下一个进入。所有这些都是由组件的设计属性完成的。(尽管底层的Transition源代码只是包装了Rudolf Olah的方法,但我只尝试使用设计好的属性)

然而,仅使用Transition的属性,我认为不可能实现OP使用setTimeout进行“延迟”输入的操作,因此如果OP仍然希望在“Two”进入之前有一小段延迟,您可能仍然需要使用setTimeout


这似乎无法保持输出过渡。 - Scotty H
@ScottH 您是正确的,我的错误,我修改了代码,请检查是否符合您的需求。 - Marson Mao

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