React Native:在React Hook中将Ref从父对象传递给子对象

时间:2020-05-25 04:25:21

标签: reactjs react-native

尝试了几种不同的方法,无法找出将引用从父对象传递给子对象的确切语法。最终,我试图做到这一点,以便可以滚动到Child组件的开始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" />
  )
}

1 个答案:

答案 0 :(得分:1)

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

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>
  )
}