Reactjs React Native:在React钩子中将Ref从父对象传递给子对象
我尝试了几种不同的方法,但无法找出将ref从父对象传递给子对象的确切语法。最终,我试图使它,以便我可以滚动到开始按下一个子组件。有人能帮我弄清楚吗 获取错误:`scrollViewRef.scrollTo不是函数'Reactjs React Native:在React钩子中将Ref从父对象传递给子对象,reactjs,react-native,Reactjs,React Native,我尝试了几种不同的方法,但无法找出将ref从父对象传递给子对象的确切语法。最终,我试图使它,以便我可以滚动到开始按下一个子组件。有人能帮我弄清楚吗 获取错误:`scrollViewRef.scrollTo不是函数' import React, { useRef } from 'react'; import { ScrollView, Button } from 'react-native'; const Parent = () => { const scrollViewRef =
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" />
)
}
import React,{useRef}来自“React”;
从“react native”导入{ScrollView,Button};
常量父项=()=>{
const scrollViewRef=useRef();
常量滚动开始=()=>{
scrollViewRef.scrollTo({x:0,动画:true});
}
返回(
)
}
const Child=(道具)=>{
返回(
)
}
您需要使用scrollViewRef.current.scrollTo({x:0,动画: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>
)
}
const Parent=()=>{
const scrollViewRef=useRef();
常量滚动开始=()=>{
scrollViewRef..current.scrollTo({x:0,动画:true});
}
返回(
)
}
函数scrollTo()
不直接存在于ref上。您必须使用窗口。scrollTo
或ref.current。scrollTo
检查此项: