首页 > 解决方案 > 为什么 react-native 的 onLayout 在 ios 中以随机顺序出现?

问题描述

为什么 react-native 的 onlayout 在 IOS 设备上的 array.map 中使用时以明显随机的顺序返回?

我在一个函数中使用 onlayout,它基于对象数组返回许多可触摸的不透明度组件。它找到尚未通过的第一个,然后使用以下代码存储其位置以滚动到它:

renderScrollViewContent () {
var data = this.state.dataSource.topics[this.state.TopicID].programs
return (
  <View style={{flex: 1, marginTop: 7}}>
    {
        data.map((l, i) => (
          console.log("B:" + l.title),
          <TouchableOpacity key={i}
            onLayout={event => {
              console.log("C:" + l.title)
              if (this.state.scrollPosition === 0 && Moment().isBefore(l.end_time)) {
                const layout = event.nativeEvent.layout
                this.state.scrollPosition = layout.y  
                ...

问题是,虽然 B: 总是以相同的顺序,但 C: 每次都不同,就像它被异步绘制一样,但仅在 IOS 设备上 - android 测试每次都显示相同。

有没有办法让它同步或以其他方式获取结束时间尚未过去的第一个数组元素的 y 位置?ios和android使用onlayout的方式有什么区别?

标签: iosreact-native

解决方案


const setCoordinates = (event, itemIndex) => {
      console.log('itemIndex:', itemIndex)
      // and your logic of itemIndex
   }

items.map((item, index)=> {
   return (
      <View
         key={index}
         onLayout={(event) => setCoordinates(event, index)}
      >
        <Text>TextExample<Text>
      </View>
   )

})

推荐阅读