React Native - 如何测量 ScrollView 中的内容大小?

IT技术 javascript reactjs scrollview react-native nativemethodsmixin
2021-04-26 16:23:04

我想测量我的ScrollView.

因此,我使用measurefrom NativeMethodsMixin

import NativeMethodsMixin from 'NativeMethodsMixin'

我不太确定从哪里开始,与此问题相关的大多数 SO 帖子似乎已经过时。

我知道我需要创建一个ref到我的ScrollView(我做了并调用了它_scrollView,我可以使用它访问它this.refs._scrollView)。

问题是,我不能只是传递this.refs._scrollViewmeasure像这样:

NativeMethodsMixin.measure(this.refs._scrollView, (data) => {
  console.log('measure: ', data)
})

然后我收到以下错误:

ExceptionsManager.js:61 findNodeHandle(...): Argument is not a component (type: object, keys: measure,measureInWindow,measureLayout,setNativeProps,focus,blur,componentWillMount,componentWillReceiveProps)

然后我尝试使用检索实际节点句柄findNodeHandle并将其传递给measure这个github 问题中的讨论

const handle = React.findNodeHandle(this.refs._scrollView)
NativeMethodsMixin.measure(handle, (data) => {
  console.log('measure: ', data)
})

但这会导致相同的错误。有任何想法吗?

2个回答

ScrollView 定义了一个名为onContentSizeChange的props

<ScrollView
  onContentSizeChange={(width, height) => {
    console.log(width, height);
  }}>
  {content}
</ScrollView>
NativeMethodsMixin.measure.call(elementToMeasure, (x, y, width, height) => {
  ...
});