gpt4 book ai didi

javascript - Material UI 在单击单个按钮时进出过渡

转载 作者:数据小太阳 更新时间:2023-10-29 04:21:47 26 4
gpt4 key购买 nike

在 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 感觉很奇怪。

最佳答案

可以直接使用 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);
}
}

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

关于javascript - Material UI 在单击单个按钮时进出过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53807894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com