简体   繁体   中英

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 . 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) :

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 .

If we create the animated component via Animated.createAnimatedComponent(FlatList) , then everything works as expected.

Here is a working version of your code. I have logged the function scrollToIndex of the FlatList ref for testing purposes.

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}
        />
    )
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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