获取 Animated 的当前值

我试图用插值动画视图。我想得到我的动画的当前价值。价值,但不知道如何。我不知道如何使用 本地反应医生

this.state = {
translateAnim: new Animated.Value(0)
}
DeviceEventEmitter.addListener('Accelerometer', function (data) {
console.log(this.state.translateAnim);
// returns an object, but I need a value in current moment
}
73629 次浏览

我发现,如何得到一个值:

this.state.translateAnim.addListener(({value}) => this._value = value);

剪辑

要记录一个值,我需要执行以下操作:

console.log(this.state.translateAnim._value)

这对我也有用。

const headerHeight = new Animated.Value(0);

经过一些操纵... 。

console.log(headerHeight.__getValue())

感觉很恶心,但能完成任务。

为打字员准备的。

console.log((this.state.translateAnim as any)._value);

它为我工作,以充分的 tsc 作为任何。

注意-可能导致严重的性能问题。我还不能弄清楚为什么,但如果你使用30 + 同步动画你的帧速度将缓慢爬行。它似乎必须是一个错误的反应-本地与动画。Value addListener 因为我没有发现我的代码有什么问题,它只是设置了一个侦听器,该侦听器设置了一个应该是即时的 ref。

下面是我想到的一个方法,它不需要求助于访问私人内部价值。

/**
* Since there's no (official) way to read an Animated.Value synchronously this is the best solution I could come up with
* to have access to an up-to-date copy of the latest value without sacrificing performance.
*
* @param animatedValue the Animated.Value to track
* @param initial Optional initial value if you know it to initialize the latest value ref before the animated value listener fires for the first time
*
* returns a ref with the latest value of the Animated.Value and a boolean ref indicating if a value has been received yet
*/
const useAnimatedLatestValueRef = (animatedValue: Animated.Value, initial?: number) => {
//If we're given an initial value then we can pretend we've received a value from the listener already
const latestValueRef = useRef(initial ?? 0)
const initialized = useRef(typeof initial == "number")


useEffect(() => {
const id = animatedValue.addListener((v) => {
//Store the latest animated value
latestValueRef.current = v.value
//Indicate that we've recieved a value
initialized.current = true
})


//Return a deregister function to clean up
return () => animatedValue.removeListener(id)


//Note that the behavior here isn't 100% correct if the animatedValue changes -- the returned ref
//may refer to the previous animatedValue's latest value until the new listener returns a value
}, [animatedValue])




return [latestValueRef, initialized] as const
}


Number.parseInt(JSON.stringify(translateAnim))

它可以在反应钩上工作

它看起来像私有属性。但对我有用。有助于调试,但不推荐在生产中使用它。

translateAnim._value