首页 > 解决方案 > 函数组件不能给出 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

标签: react-nativereact-functional-componentcreate-ref

解决方案


正如文档所说,您需要更改reflistViewRef才能检索SwipeListView.


推荐阅读