简体   繁体   English

如何将 ref 传递给 react-native-reanimated 组件?

[英]How can I pass a ref to a react-native-reanimated component?

I'm trying to pass a ref to a component with a similar approach to the following code block, but the current value always returns undefined .我正在尝试使用与以下代码块类似的方法将 ref 传递给组件,但current值始终返回undefined This approach works fine with a plain FlatList from react-native, however it doesn't work once I'm using either an Animated.FlatList or an Animated.createAnimatedComponent(FlatList) :这种方法适用于来自 react-native 的普通FlatList ,但是一旦我使用Animated.FlatListAnimated.createAnimatedComponent(FlatList)

const Parent = () => {
    const flatListRef = useRef();

    useEffect(() => {
        console.log(flatListRef.current) // undefined
    })

    return (
        <View>
            <Child ref={flatListRef} />
        </View>
    )
}

const Child = React.forwardRef((props, ref) => {

    return (
        <Animated.FlatList
            ref={ref}
        />
    )
})

The library react-native-reanimated works a little bit different in comparison to react-native-animated .react-native-reanimatedreact-native-animated相比有点不同。

If we create the animated component via Animated.createAnimatedComponent(FlatList) , then everything works as expected.如果我们通过Animated.createAnimatedComponent(FlatList)创建动画组件,那么一切都会按预期进行。

Here is a working version of your code.这是您的代码的工作版本。 I have logged the function scrollToIndex of the FlatList ref for testing purposes.为了测试目的,我已经记录了FlatList ref 的 function scrollToIndex

import Animated from "react-native-reanimated"

const ReanimatedFlatList = Animated.createAnimatedComponent(FlatList);

const Parent = (props) => {
    const flatListRef = useRef(null);

    useEffect(() => {
      console.log(flatListRef.current.scrollToIndex)
    }, [])

    return (
        <View>
            <Child ref={flatListRef} />
        </View>
    )
}

const Child = React.forwardRef((props, ref) => {
    return (
        <ReanimatedFlatList
            ref={ref}
        />
    )
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM