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

时间:2019-10-09 08:35:31

标签: react-native react-hooks ref

我有以下代码,使用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函数。谢谢

1 个答案:

答案 0 :(得分:0)

您没有将获得的ref传递给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}
    />