我有一个组件,该组件以空的项目/框列表开始,并且随着列表的增加,先前的项目在que中被下推。您可以查看以下代码段作为示例。如何添加CSS过渡,以便您可以直观地看到项目从其先前位置向下移动到下一位置?谢谢!
class App extends React.Component {
constructor() {
super();
this.state = {
count: 0
};
this.handleClick = this.handleClick.bind(this);
this.getItems = this.getItems.bind(this);
}
handleClick() {
this.setState({
count: this.state.count + 1,
});
}
getItems() {
let items = [];
for (let j = 0; j < this.state.count; j++) {
items.push(<div className="item">This is a box {j}</div>)
}
return items.reverse();
};
render() {
return (
<div className="container">
<button onClick={this.handleClick}>Add box</button>
{this.getItems()}
</div>
);
}
}
ReactDOM.render(<App />, app);
.container {
border: 1px solid green !important;
}
.item {
height: 40px;
width: 100px;
background: yellow;
border: 2px solid red;
margin: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
答案 0 :(得分:1)
您可以在最大高度上使用动画; 但是您必须知道.item的大小,max-height:100%在动画上不起作用。
class App extends React.Component {
constructor() {
super();
this.state = {
count: 0
};
this.handleClick = this.handleClick.bind(this);
this.getItems = this.getItems.bind(this);
}
handleClick() {
this.setState({
count: this.state.count + 1,
});
}
getItems() {
let items = [];
for (let j = 0; j < this.state.count; j++) {
items.push(<div className="item">This is a box {j}</div>)
}
return items.reverse();
};
render() {
return (
<div className="container">
<button onClick={this.handleClick}>Add box</button>
{this.getItems()}
</div>
);
}
}
ReactDOM.render(<App />, app);
.container {
border: 1px solid green !important;
}
.item {
height: 40px;
width: 100px;
background: yellow;
border: 2px solid red;
margin: 20px;
animation-name: example;
animation-duration: 2s;
animation-iteration-count: 1;
overflow: hidden;
}
@keyframes example {
from { max-height: 0px;}
to { max-height: 40px;}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>