同步调用几个“测量”操作

时间:2017-10-11 09:46:57

标签: react-native measure

我必须借助measure()功能测量多个值 因为它是异步操作,所以我只能写:

this.refContainerView.measure((x, y, width, height, pageX, pageY) => {
  const containerViewHeight = height

  this.refCommentList.measure((x, y, width, height, pageX, pageY) => {
    const commentListOffset = pageY
    const commentListHeight = height

  // do something

  })
})

如果需要测量更多组件,它看起来像一个回调地狱 是否可以同步编写代码,例如在await或其他人的帮助下,例如:

const contaierView = this.refContainerView.measure()
const commentList = this.refCommentList.measure()

// and then do something with 
contaierView {x, y, width, height, pageX, pageY}
commentList  {x, y, width, height, pageX, pageY}

1 个答案:

答案 0 :(得分:2)

我找到了解决方案。
measure()不是承诺,但具有回调功能:

measureComponent = component => {
  return new Promise((resolve, reject) => {
    component.measure((x, y, width, height, pageX, pageY) => {
      resolve({ x, y, width, height, pageX, pageY })
    })
  })
}

onDoSomething = async () => {
  const [containerView, commentList] = await Promise.all([
    this.measureComponent(this.refContainerView),
    this.measureComponent(this.refCommentList),
  ])

  // do here with containerView and commentList measures   
  }
}