欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > react-native-swiper active dot无法更新解决方案

react-native-swiper active dot无法更新解决方案

2025/12/22 23:01:17 来源:https://blog.csdn.net/xiangjiu99/article/details/145503396  浏览:    关键词:react-native-swiper active dot无法更新解决方案

问题描述

一个轮播图组件,展示网络图片,为了避免闪屏,先用本地默认图片作为占位符。

{previewUrl.length > 0 ? (<Swiper loop={true} height={windowWidth}>{previewUrl.map((item, index) => (<Imagekey={index}style={DetailStyle.image}resizeMode="contain"source={{uri: item}}/>))}</Swiper>
) : (<Swiper loop={true} height={windowWidth}><Imagestyle={DetailStyle.image}resizeMode="contain"source={require("@/static/defaultAvator.jpeg")}/></Swiper>
)}

结论

占位符必须在2张以上,不然react-native-swipper会认为当前激活的index一直为0。

{previewUrl.length > 0 ? (<Swiper loop={true} height={windowWidth}>{previewUrl.map((item, index) => (<Imagekey={index}style={DetailStyle.image}resizeMode="contain"source={{uri: item}}/>))}</Swiper>
) : (<Swiper loop={true} height={windowWidth}><Imagestyle={DetailStyle.image}resizeMode="contain"source={require("@/static/defaultAvator.jpeg")}/><Imagestyle={DetailStyle.image}resizeMode="contain"source={require("@/static/defaultAvator.jpeg")}/></Swiper>
)}

image外层也不能包裹fragment,不然react-native-swipper仍然会认为只有一个子节点。

分析过程

布局结束后触发onLayout,如果子节点数大于1就会更新this.internals.offset[this.state.dir]。

  onLayout = event => {const { width, height } = event.nativeEvent.layoutconst offset = (this.internals.offset = {})const state = { width, height }if (this.state.total > 1) {let setup = this.state.indexif (this.props.loop) {setup++}offset[this.state.dir] =this.state.dir === 'y' ? height * setup : width * setup}// ...}

滑动结束会调用updateIndex,根据diff判断是否需要更新子节点。

  updateIndex = (offset, dir, cb) => {const state = this.statelet index = state.indexif (!this.internals.offset)this.internals.offset = {}// 如果子节点数<2,this.internals.offset[dir]会是undefined,diff为NaNconst diff = offset[dir] - this.internals.offset[dir]const step = dir === 'x' ? state.width : state.heightlet loopJump = false// diff为NaN这里就会返回,导致index和this.internals.offset均无法正常更新if (!diff) return// ...const newState = {}newState.index = indexnewState.loopJump = loopJumpthis.internals.offset = offset// ...this.setState(newState, cb)}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词