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