Animated
Animated
库旨在使动画流畅、强大且易于构建和维护。Animated
重点关注输入和输出之间的声明关系、之间的可配置转换以及控制基于时间的动画执行的 start
/stop
方法。
¥The Animated
library is designed to make animations fluid, powerful, and painless to build and maintain. Animated
focuses on declarative relationships between inputs and outputs, configurable transforms in between, and start
/stop
methods to control time-based animation execution.
创建动画的核心工作流程是创建 Animated.Value
,将其连接到动画组件的一个或多个样式属性,然后使用 Animated.timing()
通过动画驱动更新。
¥The core workflow for creating an animation is to create an Animated.Value
, hook it up to one or more style attributes of an animated component, and then drive updates via animations using Animated.timing()
.
不要直接修改动画值。你可以使用
useRef
钩 返回可变的引用对象。该 ref 对象的current
属性被初始化为给定参数,并在整个组件生命周期中持续存在。¥Don't modify the animated value directly. You can use the
useRef
Hook to return a mutable ref object. This ref object'scurrent
property is initialized as the given argument and persists throughout the component lifecycle.
示例
¥Example
以下示例包含一个 View
,它将根据动画值 fadeAnim
淡入和淡出
¥The following example contains a View
which will fade in and fade out based on the animated value fadeAnim
请参阅 动画 指南以查看 Animated
的其他实际示例。
¥Refer to the Animations guide to see additional examples of Animated
in action.
概述
¥Overview
Animated
可以使用两种值类型:
¥There are two value types you can use with Animated
:
-
Animated.Value()
用于单个值¥
Animated.Value()
for single values -
Animated.ValueXY()
用于向量¥
Animated.ValueXY()
for vectors
Animated.Value
可以绑定到样式属性或其他属性,也可以进行插值。单个 Animated.Value
可以驱动任意数量的属性。
¥Animated.Value
can bind to style properties or other props, and can be interpolated as well. A single Animated.Value
can drive any number of properties.
配置动画
¥Configuring animations
Animated
提供了三种动画类型。每种动画类型都提供特定的动画曲线,用于控制值从初始值到最终值的动画效果:
¥Animated
provides three types of animation types. Each animation type provides a particular animation curve that controls how your values animate from their initial value to the final value:
-
Animated.decay()
以初速度开始,逐渐减慢直至停止。¥
Animated.decay()
starts with an initial velocity and gradually slows to a stop. -
Animated.spring()
提供了基本的弹簧物理模型。¥
Animated.spring()
provides a basic spring physics model. -
Animated.timing()
使用 缓动函数 随时间对值进行动画处理。¥
Animated.timing()
animates a value over time using easing functions.
在大多数情况下,你将使用 timing()
。默认情况下,它使用对称的 escapeInOut 曲线,该曲线将对象逐渐加速到全速,并通过逐渐减速到停止来结束。
¥In most cases, you will be using timing()
. By default, it uses a symmetric easeInOut curve that conveys the gradual acceleration of an object to full speed and concludes by gradually decelerating to a stop.
使用动画
¥Working with animations
通过在动画上调用 start()
来启动动画。start()
接受一个完成回调,该回调将在动画完成时调用。如果动画正常运行结束,将使用 {finished: true}
调用完成回调。如果动画完成是因为在完成之前调用了 stop()
(例如,因为它被手势或另一个动画中断),那么它将收到 {finished: false}
。
¥Animations are started by calling start()
on your animation. start()
takes a completion callback that will be called when the animation is done. If the animation finished running normally, the completion callback will be invoked with {finished: true}
. If the animation is done because stop()
was called on it before it could finish (e.g. because it was interrupted by a gesture or another animation), then it will receive {finished: false}
.
Animated.timing({}).start(({finished}) => {
/* completion callback */
});
使用原生驱动程序
¥Using the native driver
通过使用原生驱动程序,我们在启动动画之前将有关动画的所有内容发送到原生,从而允许原生代码在 UI 线程上执行动画,而无需在每一帧上都经过桥接器。一旦动画开始,就可以阻塞 JS 线程而不影响动画。
¥By using the native driver, we send everything about the animation to native before starting the animation, allowing native code to perform the animation on the UI thread without having to go through the bridge on every frame. Once the animation has started, the JS thread can be blocked without affecting the animation.
你可以通过在动画配置中指定 useNativeDriver: true
来使用原生驱动程序。请参阅 动画 指南以了解更多信息。
¥You can use the native driver by specifying useNativeDriver: true
in your animation configuration. See the Animations guide to learn more.
可动画化的组件
¥Animatable components
只有可动画化的组件才可以动画化。这些独特的组件具有将动画值绑定到属性的魔力,并进行有针对性的原生更新,以避免每帧上的 React 渲染和协调过程的成本。它们还处理卸载时的清理工作,因此默认情况下它们是安全的。
¥Only animatable components can be animated. These unique components do the magic of binding the animated values to the properties, and do targeted native updates to avoid the cost of the React render and reconciliation process on every frame. They also handle cleanup on unmount so they are safe by default.
-
createAnimatedComponent()
可用于使组件具有动画效果。¥
createAnimatedComponent()
can be used to make a component animatable.
Animated
使用上述封装器导出以下可动画组件:
¥Animated
exports the following animatable components using the above wrapper:
-
Animated.Image
-
Animated.ScrollView
-
Animated.Text
-
Animated.View
-
Animated.FlatList
-
Animated.SectionList
创作动画
¥Composing animations
动画还可以使用组合函数以复杂的方式组合:
¥Animations can also be combined in complex ways using composition functions:
-
Animated.delay()
在给定的延迟后开始动画。¥
Animated.delay()
starts an animation after a given delay. -
Animated.parallel()
同时启动多个动画。¥
Animated.parallel()
starts a number of animations at the same time. -
Animated.sequence()
按顺序开始动画,等待每个动画完成后再开始下一个动画。¥
Animated.sequence()
starts the animations in order, waiting for each to complete before starting the next. -
Animated.stagger()
按顺序并行启动动画,但有连续的延迟。¥
Animated.stagger()
starts animations in order and in parallel, but with successive delays.
通过将一个动画的 toValue
设置为另一个动画的 Animated.Value
,也可以将动画链接在一起。请参阅动画指南中的 跟踪动态值。
¥Animations can also be chained together by setting the toValue
of one animation to be another Animated.Value
. See Tracking dynamic values in the Animations guide.
默认情况下,如果一个动画停止或中断,则该组中的所有其他动画也会停止。
¥By default, if one animation is stopped or interrupted, then all other animations in the group are also stopped.
组合动画值
¥Combining animated values
你可以通过加法、减法、乘法、除法或取模来组合两个动画值以生成新的动画值:
¥You can combine two animated values via addition, subtraction, multiplication, division, or modulo to make a new animated value:
插值法
¥Interpolation
interpolate()
功能允许输入范围映射到不同的输出范围。默认情况下,它会推断超出给定范围的曲线,但你也可以让它限制输出值。它默认使用线性插值,但也支持缓动函数。
¥The interpolate()
function allows input ranges to map to different output ranges. By default, it will extrapolate the curve beyond the ranges given, but you can also have it clamp the output value. It uses linear interpolation by default but also supports easing functions.
在 Animation 指南中阅读有关插值的更多信息。
¥Read more about interpolation in the Animation guide.
处理手势和其他事件
¥Handling gestures and other events
手势(如平移或滚动)和其他事件可以使用 Animated.event()
直接映射到动画值。这是通过结构化映射语法完成的,以便可以从复杂的事件对象中提取值。第一级是一个允许跨多个参数映射的数组,并且该数组包含嵌套对象。
¥Gestures, like panning or scrolling, and other events can map directly to animated values using Animated.event()
. This is done with a structured map syntax so that values can be extracted from complex event objects. The first level is an array to allow mapping across multiple args, and that array contains nested objects.
例如,在使用水平滚动手势时,你需要执行以下操作才能将 event.nativeEvent.contentOffset.x
映射到 scrollX
(Animated.Value
):
¥For example, when working with horizontal scrolling gestures, you would do the following in order to map event.nativeEvent.contentOffset.x
to scrollX
(an Animated.Value
):
onScroll={Animated.event(
// scrollX = e.nativeEvent.contentOffset.x
[{nativeEvent: {
contentOffset: {
x: scrollX
}
}
}]
)}
参考
¥Reference
方法
¥Methods
当给定值是 ValueXY 而不是 Value 时,每个配置选项可以是 {x: ..., y: ...}
形式的向量而不是标量。
¥When the given value is a ValueXY instead of a Value, each config option may be a vector of the form {x: ..., y: ...}
instead of a scalar.
decay()
static decay(value, config): CompositeAnimation;
根据衰减系数将值从初始速度动画化到零。
¥Animates a value from an initial velocity to zero based on a decay coefficient.
Config 是一个可能具有以下选项的对象:
¥Config is an object that may have the following options:
-
velocity
:初始速度。必需的。¥
velocity
: Initial velocity. Required. -
deceleration
:衰减率。默认 0.997。¥
deceleration
: Rate of decay. Default 0.997. -
isInteraction
:该动画是否在InteractionManager
上创建 "交互句柄"。默认为真。¥
isInteraction
: Whether or not this animation creates an "interaction handle" on theInteractionManager
. Default true. -
useNativeDriver
:如果为 true,则使用原生驱动程序。必需的。¥
useNativeDriver
: Uses the native driver when true. Required.
timing()
static timing(value, config): CompositeAnimation;
沿着定时缓动曲线对值进行动画处理。Easing
模块有大量预定义曲线,或者你也可以使用自己的函数。
¥Animates a value along a timed easing curve. The Easing
module has tons of predefined curves, or you can use your own function.
Config 是一个可能具有以下选项的对象:
¥Config is an object that may have the following options:
-
duration
:动画长度(毫秒)。默认 500。¥
duration
: Length of animation (milliseconds). Default 500. -
easing
:定义曲线的缓动函数。默认为Easing.inOut(Easing.ease)
。¥
easing
: Easing function to define curve. Default isEasing.inOut(Easing.ease)
. -
delay
:延迟(毫秒)后开始动画。默认 0。¥
delay
: Start the animation after delay (milliseconds). Default 0. -
isInteraction
:该动画是否在InteractionManager
上创建 "交互句柄"。默认为真。¥
isInteraction
: Whether or not this animation creates an "interaction handle" on theInteractionManager
. Default true. -
useNativeDriver
:如果为 true,则使用原生驱动程序。必需的。¥
useNativeDriver
: Uses the native driver when true. Required.
spring()
static spring(value, config): CompositeAnimation;
根据基于 阻尼谐振 的分析弹簧模型对值进行动画处理。跟踪速度状态以在 toValue
更新时创建流畅的运动,并且可以链接在一起。
¥Animates a value according to an analytical spring model based on damped harmonic oscillation. Tracks velocity state to create fluid motions as the toValue
updates, and can be chained together.
Config 是一个可能具有以下选项的对象。
¥Config is an object that may have the following options.
请注意,你只能定义弹力/速度、张力/摩擦力或刚度/阻尼/质量之一,但不能超过一项:
¥Note that you can only define one of bounciness/speed, tension/friction, or stiffness/damping/mass, but not more than one:
摩擦/张力或弹力/速度选项与 Facebook Pop
、反弹 和 Origami 中的弹簧模型相匹配。
¥The friction/tension or bounciness/speed options match the spring model in Facebook Pop
, Rebound, and Origami.
-
friction
:控制 "bounciness"/过冲。默认 7。¥
friction
: Controls "bounciness"/overshoot. Default 7. -
tension
:控制速度。默认 40。¥
tension
: Controls speed. Default 40. -
speed
:控制动画的速度。默认 12。¥
speed
: Controls speed of the animation. Default 12. -
bounciness
:控制弹力。默认 8。¥
bounciness
: Controls bounciness. Default 8.
将刚度/阻尼/质量指定为参数使 Animated.spring
使用基于 阻尼谐振子 运动方程的分析弹簧模型。这种行为稍微更精确,更忠实于弹簧动力学背后的物理原理,并且非常模仿 iOS 的 CASpringAnimation 中的实现。
¥Specifying stiffness/damping/mass as parameters makes Animated.spring
use an analytical spring model based on the motion equations of a damped harmonic oscillator. This behavior is slightly more precise and faithful to the physics behind spring dynamics, and closely mimics the implementation in iOS's CASpringAnimation.
-
stiffness
:弹簧刚度系数。默认 100。¥
stiffness
: The spring stiffness coefficient. Default 100. -
damping
:定义如何因摩擦力而阻尼弹簧的运动。默认 10。¥
damping
: Defines how the spring’s motion should be damped due to the forces of friction. Default 10. -
mass
:附着在弹簧末端的对象的质量。默认 1。¥
mass
: The mass of the object attached to the end of the spring. Default 1.
其他配置选项如下:
¥Other configuration options are as follows:
-
velocity
:附着在弹簧上的对象的初始速度。默认 0(对象处于静止状态)。¥
velocity
: The initial velocity of the object attached to the spring. Default 0 (object is at rest). -
overshootClamping
:布尔值,指示弹簧是否应该被夹紧而不是弹跳。默认为 false。¥
overshootClamping
: Boolean indicating whether the spring should be clamped and not bounce. Default false. -
restDisplacementThreshold
:静止位移阈值,低于该阈值则应考虑弹簧处于静止状态。默认 0.001。¥
restDisplacementThreshold
: The threshold of displacement from rest below which the spring should be considered at rest. Default 0.001. -
restSpeedThreshold
:弹簧应被视为静止的速度(以每秒像素为单位)。默认 0.001。¥
restSpeedThreshold
: The speed at which the spring should be considered at rest in pixels per second. Default 0.001. -
delay
:延迟(毫秒)后开始动画。默认 0。¥
delay
: Start the animation after delay (milliseconds). Default 0. -
isInteraction
:该动画是否在InteractionManager
上创建 "交互句柄"。默认为真。¥
isInteraction
: Whether or not this animation creates an "interaction handle" on theInteractionManager
. Default true. -
useNativeDriver
:如果为 true,则使用原生驱动程序。必需的。¥
useNativeDriver
: Uses the native driver when true. Required.
add()
static add(a: Animated, b: Animated): AnimatedAddition;
创建由两个动画值相加而成的新动画值。
¥Creates a new Animated value composed from two Animated values added together.
subtract()
static subtract(a: Animated, b: Animated): AnimatedSubtraction;
通过从第一个动画值中减去第二个动画值来创建新的动画值。
¥Creates a new Animated value composed by subtracting the second Animated value from the first Animated value.
divide()
static divide(a: Animated, b: Animated): AnimatedDivision;
通过将第一个动画值除以第二个动画值来创建新的动画值。
¥Creates a new Animated value composed by dividing the first Animated value by the second Animated value.
multiply()
static multiply(a: Animated, b: Animated): AnimatedMultiplication;
创建由两个动画值相乘组成的新动画值。
¥Creates a new Animated value composed from two Animated values multiplied together.
modulo()
static modulo(a: Animated, modulus: number): AnimatedModulo;
创建一个新的动画值,该值是所提供的动画值的(非负)模数
¥Creates a new Animated value that is the (non-negative) modulo of the provided Animated value
diffClamp()
static diffClamp(a: Animated, min: number, max: number): AnimatedDiffClamp;
创建一个限制在 2 个值之间的新动画值。它使用最后一个值之间的差异,因此即使该值远离边界,当该值再次开始接近时它也会开始变化。(value = clamp(value + diff, min, max)
)。
¥Create a new Animated value that is limited between 2 values. It uses the difference between the last value so even if the value is far from the bounds it will start changing when the value starts getting closer again. (value = clamp(value + diff, min, max)
).
这对于滚动事件很有用,例如,向上滚动时显示导航栏,向下滚动时隐藏导航栏。
¥This is useful with scroll events, for example, to show the navbar when scrolling up and to hide it when scrolling down.
delay()
static delay(time: number): CompositeAnimation;
在给定的延迟后开始动画。
¥Starts an animation after the given delay.
sequence()
static sequence(animations: CompositeAnimation[]): CompositeAnimation;
按顺序启动一系列动画,等待每个动画完成后再开始下一个动画。如果当前运行的动画停止,则不会启动后续动画。
¥Starts an array of animations in order, waiting for each to complete before starting the next. If the current running animation is stopped, no following animations will be started.
parallel()
static parallel(
animations: CompositeAnimation[],
config?: ParallelConfig
): CompositeAnimation;
同时启动一系列动画。默认情况下,如果其中一个动画停止,则所有动画都会停止。你可以使用 stopTogether
标志覆盖它。
¥Starts an array of animations all at the same time. By default, if one of the animations is stopped, they will all be stopped. You can override this with the stopTogether
flag.
stagger()
static stagger(
time: number,
animations: CompositeAnimation[]
): CompositeAnimation;
动画数组可以并行(重叠)运行,但按顺序启动并具有连续的延迟。非常适合做拖尾效果。
¥Array of animations may run in parallel (overlap), but are started in sequence with successive delays. Nice for doing trailing effects.
loop()
static loop(
animation: CompositeAnimation[],
config?: LoopAnimationConfig
): CompositeAnimation;
连续循环给定的动画,以便每次到达结尾时,它都会重置并从头开始。如果子动画设置为 useNativeDriver: true
,则将循环而不阻塞 JS 线程。此外,循环可以防止基于 VirtualizedList
的组件在动画运行时渲染更多行。你可以在子动画配置中传递 isInteraction: false
来解决此问题。
¥Loops a given animation continuously, so that each time it reaches the end, it resets and begins again from the start. Will loop without blocking the JS thread if the child animation is set to useNativeDriver: true
. In addition, loops can prevent VirtualizedList
-based components from rendering more rows while the animation is running. You can pass isInteraction: false
in the child animation config to fix this.
Config 是一个可能具有以下选项的对象:
¥Config is an object that may have the following options:
-
iterations
:动画应循环的次数。默认-1
(无限)。¥
iterations
: Number of times the animation should loop. Default-1
(infinite).
event()
static event(
argMapping: Mapping[],
config?: EventConfig
): (...args: any[]) => void;
获取映射数组并相应地从每个参数中提取值,然后在映射的输出上调用 setValue
。例如
¥Takes an array of mappings and extracts values from each arg accordingly, then calls setValue
on the mapped outputs. e.g.
onScroll={Animated.event(
[{nativeEvent: {contentOffset: {x: this._scrollX}}}],
{listener: (event: ScrollEvent) => console.log(event)}, // Optional async listener
)}
...
onPanResponderMove: Animated.event(
[
null, // raw event arg ignored
{dx: this._panX},
], // gestureState arg
{
listener: (
event: GestureResponderEvent,
gestureState: PanResponderGestureState
) => console.log(event, gestureState),
} // Optional async listener
);
Config 是一个可能具有以下选项的对象:
¥Config is an object that may have the following options:
-
listener
:可选的异步监听器。¥
listener
: Optional async listener. -
useNativeDriver
:如果为 true,则使用原生驱动程序。必需的。¥
useNativeDriver
: Uses the native driver when true. Required.
forkEvent()
static forkEvent(event: AnimatedEvent, listener: Function): AnimatedEvent;
高级命令式 API,用于监听通过 props 传入的动画事件。它允许向现有的 AnimatedEvent
添加新的 javascript 监听器。如果 animatedEvent
是一个 javascript 监听器,它将把 2 个监听器合并为一个监听器,如果 animatedEvent
为 null/未定义,它将直接分配 javascript 监听器。尽可能直接使用值。
¥Advanced imperative API for snooping on animated events that are passed in through props. It permits to add a new javascript listener to an existing AnimatedEvent
. If animatedEvent
is a javascript listener, it will merge the 2 listeners into a single one, and if animatedEvent
is null/undefined, it will assign the javascript listener directly. Use values directly where possible.
unforkEvent()
static unforkEvent(event: AnimatedEvent, listener: Function);
start()
static start(callback?: (result: {finished: boolean}) => void);
动画是通过调用动画的 start() 来启动的。start() 接受一个完成回调,该回调将在动画完成时或动画完成时调用,因为在动画完成之前调用了 stop() 。
¥Animations are started by calling start() on your animation. start() takes a completion callback that will be called when the animation is done or when the animation is done because stop() was called on it before it could finish.
参数:
¥Parameters:
名称 | 类型 | 必需的 | 描述 |
---|---|---|---|
callback | (result: {finished: boolean}) => void | 不 | 动画正常运行结束后或动画完成后将调用的函数,因为在它完成之前调用了 stop() |
以回调开始示例:
¥Start example with callback:
Animated.timing({}).start(({finished}) => {
/* completion callback */
});
stop()
static stop();
停止任何正在运行的动画。
¥Stops any running animation.
reset()
static reset();
停止任何正在运行的动画并将值重置为其原始值。
¥Stops any running animation and resets the value to its original.
属性
¥Properties
Value
驾驶动画的标准值类别。通常在类组件中使用 useAnimatedValue(0);
或 new Animated.Value(0);
初始化。
¥Standard value class for driving animations. Typically initialized with useAnimatedValue(0);
or new Animated.Value(0);
in class components.
你可以在单独的 page 上阅读有关 Animated.Value
API 的更多信息。
¥You can read more about Animated.Value
API on the separate page.
ValueXY
用于驱动 2D 动画(例如平移手势)的 2D 值类。
¥2D value class for driving 2D animations, such as pan gestures.
你可以在单独的 page 上阅读有关 Animated.ValueXY
API 的更多信息。
¥You can read more about Animated.ValueXY
API on the separate page.
Interpolation
导出以在流中使用插值类型。
¥Exported to use the Interpolation type in flow.
Node
导出以便于类型检查。所有动画值均源自此类。
¥Exported for ease of type checking. All animated values derive from this class.
createAnimatedComponent
使任何 React 组件可动画化。用于创建 Animated.View
等。
¥Make any React component Animatable. Used to create Animated.View
, etc.
attachNativeEvent
用于将动画值附加到视图上的事件的命令式 API。如果可能的话,最好使用 Animated.event
和 useNativeDriver: true
。
¥Imperative API to attach an animated value to an event on a view. Prefer using Animated.event
with useNativeDriver: true
if possible.