首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ref本机:Ref缺少用于scrollToIndex()的FlatList

Ref本机:Ref缺少用于scrollToIndex()的FlatList
EN

Stack Overflow用户
提问于 2022-04-10 16:29:49
回答 1查看 934关注 0票数 0

我将一个ref传递给一个FlatList,并期望访问scrollToIndex()函数,但是它不会出现在控制台中,当我试图使用它时,它会抛出一个错误:"scrollTo()不是一个函数“,它甚至不承认我试图使用scrollToIndex()。

这是我的代码中使用的一个简单示例:

代码语言:javascript
复制
const ref = useRef()

ref.current?.scrollToIndex({index:itemIndex,animated:true})

<FlatList ref={ref} .../>

有没有人经历过这样的经历,并知道如何让它发挥作用?我已经查看了文档和示例,一切似乎都很好。任何帮助都将不胜感激!

更新:

构成部分:

代码语言:javascript
复制
import React from "react";
import { View, FlatList, ImageBackground,TouchableOpacity,ScrollView,StyleSheet, Text} from "react-native";


const Projects = ({ index, navigation }) => {
 const {width} = Dimensions.get("window")
  const [imageIndex, setIndex] = React.useState(0)
  const ref = React.useRef()
  const wItem = (width - 63) / 2;
console.log("index projects", imageIndex)


const scrollToIndex = (index)=>{
  if(ref.current){
    ref.current.scrollToIndex({index:index})
  }
}
 
const goToIndex = React.useCallback((info) => {
  const wait = new Promise(resolve => setTimeout(resolve, 200));
  wait.then(() => {
    ref.current?.scrollToIndex({ index: info.index, animated: true });
  })
}, [])

  return (
  
      <ScrollView >
      <TouchableOpacity onPress={()=> scrollToIndex(5)}><Text>Scroll to</Text></TouchableOpacity>
      <FlatList ref={ref}
      nestedScrollEnabled
        numColumns={2}
        data={DATA}
        onScrollToIndexFailed={(index)=>goToIndex(index)}
        style={styles.flatList}
        keyExtractor={(i, index) => index.toString()}
        renderItem={({ item, index }) => (
          <View style={styles.item}>
            <ImageBackground
              source={item.image}
              /* @ts-ignore */
              imageStyle={styles.imgStyle}
              style={{ width: wItem, height: wItem, alignItems: "flex-end" }}>
              
            </ImageBackground>
            </TouchableOpacity>
            <Text>{item.title}</Text>
          </View>
        )}
      />
    </ScrollView>
  
  );
};

export default Projects;

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  item: {
    marginRight: 15,
    marginBottom: 24,
    alignItems:'center'
   
  },
  flatList: {
    marginHorizontal: 24,
    marginTop: 16,
  },
  imgStyle: {
    borderRadius: 12,
  },
});

const DATA =//本地图像列表

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-11 08:01:19

它无法调用scrollTo,因为只初始化了ref,在使用时没有分配:

代码语言:javascript
复制
const ref = useRef()
// ref = null

ref.current?.scrollToIndex({index:itemIndex,animated:true})
// ref = null    

<FlatList ref={ref} .../>
// ref != null

因此,在您第一次呈现之前,不指定ref。这意味着,如果您想在ref上调用.scrollTo(),可以通过两种不同的方式进行:

1-如果您想首先滚动到某个索引:

代码语言:javascript
复制
useEffect(() => {
  const initialIndex = 34 //random number
  if (ref.current){
    ref.current.scrollToIndex({index: initialIndex})    
  }
}, [ref])

依赖项数组中的ref将确保每当ref的值发生变化时,useEffect都会运行(在本例中,一旦通过呈现<Flatlist />将其赋值给一个值,它就会改变)。

2-如果您想按需滚动到某个索引:

代码语言:javascript
复制
const handleScrollTo = (index) => {
  if (ref.current && typeof ref.current.scrollToIndex === 'function'){
    ref.current.scrollToIndex({index: index})    
  }
}

这个函数应该连接到类似onPress或类似的东西,这意味着只要用户按下按钮,就应该定义ref,因为能够看到按钮并按下按钮需要组件已经呈现。尽管在这里使用ref.current后应该已经分配了它,但是确保它在没有崩溃的情况下不会崩溃总是很好的做法,这就是为什么我们要添加if-语句。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71818516

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档