reactjs 获取动画的当前值,值,React-本机

z8dt9xmd  于 2023-01-17  发布在  React
关注(0)|答案(7)|浏览(145)

我正在尝试用插值来动画视图。我想得到我的Animated.Value的当前值,但是不知道怎么做。我不知道如何用React原生文档来做。

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
}
vlf7wbxs

vlf7wbxs1#

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

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

编辑
要记录值,我执行以下操作:

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

xxhby3vn2#

这对我也有效......

const headerHeight = new Animated.Value(0);

经过一些操作...

console.log(headerHeight.__getValue())

感觉有点像黑客,但它完成了工作...

kmpatx3s

kmpatx3s3#

给有 typescript 的人。

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

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

3phpmpom

3phpmpom4#

Number.parseInt(JSON.stringify(translateAnim))

在React Hook上有效

waxmsbnn

waxmsbnn5#

编辑:警告-可能会导致严重的性能问题。我还不能找出原因,但如果你使用这个30+同时动画你的帧率会慢到爬行。它似乎一定是一个错误的react-native与动画。值addListener,因为我没有看到任何错误与我的代码,它只设置一个侦听器,设置一个参考,这应该是即时的。
这里有一个我想到的钩子,它可以在不访问私有内部值的情况下完成此操作。

/**
 * 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
}
sczxawaw

sczxawaw6#

它看起来像私有财产。但对我有用。有助于调试,但不建议在生产中使用它。

translateAnim._value
oymdgrw7

oymdgrw77#

我实际上找到了另一种获取值的方法(不确定这是否是推荐的方法,但它很有效)。
对动画值使用JSON.stringify(),并对结果使用“Number”将其转换为“Number”。
例如,

const animatedVal = new Animated.Value(0);

const jsanimated = JSON.stringify(animatedVal);

const finalResult = Number(jsanimated)

相关问题