【发布时间】:2020-06-30 17:14:36
【问题描述】:
我有一个ScrollView 的引用,需要得到它的高度。它似乎没有高度属性:
import React, { useRef, useEffect } from "react";
import { View, ScrollView } from "react-native";
function Component() {
const scrollView = useRef(null);
useEffect(
function() {
// All of these print undefined
console.log(scrollView.height);
console.log(scrollView.current.height);
console.log(scrollView.current.clientHeight);
},
[scrollView]
);
return (
<ScrollView ref={scrollView}>
<View style={{ height: 800, width: 100 }} />
</ScrollView>
);
}
我如何简单地从 ref 中获取 scrollView 的高度?在 ReactJS 中是可能的,但我不确定 react-native。
如果可能的话,我想在不使用 onLayout 的情况下执行此操作。如果 onLayout 是唯一的方法,请告诉我。
【问题讨论】:
-
这能回答你的问题吗? Get size of a View in React Native
-
@Qiarash 不完全是。我知道 onLayout 可用于在布局视图后获取元素的高度,但我希望能够在不使用 onLayout 回调的情况下从 ref 本身获取高度。不过,获得高度的唯一方法可能是 onLayout 回调。我只是觉得裁判也应该有这些信息。
-
我相当有信心
onLayout是做到这一点的唯一方法。但是,如果您想将其从业务逻辑中抽象出来,那么您可以围绕 ScrollView 构建一个包装器,将布局高度和宽度保存到状态。然后你可以从 ref 访问它。
标签: reactjs react-native react-hooks