0

我正在为 sectionlist 创建一个间谍滚动,我想获取 section list header 的 Y 值,

我尝试使用 onLayout 方法,但我只得到 0 的 y 值。我假设我的组件位于 react-native 容器内,因此我的视图获得了该容器的相对值 0..

这是我的代码:

<Animated.SectionList
                    initialNumToRender={5}
                    keyExtractor={(item) => item.docRef}
                    sections={data.slice()}
                    renderSectionHeader={this.renderSectionHeader}
                    renderItem={this.renderItem}
                    stickySectionHeadersEnabled={false}
                />

renderSectionHeader = ({section}) => {
    const index = section.sort;
    return (
        <View onLayout={e => this.onSectionLayout(e, index)}>
            <SectionListHeader section={section} index={index}/>
        </View>
    )
};

onSectionLayout = ({nativeEvent: {layout: {x, y, width, height}}}, index) => 
{
    console.log(height)
};
4

1 回答 1

1

这是因为SectionHeader被父视图包裹,所以y位置始终为0。

另一种方法是 ref.measure。like

constructor(props) {
    super(props)
    this.sectionHeaders = []
}

renderSectionHeader = ({section}) => {
    const index = section.sort;
    return (
        <View ref={c => this.sectionHeaders[index] = c}>
            <SectionListHeader section={section} index={index}/>
        </View>
    )
};

componentsDidMount() {
    setTimeout(() => {
      this.sectionHeaders.forEach((ref,index)=>{
        ref.measure((fx,fy,w,h,px,py) => {
           console.log('y pos is ',py))
        })
     })
  }, 500)
}
于 2019-06-25T09:50:52.600 回答