如何在页面的特定坐标处呈现视图?

Kis*_*ore 1 react-native

当屏幕被触摸并保持在某个位置时,我想View准确地渲染屏幕被触摸的位置(如android中的上下文菜单)。我有页面坐标pageXpageY,我想View根据这些坐标渲染一个。

有没有办法在 Style 对象中给出这些坐标,如下所示,

<View style={{X: 120, Y: 75}} />
Run Code Online (Sandbox Code Playgroud)

den*_*emm 5

与常规 CSS 不同,react-native 不支持position: fixed手动将视图定位在相对于视口的某个位置。但是您可以使用父组件position: 'absolute'onLayout方法和方法。我将尝试澄清:

第1步:

假设您有一个父视图,它正好是屏幕的宽度和高度,那么您可以像这样轻松定位视图:

<View> // this parent view has the same dimensions as the screen
  // Below is the view you want to position according your x, y coordinates
  <View 
    style={{
      position: 'absolute',
      left: this.state.x,
      top: this.state.y
    }}>
  </View>
</View>
Run Code Online (Sandbox Code Playgroud)

第 2 步(可选):

您拥有的触摸坐标是屏幕坐标,因此如果您的视图与屏幕的大小不完全相同,则步骤 1 是不够的。但是 react-native 提供了一个measureInWindow()(通过组件的 ref 可用)回调来确定组件的屏幕坐标。

所以基本上你measureInWindow()在发生触摸时调用父视图来确定父窗口的 x 和 y 偏移量,并考虑这个偏移量来计算正确的 x 和 y 值。