如何在视图中使用event.nativeEvent.layout计算位置

时间:2017-01-12 14:15:25

标签: react-native

我正在尝试拖放组件,为此我需要dropZone的x和y位置。一切都很好,但是当我试图获得区域和我的dropzone的位置时,如果在视图内反应本机给我一个基于视图的值,我能以某种方式知道根位置。

  

whit onLayout我参加活动

<View style={styles.borderView}>
  <Text style={styles.text}>
    after he had dug down only a few inches he uncovered a 
    <View
      onLayout={this.setDropZoneValues.bind(this)}
      style={styles.viewDropZone}
    >
      <Text>_________</Text>
    </View>
    of silver coins and jewelry. He couldn’t believe it
  </Text>
</View>
  

这里我拿区域,y和x

setDropZoneValues(event) {
        this.props.setDropZoneValue(event.nativeEvent.layout);
}
  

样式

viewDropZone: {
    backgroundColor:'red',
    height: 10,
    width: 60
},
text: {
    backgroundColor: theme.colors.transparent,
    textAlign: 'left',
},
borderView: {
    backgroundColor: theme.colors.colomboGrayBackground,
    marginTop: 5,
    margin: 8,
    padding: 10,
    borderStyle: 'dashed',
    borderWidth: 1.5,
    borderRadius: 2,
    borderColor: theme.colors.colomboSubTitle,
},

感谢

1 个答案:

答案 0 :(得分:0)

这就是我处理这个问题的方法

我在父视图和Son视图中都使用了onLayaut,在父级中我将值保存在状态中,当我在子视图中计算位置时,我在我的视图中将parentPosition添加到我的postionValue。

一些代码:

  

    renderSection(seccion, key) {
    return (
        <View onLayout={(event) => this.props.setSeccionOffset(event.nativeEvent.layout.y, seccion.id)} style={styles.mainContainer} key={key}>
            <Text numberOfLines={1} style={styles.title} >{seccion.title}</Text>
            {seccion.questions.map((dropZones, idx) => {
                return this.renderDropZones(dropZones, idx, seccion.id)
            })}
        </View>
    )
}
  

    renderDropZones(seccion, idx, parentId) {
    return (
        <View onLayout={(event) => this.setDropZoneValues(event, seccion, parentId)} style={styles.leftField} key={idx}>
            <Text style={styles.LabelTittle} numberOfLines={1}> {seccion.text} <Text style={[styles.LabelTittle, { color: this.setColor() }]}>{seccion.selectedBy}</Text></Text>
        </View>
    );
}
  

在这里,我计算了基于他父母的观点位置和基于屏幕的父位置

    setDropZoneValues(event, seccion, parentId) {
    let dropZone = event.nativeEvent.layout;
    setTimeout(
        () => {
            dropZone.id = seccion.index;
            dropZone.y += this.props.multiDragStore.seccions[parentId].offsetContainer;
            this.props.setDropZoneValue(dropZone);
        },
        10,
        dropZone
    );
}

setTimeOut是因为onlayout是一个回调,我需要在计算儿子位置之前验证他父母的偏移是否已定义