【问题标题】:React-Native Reference to FlatList doesn't work对 FlatList 的 React-Native 引用不起作用
【发布时间】:2018-03-13 10:17:48
【问题描述】:

我尝试在我的 react native 应用程序中始终滚动到我的平面列表的底部,但不幸的是我没有得到对平面列表的引用。

            <View style={styles.viewPointOverview}>
                <Text > Point overview: </Text>
                <FlatList
                    ref={(ref) => this.flatList = ref}
                    data={pointRecord}
                    renderItem={({ item }) => <Text>{item}</Text>}
                />
            </View>

在渲染函数中我尝试调用方法 scrollToEnd()

this.flatList.scrollToEnd();

我在平面列表中尝试过

ref = {"flatlist"}

ref = "flatlist"

但是他们都没有工作我总是得到错误: 类型错误:无法读取未定义的属性“scrollToEnd”。

你可以在这里找到完整的代码:https://github.com/AlessandroVol23/Counter10000/blob/master/app/screens/PlayScreen.js

【问题讨论】:

  • Sandro_V,看看我下面的答案,它会对你有所帮助。
  • 你首先在哪里定义了“this.flatlist”?
  • 当然,你在渲染方法中使用this.refs.flatlist.scrollToEnd({animated: true });是行不通的,第一次引用不存在,所以它会给你错误。你必须把它放在一个方法中,让它在初始化后工作
  • 啊当然!很抱歉,感谢您的解决!

标签: react-native react-native-flatlist


【解决方案1】:

你必须使用 ref 所以它将是this.refs.flatlist.scrollToEnd()

您还可以添加动画可选参数:

  this.refs.flatlist.scrollToEnd({animated: true });

对于声明,我个人是这样做的:

ref='flatlist'

然后你必须使用这个技巧调用这个函数的方法(不是在没有引用的渲染中,因为它将在第一次完整渲染后首先声明):

React Native ListView scrollToEnd it doesn't work

【讨论】:

  • 还是不行。像这样ref={(ref) =&gt; this.flatList = ref}和像这样ref='flatlist'在flatlist中试过然后我在渲染方法中调用了该方法:this.refs.flatlist.scrollToEnd({animated: true });
  • 你能展示一下你使用这个的完整方法吗?
  • render() { const { players, playerAmount } = this.props; const pointRecord = players[this.state.currentPlayerNumber].pointRecord; this.refs.flatlist.scrollToEnd({animated: true }); 这是完整的方法。 github.com/AlessandroVol23/Counter10000/blob/master/app/screens/…有完整代码
  • 你不能像这样在渲染中这样做,因为在第一次渲染时 ref 将不存在并且会导致错误
【解决方案2】:

您需要从引用中访问您的 FlatList 以调用方法 scrollToEnd()

this.refs.flatlist.scrollToEnd({animated: true });

将您的代码 this.flatList.scrollToEnd(); 更改为 this.refs.flatlist.scrollToEnd();

它会为你工作。

【讨论】:

    【解决方案3】:

    就像 Clad Clad 告诉我的那样,我在 render 方法中有它,当然此时 flatlist 元素不存在。 谢谢! :-)

    【讨论】:

      【解决方案4】:

      您应该将 ref={(ref) =&gt; { this.listRef = ref; }} 属性提供给 Flat List。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-04
        • 2020-03-21
        • 1970-01-01
        • 2020-09-25
        • 2021-05-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多