programing

React Native: 요소의 위치 가져오기

mailnote 2023. 3. 17. 21:47
반응형

React Native: 요소의 위치 가져오기

스타일링하고 있어요Image플렉스 박스가 있는 컴포넌트는 화면 중앙에 배치되어 매우 잘 작동합니다.이제 좀 기다려줘Image첫 번째 컴포넌트 상단에 직접 표시됩니다.두 번째 이미지는 절대 위치를 사용하고 있습니다.현시점에서는 픽셀이 맞도록 추측하고 있습니다만, 물론 정확하지 않고 유지보수에 너무 많은 노력을 기울이고 있습니다.

jQuery의 리액트 네이티브와 동등한 제품을 찾고 있습니다..offset()그런 게 있나요? 만약 없다면 어떻게 하는 게 최선일까요?

React Native는 콜백을 받아 컴포넌트의 오프셋과 너비/높이로 호출하는 메서드를 제공합니다.

myComponent.measure( (fx, fy, width, height, px, py) => {

    console.log('Component width is: ' + width)
    console.log('Component height is: ' + height)
    console.log('X offset to frame: ' + fx)
    console.log('Y offset to frame: ' + fy)
    console.log('X offset to page: ' + px)
    console.log('Y offset to page: ' + py)
})

예...

다음은 사용자 정의 구성 요소가 렌더링된 후 레이아웃을 계산합니다.

class MyComponent extends React.Component {
    render() {
        return <View ref={view => { this.myComponent = view; }} />
    }
    componentDidMount() {
        // Print component dimensions to console
        this.myComponent.measure( (fx, fy, width, height, px, py) => {
            console.log('Component width is: ' + width)
            console.log('Component height is: ' + height)
            console.log('X offset to frame: ' + fx)
            console.log('Y offset to frame: ' + fy)
            console.log('X offset to page: ' + px)
            console.log('Y offset to page: ' + py)
        })        
    }
}

버그 노트

  • 컴포넌트가 렌더링 전에 완료되지 않는 경우가 있습니다.componentDidMount()호출됩니다.그 결과 0이 되는 경우measure(...), 그 후, 그것을 포장을 합니다.setTimeout문제를 해결할 필요가 있습니다.

    setTimeout( myComponent.measure(...), 0 )
    

를 사용하여 컴포넌트가 사용 가능한 가장 빠른 시점에 컴포넌트의 폭, 높이 및 부모에 대한 상대 위치를 가져올 수 있습니다.

<View
  onLayout={event => {
    const layout = event.nativeEvent.layout;
    console.log('height:', layout.height);
    console.log('width:', layout.width);
    console.log('x:', layout.x);
    console.log('y:', layout.y);
  }}
>

승인된 답변에 나타난 것과 같이 사용하는 것에 비해, 이 기능은 사용자가 시간을 낭비할 필요가 없다는 장점이 있습니다..measure()와의 통화setTimeout측정값을 사용할 수 있지만 전체 페이지를 기준으로 오프셋을 제공하지 않고 요소의 상위 페이지에만 오프셋을 제공한다는 단점이 있습니다.

나도 비슷한 문제가 있어서 위의 답을 조합해서 해결했다.

class FeedPost extends React.Component {
  constructor(props) {
    ...
    this.handleLayoutChange = this.handleLayoutChange.bind(this);
  }


handleLayoutChange() {
    this.feedPost.measure( (fx, fy, width, height, px, py) => {
      console.log('Component width is: ' + width)
      console.log('Component height is: ' + height)
      console.log('X offset to page: ' + px)
      console.log('Y offset to page: ' + py)
    })
  }

  render {
    return(
      <View onLayout={(event) => {this.handleLayoutChange(event) }} 
      ref={view => { this.feedPost = view; }} >
...

로그에서 feedPost 요소의 위치를 확인할 수 있습니다.

08-24 11:15:36.838  3727 27838 I ReactNativeJS: Component width is: 156
08-24 11:15:36.838  3727 27838 I ReactNativeJS: Component height is: 206
08-24 11:15:36.838  3727 27838 I ReactNativeJS: X offset to page: 188
08-24 11:15:36.838  3727 27838 I ReactNativeJS: Y offset to page: 870

ListView 내에서 요소의 위치를 찾아야 했고 다음과 같은 스니펫을 사용했습니다..offset:

const UIManager = require('NativeModules').UIManager;
const handle = React.findNodeHandle(this.refs.myElement);
UIManager.measureLayoutRelativeToParent(
  handle, 
  (e) => {console.error(e)}, 
  (x, y, w, h) => {
    console.log('offset', x, y, w, h);
  });

이 경우, 저는ref='myElement'내 컴포넌트에 있습니다.

기능 컴포넌트를 사용하고 있으며, 이를 사용하지 않는 경우forwardRef컴포넌트의 절대 레이아웃을 측정하려면LayoutChangeEvent에서onLayout콜백

이렇게 하면 요소의 절대 위치를 얻을 수 있습니다.

<MyFunctionComp
  onLayout={(event) => {
    event.target.measure(
      (x, y, width, height, pageX, pageY) => {
        doSomethingWithAbsolutePosition({
          x: x + pageX, 
          y: y + pageY,
        });
      },
    );
  }}
/>

React Native 0.63.3으로 테스트 완료.

이는 Ref를 사용하여 계산할 때 React Native의 최신 버전에서 변경된 것으로 보입니다.

참조를 이렇게 선언합니다.

  <View
    ref={(image) => {
    this._image = image
  }}>

그리고 이런 식으로 가치를 찾아보세요.

  _measure = () => {
    this._image._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)
    })
  }

ref 인수 오브젝트에는 다음과 같이 사용할 수 있는measureInWindow 속성이 있습니다.

const [offset, setOffset] = React.useState();

<View ref={(view) =>
    if(!view) return;
    view.measureInWindow((x, y) => {
        setOffset({ x, y });
    })
}>
</View>

언급URL : https://stackoverflow.com/questions/30096038/react-native-getting-the-position-of-an-element

반응형