"animated"在react-spring中做了什么?

What does "animated" do in react-spring?

我目前正在掌握 react-spring animation library

在文档中的一些 CodeSandbox 演示(例如 https://codesandbox.io/embed/j150ykxrv)中,导入了名为 "animated":

的内容
import { Transition, animated } from 'react-spring'

然后像这样使用:

  {this.state.items.map(item => styles => <animated.li style={{ ...defaultStyles, ...styles }}>{item}</animated.li>)}

在其他示例中未使用:

import { Spring } from 'react-spring'

<Spring
  from={{ opacity: 0 }}
  to={{ opacity: 1 }}>
  {props => <div style={props}>✌️</div>}
</Spring>

我在文档中找不到任何关于它的用途或使用原因的提及,因为您似乎可以通过将动画样式道具传递到组件中来制作动画。

文档部分中的使用是遗留版本吗?

看起来是用来做native渲染的,看看Transition组件,它有一个native prop

进一步查看文档,我可以看到它用于 "native" rendering

这允许 react-spring 绕过 React 进行帧更新。这种方法的好处是提高了性能。


推荐使用这种方式

"Try doing this in all situations where you can"


请注意以下条件:

  1. native only animates styles, attributes and children (as textContent)
  2. The values you receive are opaque objects, not regular values
  3. Receiving elements must be animated.[elementName], for instance div becomes animated.div
  4. If you use styled-components or custom componemts do: animated(component)
  5. If you need to interpolate styles use interpolate

总结的好处:

  1. Your application will be faster, the difference really can be night and day
  2. You get quite powerful interpolation and keyframing tools (see below)
  3. You get to animate scrollTop and scrollLeft out of the box (which React can't normally handle)

Native 是可选的,如果你设置它(然后你需要组件从 animated.xxx 扩展)它不会像通常的反应动画库那样渲染出动画,换句话说他们调用在每一帧上强制更新或设置状态,这是昂贵的。对于本机,它将渲染组件一次,然后使用直接设置样式的 requestAnimationFrame 循环在后台进行动画处理。您传递给目标 div(或其他)的值不是数值,而是接收更新事件的 类,这就是您需要扩展的原因。

通过 React 进行渲染并没有过时,但是,这是唯一可以为 React 组件道具设置动画的方法。如果你有一个外部控件,或者一个 D3 图,你可以简单地把道具吹进去,而 spring 渲染它们。