【问题标题】:Material UI transition out and in on single button click材料 UI 转换出和单击一个按钮
【发布时间】:2018-12-17 01:11:26
【问题描述】:

在 Material UI Transitions doc 中,有一些按钮触发转换的示例。我有一个按钮触发状态更改的情况,我希望以前的数据转出,然后转入新数据。我发现这样做的唯一方法是使用setTimeout。有没有更好的办法?

In 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感觉怪怪的。

【问题讨论】:

    标签: javascript material-ui transition


    【解决方案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);
      }
    }
    

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

    【讨论】:

      【解决方案2】:

      我认为有条件地渲染所有 3 个Slides 可以解决您的问题,here

      我还检查了Transitionsource codes,它最后也使用了setTimeout,所以我认为使用它并没有那么“奇怪”,但是如果组件已经包装了低级api(我的意思是 setTimeout) 对我们来说,那么我们肯定不想使用它。


      编辑:

      作为 OP 的评论,我发现我误读了他的示例并且没有注意到 out 转换,所以我 modified my codes 满足要求。现在前一个Slide 完全退出,然后下一个进入。一切都由组件设计的道具完成。 (不过,底层Transition 源代码只是包装了 Rudolf Olah 的方法,但我只是尝试只使用设计的道具)

      但是,仅使用Transition的道具,我认为不可能实现“延迟”进入OP使用setTimeout所做的,所以如果OP仍然希望在“Two”进入之前有那么小的延迟,你可能仍然需要使用setTimeout

      【讨论】:

      • 这似乎并没有维持 out 过渡。
      • @ScottH 你是对的,我的错,我修改了代码,请检查它是否是你需要的。
      猜你喜欢
      • 1970-01-01
      • 2020-11-05
      • 1970-01-01
      • 2019-01-30
      • 2021-05-20
      • 2021-07-20
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多