我正在使用react-animated-css库在React JS中将动画应用于状态更改。
代码如下:
import ReactDOM from "react-dom";
import React, { Component } from "react";
import { Animated } from "react-animated-css";
const animationIn = "fadeInLeft";
const animationOut = "fadeOutLeft";
const animationDuration = 400; // in ms
const arr = [
{
id: 1,
name: "Test"
},
{
id: 2,
name: "Test1"
},
{
id: 3,
name: "Test3"
},
{
id: 4,
name: "Test4"
},
{
id: 5,
name: "Test5"
}
];
class Selection extends Component {
constructor(props) {
super(props);
this.state = {
selection: []
};
this.addSelection = this.addSelection.bind(this);
this.removeItem = this.removeItem.bind(this);
}
addSelection(item) {
const exists = this.state.selection.find(i => i.id === item.id);
if (exists === undefined) {
this.setState({ selection: [...this.state.selection, item] });
}
}
removeItem(item) {
this.setState({
selection: this.state.selection.filter(i => i.id !== item.id)
});
}
render() {
return (
<div
style={{
display: "flex",
flexDirection: "row",
justifyContent: "space-between"
}}
>
<div>
<h2>Choose from the list</h2>
{arr.map(item => {
return (
<div
key={item.id}
style={{ marginBottom: 5, cursor: "pointer" }}
onClick={() => this.addSelection(item)}
>
{item.name}
</div>
);
})}
</div>
<div>
<h1>Selection</h1>
{this.state.selection.length < 1 ? (
<div>Nothing selected</div>
) : (
this.state.selection.map(l => {
return (
<Animated
key={l.name}
animationIn={animationIn}
animationOut={animationOut}
animationInDuration={animationDuration}
animationOutDuration={animationDuration}
isVisible={true}
>
<div key={l.id} style={{ marginBottom: 5 }}>
{l.name}
<button
onClick={() => this.removeItem(l)}
style={{ marginLeft: 5, cursor: "pointer" }}
>
Remove
</button>
</div>
</Animated>
);
})
)}
</div>
</div>
);
}
}
ReactDOM.render(<Selection />, document.getElementById("root"));
当我单击左侧的某个项目并将其添加到状态时,它可以正常工作,但是当我删除它时,它不起作用。
Here is the example on sandbox.
有没有办法在从状态中删除项目时也应用动画?
答案 0 :(得分:2)
答案 1 :(得分:0)
乍一看,您似乎删除了带有该项目的动画,这就是为什么它不播放的原因。 如果将动画包装在整个选择列表中(从h1开始),是否可行?
答案 2 :(得分:0)
您必须切换isVisible
属性才能看到动画。如果卸载了组件,则无法对其进行动画处理。