如何在屏幕上获取组件的位置以反应原生?

时间:2017-11-24 10:31:54

标签: javascript react-native

我正在开发一个本机应用程序,我想在屏幕上处理触摸。

一个用例是用户"按"在屏幕上,我希望能够获得屏幕上特定组件的位置(x,y),以确定它是否与触摸的(x,y)匹配。

我已经搜索了堆栈溢出,但是没有一个给定的解决方案有效......

在我的根组件中:

_onPress = () => {
    // How can I get the position of my component ?
    this._myComponent.xxx();
};

render() {
    return (
        <View><MyComponent ref={(r) => this._myComponent = r;} /></View>
    );
}

修改 在尝试此解决方案(React Native: Getting the position of an element)后,我按照以下方式工作:

在MyComponent.js中:

getPosition () => {
    this._ref._component.measure((width, height, px, py, fx, fy) => {
        const location = {
            fx: fx,
            fy: fy,
            px: px,
            py: py,
            width: width,
            height: height
        }
        console.log(location)
    });
};

render() {
    return (
        <View ref={(r) => { this._ref = r;} } />
    );
}

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

在React Native中使用useRef的功能组件中的示例:

const BoardSquare = props => {
  const squareRef = useRef(null);

  console.log('squareRef', squareRef);

  const doMeasure = square => {
    squareRef.current.measure((width, height, px, py, fx, fy) => {
      const location = {
        fx: fx,
        fy: fy,
        px: px,
        py: py,
        width: width,
        height: height,
      };
      console.log('location', location);
      square.x = fx;
      square.y = fy;
      square.xMax = fx + px;
      square.yMax = fy + py;
    });
  };

  return (
    <Square
      {...props}
      ref={squareRef}
      filled={props.square.filled}
      onLayout={() => doMeasure(props.square)}
    />
  );
};

答案 1 :(得分:0)

另一种选择是使用 onLayout。示例

const [viewHeight, setViewHeight] = React.useState(0);
return (
  <View
    onLayout={e => {
      e.persist();
      setViewHeight(e && e.nativeEvent ? e.nativeEvent.layout.height : 0);
    }}
  />
);

A more in-depth example

Documentation of LayoutEvent

相关问题