首页 > 解决方案 > React Native:在 React Hooks 中将 Ref 从父级传递给子级

问题描述

尝试了几种不同的方法,但无法弄清楚将 ref 从父级传递给子级的确切语法。最终,我试图做到这一点,以便我可以滚动到子组件的 onPress 开头。有人可以帮我弄清楚吗?

出现错误:`scrollViewRef.scrollTo 不是函数'

import React, { useRef } from 'react';
import { ScrollView, Button } from 'react-native';

const Parent = () => {

  const scrollViewRef = useRef();

  const scrollToBeginning = () => {
    scrollViewRef.scrollTo({ x: 0, animated: true });
  }

  return (
    <ScrollView
      ref={ scrollViewRef }
      pagingEnabled
      snapToInterval={ width }
      horizontal
      scrollEventThrottle={16}
      scrollEnabled={ true }
    >
      <Child
        scrollToBeginning={ scrollToBeginning }
      >
    </ScrollView>
  )
}


const Child = (props) => {
  return (
    <Button onPress={ props.scrollToBeginning } title="Scroll To Beginning" />
  )
}

标签: reactjsreact-native

解决方案


您需要使用scrollViewRef.current.scrollTo({ x: 0, animated: true });,因为 ref 属性已分配给 ref 对象中的当前变量

const Parent = () => {

  const scrollViewRef = useRef();

  const scrollToBeginning = () => {
    scrollViewRef..current.scrollTo({ x: 0, animated: true });
  }

  return (
    <ScrollView
      ref={ scrollViewRef }
      pagingEnabled
      snapToInterval={ width }
      horizontal
      scrollEventThrottle={16}
      scrollEnabled={ true }
    >
      <Child
        scrollToBeginning={ scrollToBeginning }
      >
    </ScrollView>
  )
}

推荐阅读