我很难让动画在每次点击时触发-它只在页面挂载时触发一次。
我找到的解决方案是向我想要动画的文本添加一个Math.random键,但是一旦我添加了新的处理函数,它就不起作用了,因为如果有任何函数被触发,它就会触发动画。
另外,我读到在React中操作DOM不是一种好的做法。
我知道我可以使用合成事件onAnimationEnd,但我想在每次点击时再次触发动画,而不是等待它结束。
我设法让它以一种有点老套的方式工作,在onClick函数的setState中添加一个动画,然后在onAnimationStart中添加一个不同的动画。
有什么更好的方法来解决这个问题,最好是遵循最佳实践的方法?
最小可行示例:
class App extends React.Component {
state = {
quotes: [{quote: "a", author: 1},
{quote: "b", author: 2},
{quote: "c", author: 3}],
quote: {quote: "a", author: 1}
}
handleClick = () => {
this.setState({
quote: this.state.quotes[Math.floor(Math.random()*3)]
});
}
render() {
// assign random quote
const quote = this.state.quotes.length ? (this.state.quote.quote) : ("Wait o");
// assign author
const author = this.state.quotes.length ? (this.state.quote.author) : ("");
return(
<div className="App">
<p className="animated jackInTheBox">
{quote}
</p>
<p className="animated jackInTheBox">
{author}
</p>
<button id="new-quote" onClick={this.handleClick}>
New Quote
</button>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);<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>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">
</head>
<div id="root"></div>
发布于 2020-04-10 18:55:33
class App extends React.Component {
state = {
classes:"animated jackInTheBox",
quotes: [{quote: "a", author: 1},
{quote: "b", author: 2},
{quote: "c", author: 3}],
quote: {quote: "a", author: 1}
}
handleClick = () => {
this.setState({
quote: this.state.quotes[Math.floor(Math.random()*3)],
classes:"hidden"
}, () => {
setTimeout(() => this.setState({classes:"animated jackInTheBox"}),100)
});
}
render() {
// assign random quote
const quote = this.state.quotes.length ? (this.state.quote.quote) : ("Wait o");
// assign author
const author = this.state.quotes.length ? (this.state.quote.author) : ("");
return(
<div className="App">
<p className={this.state.classes}>
{quote}
</p>
<p className={this.state.classes}>
{author}
</p>
<button id="new-quote" onClick={this.handleClick}>
New Quote
</button>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);<style>.hidden{opacity:0}</style>
<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>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">
</head>
<div id="root"></div>
https://stackoverflow.com/questions/61138021
复制相似问题