【发布时间】:2020-05-12 23:40:59
【问题描述】:
我希望我的应用程序中的页面内容能够顺利过渡。我一直在尝试使用 react-transition-group 来做到这一点,但我一直在努力实现正确的实现。以下链接提供了丰富的信息: https://coursework.vschool.io/react-transitions-with-react-transition-group/
它展示了如何进行模块化和使用 TransitionGroup(不幸的是,虽然不能同时使用两者)。
我创建了一个演示项目(基于上面的链接)来解决这个问题。我在数组“contactComponents”中有两个项目。我现在要做的就是使用显示/隐藏按钮使这些信息出现和消失。
代码主体如下:
const contactDetails = ['Gryffindor Tower, Hogwarts','Gryffindor Tower, Hogwarts'];
const contacts = ['Harry', 'Ron'];
export default class App extends React.Component {
constructor(props){
super(props);
this.state = {
count: 0,
showMyContact: false
};
this.showContact = this.showContact.bind(this);
}
showContact() {
this.setState({showMyContact: !this.state.showMyContact})
}
render() {
const styles = {
container: { display: 'flex', justifyContent: 'center', width: '100vw', height: 100, flexDirection: 'column', padding: 100 },
btn: { width: '100%', display: 'flex', justifyContent: 'center'},
h1: { border: '2px solid blue', padding: 5, display: 'flex'}
};
let contactComponents = [contacts[this.state.count], contactDetails[this.state.count]];
console.log(this.state.showMyContact)
return (
<div>
<div style={ styles.container }>
<TransitionGroup component={null}>
{ contactComponents.map((item, key) =>
<CSSTransition
in={this.state.showMyContact}
key={key}
timeout={800}
classNames={"fade"}>
<h1 style={styles.h1}>
{
item
}
</h1>
</CSSTransition>
)}
</TransitionGroup>
<div style={ styles.btn }>
<button onClick={ this.showContact }>show/hide</button>
</div>
</div>
</div>
)
}
}
scss 文件:
.fade-appear,
.fade-enter {
opacity: 0;
z-index: 1;
}
.fade-appear-active,
.fade-enter.fade-enter-active {
opacity: 1;
transition: opacity 600ms linear 200ms;
}
.fade-exit {
opacity: 1;
}
.fade-exit.fade-exit-active {
opacity: 0;
transition: opacity 200ms linear;
}
目前,即使在第一次调用渲染函数时 showMyContact 为 false,内容也会显示。使用显示/隐藏按钮更改 showMyContact 的状态无效。内容不会按预期淡入淡出。
这篇文章: page transitions without React-Router
建议使用纯 css 执行转换而不是 react-transition-group 可能会更好。我是不是找错树了?
【问题讨论】:
标签: reactjs