我正在使用react-spring为我的组件设置动画。但是我想仅在安装时运行动画,然后在卸载时离开动画。但是,每次重新渲染组件时,我的动画都会运行。每次prop
的更改都会使动画再次运行,这不是我期望的那样。谢谢您的帮助。
/* eslint-disable react/jsx-props-no-spreading */
import * as React from 'react'
import { Transition, animated, config } from 'react-spring/renderprops'
class Animation extends React.Component {
constructor(props) {
super(props)
this.shouldAnimate = props.shouldAnimate
}
render() {
const Container = animated(this.props.container)
return (
<Transition
items={this.props.items}
native
initial={this.props.initial}
from={this.props.from}
leave={this.props.leave}
enter={this.props.enter}
config={config.gentle}
>
{(visible) =>
visible &&
((styles) => (
<Container
style={styles}
{...this.props.containerProps}
>
{this.props.children}
</Container>
))
}
</Transition>
)
}
}
export default Animation
答案 0 :(得分:1)
仔细查看我的组件并记录了生命周期方法调用后,我已经找到了解决这个问题的方法。我发现每次道具更改都会导致创建一个新的容器组件,从而导致该组件卸载和重新安装,进而导致动画播放。在意识到这一点之后,解决方案很容易。我只是将文件更改为此,现在工作正常。
/* eslint-disable react/jsx-props-no-spreading */
import * as React from 'react'
import { Transition, animated } from 'react-spring/renderprops'
class Animation extends React.PureComponent {
constructor(props) {
super(props)
this.shouldAnimate = props.shouldAnimate
this.container = animated(this.props.container)
}
render() {
const Container = this.container
return (
<Transition
items={this.props.items}
native
initial={this.props.initial}
from={this.props.from}
update={this.props.update}
leave={this.props.leave}
enter={this.props.enter}
>
{(visible) =>
visible &&
((styles) => (
<Container
style={styles}
{...this.props.containerProps}
>
{this.props.children}
</Container>
))
}
</Transition>
)
}
}
export default Animation