我需要测量组件与屏幕顶部之间的距离,然后将此值传递给孩子。
class MyComponent extends React.Component {
state = {
containerHeight: 0
};
handleLayoutChange() {
this.conainerView.measure(
(fx, fy, containerWidth, containerHeight, px, yOffsetToPage) => {
this.setState({ containerHeight });
}
);
}
render() {
return (
<View
onLayout={event => {
this.handleLayoutChange(event);
}}
ref={view => {
this.conainerView = view;
}}
>
<Child containerHeight={this.state.containerHeight} />
</View>
);
}
}
上面的代码在页面加载时有效,但是在滚动时(父组件具有ScrollView)或方向改变时不会更新。什么是“正常”解决方案?我对React Native还是很陌生,但感觉就像我在为一件很简单的事情写很多代码,所以我想知道我做错了什么吗?
组件有一个称为onScroll的道具,其参数包含偏移值,遵循此格式nativeEvent: { contentInset: { bottom, left, right, top }, contentOffset: { x, y }, contentSize: { height, width }, layoutMeasurement: { height, width }, zoomScale } }
我认为您可以使用它来监听滚动事件并计算新的测量值。