【问题标题】:How to get ref from custom component in react hook?如何从反应钩子中的自定义组件中获取参考?
【发布时间】:2020-02-06 13:16:14
【问题描述】:

我有这段代码,使用 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>
  )
}
)

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

【问题讨论】:

    标签: react-native react-hooks ref


    【解决方案1】:

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

    【讨论】:

    • 嗨,这不是我的预期,我正在编辑我的问题,请再看一遍,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多