react-native - 函数组件不能给出 refs
问题描述
我有以下问题:
我有 ActionWeekModal,其中包含我自己的名为 MList 的自定义组件。在这个 MList 中有一个SwipeListView。我想使用 ActionWeekModal 中 SwipeListView 的引用来触发函数 scrollToEnd()。这应该是可能的,因为 SwipeListView 从 FlatList 继承了这个功能。但是我得到的错误如下:
warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
但我在 MList.js 中使用 React.forwardRef()。我究竟做错了什么?
ActionweekModal.js
import React, { useState, useRef } from 'react'
{ ... }
export default function ActionWeekModal({ navigation, route }) {
const mlist = React.createRef()
{ ... }
const scroll = () => {
mlist.current.scrollToEnd()
}
return (
<MModal
isVisible={true}
onBackdropPress={() => NavigationService.goBack()}
onCancel={() => NavigationService.goBack()}
title="Actieweek"
>
<Button title={'button'} onPress={() => scroll()} />
<ScrollView>
<MList
keyExtractor={keyExtractor}
data={actionWeeks}
refreshing={isFetching}
renderItem={renderItem}
ref={mlist}
initialNumToRender={15}
onEndReached={() => {
if (hasNextPage) {
fetchNextPage()
}
}}
onEndReachedThreshold={0.2}
/>
</ScrollView>
</MModal>
)
}
MList.js
import React from 'react'
{ ... }
const MList = React.forwardRef((props, ref) => (
<View style={ApplicationStyles.screen}>
<SwipeListView
style={ApplicationStyles.flatListContainer}
data={props.data}
ref={ref}
initialNumToRender={props.initialNumToRender}
keyExtractor={props.keyExtractor}
renderItem={props.renderItem}
onEndReached={props.onEndReached}
onEndReachedThreshold={props.onEndReachedThreshold ?? 1}
closeOnRowOpen
closeOnRowPress={true}
closeOnRowBeginSwipe
disableRightSwipe
{...props}
/>
</View>
))
export default MList
解决方案
正如文档所说,您需要更改ref
为listViewRef
才能检索SwipeListView
.
推荐阅读
- amazon-web-services - listNextBatchOfObjects() 请求对象
- php - Bronto PHP API 获取特定电子邮件的特定列表的订阅状态
- node.js - 在 Active Directory 中设置或修改经过身份验证的用户的特定属性值
- java - 如何在 Guice 中进行急切的单例初始化
- javascript - 堆叠条形图 chartist.js 中的边界半径
- c++ - 在可移动类型的构造函数 lambda 中安全使用捕获的 this
- networking - 无法ping主路由器默认网关
- c# - 如何访问 Powershell 二进制模块 FileList 属性中的文件
- distributed - 如何从分布式表中获取数据
- knockout.js - 淘汰赛无法使用函数代替 ko.computed()