获取Animated.Value,React-native的当前值

时间:2017-01-30 09:19:02

标签: reactjs react-native react-native-android

我正在尝试使用插值设置动画。我想得到我的Animated.Value的当前值,但不知道如何。我不明白如何使用React-native docs

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
}

6 个答案:

答案 0 :(得分:53)

我发现,如何获得价值:

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

修改

记录我执行以下操作的值:

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

答案 1 :(得分:10)

我没有声明添加评论,但对于有typsecript的人。

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

对我来说,对任何人都有充分的理解。

答案 2 :(得分:8)

这对我也有用......

const headerHeight = new Animated.Value(0);

经过一些操纵......

console.log(headerHeight.__getValue())

感觉很乱,但它完成了工作......

答案 3 :(得分:5)

edit:注意-可能会导致严重的性能问题。我还无法弄清楚为什么,但是如果您将其用于30多个同步动画,则帧速率将变慢。似乎与Animated.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
}

答案 4 :(得分:3)

Number.parseInt(JSON.stringify(translateAnim))

它适用于 React Hook

答案 5 :(得分:0)

这似乎是私有财产。但对我有用。有助于调试,但不建议在生产中使用。

translateAnim._value