【问题标题】:Cannot access the scrollToIndex() method in React Native using the useRef hook无法使用 useRef 挂钩访问 React Native 中的 scrollToIndex() 方法
【发布时间】:2020-02-06 09:31:04
【问题描述】:

我正在尝试使用功能组件中的 useRef 挂钩从 FlatList 访问 scrollToIndex() 方法或 scrollToItem() 方法。我希望能够在我的组件中使用flatListRef.current.ScrollToIndex(),类似于基于类的组件使用this.flatListRef.ScrollToIndex():

 const flatListRef = useRef(React.createRef)
 <FlatList 
    data={items}
    renderItem={({ item }) => <Item item={item} />}
    keyExtractor={item => item.id.toString()}
    contentContainerStyle={styles.card}
    horizontal={true}
    showsHorizontalScrollIndicator={false}  
    ref={flatListRef}                      
/>

console.logging flatListRef.current 没有显示我正在寻找的上述方法。

【问题讨论】:

    标签: reactjs react-native react-hooks


    【解决方案1】:

    您不需要使用createRef 创建引用,您可以使用useRef()。另一个重要的事情是正确使用scrollToIndex。请参阅documentation 和下面的代码。

    代码:

    const CustomFlatList = () => {
      const flatListRef = useRef(); // useRef 
      return (
        <View>
        <FlatList 
            data={items}
            renderItem={({ item }) => <Text style={{width: 100}}> {item.id} </Text> }
            keyExtractor={item => item.id.toString()}
            contentContainerStyle={styles.card}
            horizontal={true}
            showsHorizontalScrollIndicator={false}  
            ref={flatListRef} // create ref                
        />
         <TouchableHighlight onPress={() => flatListRef.current.scrollToIndex({index: 4, animated: true })}>
         <Text> ScrollToIndex </Text>
          </TouchableHighlight>
        </View>
      )
    }
    

    工作示例:

    https://snack.expo.io/B1rfdbsuS

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      • 2020-03-07
      • 2020-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多