如何从React挂钩中的自定义组件获取引用?

问题描述 投票:0回答:1

我有此代码,使用React.useRef(),但不起作用:Main.js:

import * as React from "react"
export const Main: React.FunctionComponent<Props> = observer((props) => {
  const ref = React.useRef()

  React.useEffect(() => {
    ///Can not get ref from message
    ref.gotoPosition(5)
  }, [])
  return (
    <View style={styles.container}>
      <Message
        ref={ref}
        getGotoIndex={getFunction}
        onEndList={isShowQuickMove}
        isSpeaker={state.isSpeaker}
        questionsList={state.questionsList}
        clickQuestion={clickQuestion}
        isTyping={chatStore.loading}
        data={state.data}/>
    </View>
  )
}

Message.js:

import * as React from "react"
// eslint-disable-next-line react/display-name
export const Message = React.forwardRef((props, ref) => ({
  const { ... } = props

  const gotoPosition = (index) => {
    console.log('in here')
  }
  return (
    <View>
....
</View>
  )
}
)

即使我使用React.forwardRef,我也无法从Message获取引用。如何通过ref.gotoPosition(5)之类的ref访问Message中的gotoPosition函数。谢谢

react-native react-hooks ref
1个回答
0
投票

您没有将获得的参考传递给Flatlist,只需要像这样传递它:

    <FlatList
      ref={ref} // create a referenece like so
      extraData={[data, isSpeaker]}
      onEndReached={handleEnd}
      onEndReachedThreshold={0.4}
      data={data}
      keyExtractor={(item, index) => index.toString()}
      renderItem={renderItems}
    />
© www.soinside.com 2019 - 2024. All rights reserved.