【问题标题】:How to use scrollTo function with argument is target not x and y in ListView?如何使用带有参数的scrollTo函数是ListView中的目标而不是x和y?
【发布时间】:2018-12-06 08:35:19
【问题描述】:

当我有多个 <View /> 时,我在获取 x 和 y 时遇到了一些问题,但我发现参数 target 的值是正确的。所以我决定使用它。

这是我的 scrollTo 函数:

listView.scrollTo({ x, y, animated: true});

我改成这样,但它不起作用:

listView.scrollTo({ target, animated: true});

有什么方法可以将 scrollTo 与 target 一起使用吗?

任何帮助将不胜感激。

【问题讨论】:

    标签: react-native react-native-listview


    【解决方案1】:

    您必须实现自己的 scrollToTarget 方法才能实现这一点。

    我的解决方案是……像这样:

    import * as React from 'react';
    import { Text, View, StyleSheet, ScrollView, findNodeHandle, Button } from 'react-native';
    
    export default class App extends React.Component {
    
      itemRefs = [];
      state = {
        dummyList: ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7"]
      };
    
      scrollToItem = () => {
        // Scroll to Item 2
        let refToScroll = this.itemRefs["Item 2"];
        refToScroll.measureLayout(findNodeHandle(this.listRef), (x,y) => {this.listRef.scrollTo({x: 0, y: y, animated: true})});
      }
    
      renderItems = ({ item }) => {
       return (
         <View ref={ref => {this.itemRefs[item] = ref}} style={{height: 200, margin: 20, borderWidth: 5, borderColor: "black"}}>
          <Text>{item}</Text>
         </View>
       )
      }
    
      render() {
        return (
          <View>
          <View style={{height: 25}}/>
          <Button containerStyle={{height: 55}} title="Click to scroll" onPress={this.scrollToItem} />
          <ScrollView
            ref={ref => {this.listRef = ref}}
            data = {this.state.dummyList}
            renderItem ={this.renderItems}
            >
            {this.state.dummyList.map(item => (
              <View ref={ref => {this.itemRefs[item] = ref}} style={{height: 200, margin: 20, borderWidth: 5, borderColor: "black"}}>
                <Text>{item}</Text>
              </View>
            ))}
            </ScrollView>
            </View>
        );
      }
    }
    

    【讨论】:

    • 感谢您的回复,但您的findNodeHandle 功能在哪里?能再贴一下代码吗?谢谢你。
    • 从上面检查我的导入。它是 react-native 库的一部分
    • 嘿,谢谢!我尝试findNodeHandle,我认为它只是像onLayout 一样计算视图。 findNodeHandle 无法滚动到任何视图的位置。我仍然必须使用this.listRef.scrollTo({x: 0, y: y, animated: true})},但我的y 仍然是个问题。
    • 上面的代码可以工作,但我不知道你是如何将它实现到你的代码库中的。在这里查看:snack.expo.io/@mukeyii/list-scrolltoitem
    猜你喜欢
    • 2010-11-05
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 2014-07-02
    相关资源
    最近更新 更多