Reactjs 获取动画的当前值。值,反应本机
我正在尝试使用插值设置视图的动画。我想获取动画.value的当前值,但不知道如何获取。我不知道该怎么做Reactjs 获取动画的当前值。值,反应本机,reactjs,react-native,react-native-android,Reactjs,React Native,React Native Android,我正在尝试使用插值设置视图的动画。我想获取动画.value的当前值,但不知道如何获取。我不知道该怎么做 this.state={ translateAnim:新的动画值(0) } DeviceEventEmitter.addListener('Accelerator',函数(数据){ console.log(this.state.translateAnim); //返回一个对象,但我需要当前时刻的值 } 我发现如何获取值: this.state.translateAnim.addListener
this.state={
translateAnim:新的动画值(0)
}
DeviceEventEmitter.addListener('Accelerator',函数(数据){
console.log(this.state.translateAnim);
//返回一个对象,但我需要当前时刻的值
}
我发现如何获取值:
this.state.translateAnim.addListener(({value})=>this.\u value=value);
编辑
要记录值,请执行以下操作:
console.log(this.state.translateAnim.\u值)
这对我也适用
const headerHeight=新的动画值(0);
经过一些操纵
console.log(headerHeight.\uu getValue())
它让人感觉很粗糙,但它完成了工作…对于使用typescript的人来说
console.log((this.state.translateAnim,如有)。\u值);
对我来说,完全使用tsc是有效的。编辑:注意-可能会导致严重的性能问题。我还不知道为什么,但是如果你同时使用30多个动画,你的帧速率会慢到爬行。这似乎是react native with 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
}
它与tsc一起在React Hook上工作给我一个警告:
属性'\u value'在'value'类型中不存在。
@jose920405你知道如何用tsc编译它吗?这个观察者记录在:-他们说“这很有用,因为无法同步读取值,因为它可能是本机驱动的。"可以使用//@ts ignore comment忽略React本机版本0.59.1中的Line的tsc警告。它说,addListener不是一个函数。如果我错了,请纠正我。我无法通过任何方式控制动画值。警告:如果userNativeDriver为真,这将始终返回0。您如何在功能组件中添加addListener?@roz333我编写了一个hook to在我下面的回答中处理这个问题,而不是userNativeDriver
非常感谢!当我尝试将动画.动画乘法的类型转换为数字解析int(JSON.stringify(translateAnim))
时,这对我很有效,没有数字
Number.parseInt(JSON.stringify(translateAnim))