我有一个带有嵌套项目的视图,实现了显示接收到的 props 数组的类似列表的块,我想从所有子项的高度总和中获取该块的高度。所以我的组件看起来像这样:
class MultiColumnBox extends Component {
state = {
calculatedMaxHeight: null,
};
measureBlock = () => {
let totalHeight = 0;
//this.props.data is array
this.props.data.forEach((item, index) => {
this['checkbox_${index}'].measure((x , y, width, height) => {
console.log(height)
totalHeight += height;
})
if (index === (this.props.data.length - 1)) {
this.setState({
calculatedMaxHeight: totalHeight
})
}
})
};
render() {
return (
<View
onLayout={() => this.measureBlock()}
>
{this.props.data.map((item, index) => (
<View ref={node => this[`checkbox_${index}`] = node}>
// some content....
</View>
)}
</View>
)
}
}
但是如果有例如 5 个高度为 40dp 的块,它将控制台日志 40 5 次并将 state.calculatedMaxHeight 设置为 0。但是如果我if (index === (this.props.data.length - 1))
在测量函数中移动条件,它会正常工作并将 state.calculatedMaxHeight 设置为 200。为什么它是这样工作的吗?无论在测量函数内部嵌套如何,我都使用相同的index
变量并增加相同的totalHeight
变量,在循环外定义一次。
我认为问题在于 setState 函数在为第一个节点调用的度量内部的回调函数之前被调用。
console.log(height)将打印 40 5 次,但在第一次打印高度值之前,calculatedMaxHeightt 被设置为 0。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句