【问题标题】:Get the coordinates of <View> when using flex使用flex时获取<View>的坐标
【发布时间】:2019-02-21 10:39:44
【问题描述】:

我正在关注this tutorial 创建多个带有拖放区的拖放对象。

放置区只是水平填充屏幕的一定高度

export default class Screen extends Component {
  render() {
    return (
      <View style={styles.mainContainer}>
        <View style={styles.dropZone}>
          <Text style={styles.text}>Drop them here!</Text>
        </View>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  mainContainer: {
    flex: 1
  },
  row: {
    flexDirection: "row"
  },  
  dropZone: {
    height: 200,
    backgroundColor: "#00334d"
  }
}

然后检查我们是否在放置区域内释放了可拖动对象的代码非常简单,只需检查 y 坐标是否高于某个值。

isDropArea(gesture) {
  return gesture.moveY < 200;
}

这很简单,它将 200 值硬编码在样式定义和检查我们是否在放置区域的函数中。

我想做的是创建一个 2x2 拖放区数组。为此,我将它们放在一定高度的View 中,并使用 flex 按行和按列扩展每个放置区。我将每个 dropZone 定义为 30x30,并使用“space-around”来对齐内容。

<View style={styles.mainContainer}>
  <View style={styles.col}>
    <View style={styles.row}>
      <View style={styles.dropZone} />
      <View style={styles.dropZone} />
    </View>
    <View style={styles.row}>
      <View style={styles.dropZone} />
      <View style={styles.dropZone} />
    </View>
  </View>
</View>


const styles = StyleSheet.create({
  mainContainer: {
    flex: 1
  },
  row: {
    flexDirection: "row",
    justifyContent: 'space-around'
  },  
  col: {
    height: 500,
    flexDirection: "column",
    justifyContent: 'space-around'
  },  
  dropZone: {
    height: 30,
    width: 30,
    flexDirection: "row",
    backgroundColor: "#00334d"
  }
})

好的,现在是问题。通过使用 flex,我没有指定每个放置区域的坐标,而是让渲染来完成。 我可以做一些数学运算并通过获取屏幕的分辨率并知道我有多少拖放区及其大小来计算这些坐标。

但是,有没有办法检索此 DropZones 的位置,以便我可以创建一个函数 getDropZoneIndex 来返回我将可拖动对象放入哪个放置区域?

【问题讨论】:

    标签: react-native flexbox drag-and-drop


    【解决方案1】:

    是的,您可以在 React Native 中获取任何视图的坐标。有一个 onLayout() 道具可以让你做到这一点:

    render() {
      return (<View onLayout={this.onLayout}/>);
    }
    
    onLayout = (event) => {
      const {x, y, width, height} = event.nativeEvent.layout;
    }
    

    如果我没记错的话,这个布局对象的 x 和 y 坐标是相对于父组件的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 2010-12-19
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多