我目前正在自学React,并且遇到了我不了解的行为。我的第一个简单项目是创建一个动画的侧边栏折叠按钮。如果我正确了解引擎盖下发生了什么,那么在单击该组件时,React会重新创建该组件。如果是这样,为什么完全显示过渡?不会在过渡“结束”时以初始状态重新创建组件吗?
JSX
class SidebarButton extends React.Component {
constructor(props) {
super(props);
this.state = {open: props.open || false};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState((prevState) => ({
open: !prevState.open
}));
}
render() {
const classes = ['sidebar-button'];
if (this.state.open) classes.push('open');
const bars = [];
for (let i = 0; i < 3; ++i)
bars.push(<SidebarButtonLine key={`${i}`} index={i} />);
return (
<div className={classes.join(' ')} onClick={this.handleClick}>
{bars}
</div>
);
}
}
class SidebarButtonLine extends React.Component {
constructor(props) {
super(props);
}
render() {
const classes = ['sidebar-button-line'];
classes.push(`sidebar-button-line-${this.props.index}`);
return (
<div className={classes.join(' ')} />
);
}
}
CSS
.sidebar-button {
display: inline-block;
border: 1px solid #aaa;
border-radius: 2px;
padding: 5px;
}
.sidebar-button>.sidebar-button-line {
background-color: #000;
margin: 0 auto;
width: 26px;
height: 2px;
transition: transform 0.2s ease;
}
.sidebar-button>.sidebar-button-line:not(:last-child) {
margin-bottom: 10px;
}
.sidebar-button.open>.sidebar-button-line.sidebar-button-line-0 {
transform: translateY(12px) rotate(-135deg);
}
.sidebar-button.open>.sidebar-button-line.sidebar-button-line-1 {
transform: scaleX(0);
}
.sidebar-button.open>.sidebar-button-line.sidebar-button-line-2 {
transform: translateY(-12px) rotate(135deg);
}