javascript - React Native - 如何将 .subscribe() 与滚动视图的 onLayout 和 onScroll 一起使用?
问题描述
所以我有一个滚动视图,其中包含显示食物和饮料类别的组件以及“类别”的 onLayout 我运行此代码以获取它们的 x 和 y 值。
_onLayoutCategories = ({ nativeEvent: { layout: { x, y, width, height } } }) => {
this.setState(prevState => ({
categoryYvals: [...prevState.categoryYvals, y].sort(function (a, b) { return a - b })
}))
};
我还有另一个水平滚动视图,只显示类别标题,在这些布局上,我运行这段代码,仍然简单地获取它们的坐标和类似的东西
_onLayoutCatTitles = ({ nativeEvent: { layout: { x, y, width, height } } }) => {
if (this._isMounted) {
this.setState(prevState => ({
catTitlesWidths: [...prevState.catTitlesWidths, width],
catTitlesXvals: [...prevState.catTitlesXvals, x].sort(function (a, b) { return a - b }),
catTitlesWidthsRef: [...prevState.catTitlesWidthsRef, { [x]: width }]
}))
}
};
现在我这样做是为了在滚动类别滚动视图时运行这个函数:
handleScroll = (event) => {
var y = event.nativeEvent.contentOffset.y
var translateValueX;
var translateValueW;
for (let i = 0; i < this.state.categoryYvals.length; i++) {
if (y > this.state.categoryYvals[i] && y < this.state.categoryYvals[i + 1]) {
translateValueX = this.state.catTitlesXvals[i];
translateValueW = this.state.catTitlesWidths[i];
Animated.parallel([
Animated.timing(
this.state.translateX,
{
toValue: translateValueX,
duration: 75,
}
),
Animated.timing(
this.state.translateWidth,
{
toValue: translateValueW,
duration: 50,
}
)
]).start()
}
}
}
现在,它在第一次安装时工作正常。但是,当我返回并导航回屏幕(使用 React Navigation 5.x)和 onLayout 功能时,我收到“未安装组件上的 setstate,这是一个无操作并指示内存泄漏......”的错误没有正确调用this.state.catTitlesValues
并且this.state.catTitlesWidths
是空的并且在尝试动画时会导致错误。
我将如何实现 .subscribe() 或承诺解决这个问题?任何帮助将不胜感激,我需要它。先感谢您!:D
成分:
<ScrollView stickyHeaderIndices={[0]} ref={(node) => this.scroll = node} onScroll={this.handleScroll} scrollEventThrottle={1}>
.................
<ScrollView style={{ backgroundColor: 'white', borderBottomColor: 'orange', borderBottomWidth: 1 }}
horizontal={true}
showsHorizontalScrollIndicator={false}
ref={(node) => this.scrollTitles = node}>
<View style={{ flexDirection: 'row', alignItems: 'center', height: 50 }}>
{getCatTitles(this.props.route.params['menu'])}
</View>
<Animated.View style={[styles.highlight, { left: this.state.translateX, width: this.state.translateWidth }]}></Animated.View>
</ScrollView>
</View>
{DisplayMenu(this.props.route.params['menu'], this)}
解决方案
推荐阅读
- r - nls sslogis:使用虚拟变量作为交互项来比较两个 sigmoid 模型
- twilio - Twillio 通话耳语和录音
- javascript - 尝试下载到对象的 csv javascript 数组
- azure - 无法授权 Azure 订阅在基于 YAML 的管道中使用
- python - Keras Lambda 层计算平均值
- arrays - 在 Swift 中从二进制文件中读取整数
- django - 任何人都可以为我的 django 项目建议一个数据库模式吗?
- javascript - 提交空搜索请求时出现错误“TypeError: Cannot read property 'map' of undefined”
- jira - Leverice 中的 Jira 通道状态
- powershell - pwsh -Command 正在删除引号