reactjs - 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" />
)
}
解决方案
您需要使用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>
)
}
推荐阅读
- javascript - React:重复值仅显示在材料 ui 表中的第一项上
- wpf - 更改 .Net Web 应用程序和 wpf 客户端的 IDP 提供程序。如何处理用户不想升级桌面应用程序的场景
- python - 如何使用变量中的值调用方法?
- java - 尝试将字符串转换为 java.sql.Date 时出现异常
- spring-boot - 如何配置 ElasticsearchRepositoryFactory 以在具有 ElasticsearchCustomConversions 的独立程序中使用 ElasticsearchRepository
- java - 在注释处理期间是否可以获取超类构造函数参数?
- javascript - 是否可以访问网站的元素?
- c# - 如何在 Linq <> ASP.NET MVC <> C# 中使用“IN”语句
- php - PHP - 列出计划日的空闲时间段
- r - 如何制作一个数据集,其中的行表示编号。的集群,而列是两个变量,集群的值不同