不能给函数组件提供 refs ActionweekModal.jsMList.js

问题描述

我有以下问题:

我有 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

解决方法

正如 documentation 所说,您需要将 ref 更改为 listViewRef 才能检索 SwipeListView 的引用。