【问题标题】:Function components cannot be given refs函数组件不能给出 refs
【发布时间】:2021-05-26 14:39:23
【问题描述】:

我有以下问题:

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

【问题讨论】:

  • 你能禁用{...props}这一行看看会发生什么吗?
  • @LeriGogsadze 删除 ` {...props}` 没有区别

标签: react-native react-functional-component create-ref


【解决方案1】:

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

【讨论】:

  • 当我这样做时,我得到TypeError: null is not an object (evaluating 'Object.keys(this.props.listViewRef)')
猜你喜欢
  • 1970-01-01
  • 2020-10-20
  • 1970-01-01
  • 2018-03-29
  • 1970-01-01
  • 2020-02-22
  • 2020-08-10
  • 1970-01-01
  • 2021-06-05
相关资源
最近更新 更多