Nice programing

React Native : 요소의 위치 얻기

nicepro 2021. 1. 5. 21:13
반응형

React Native : 요소의 위치 얻기


Image꽤 잘 작동하는 화면 중앙에 플렉스 박스를 사용 하여 구성 요소를 스타일링하고 있습니다. 이제 첫 번째 Image구성 요소의 맨 위에 두 번째 구성 요소를 직접 표시 하고 싶습니다 . 두 번째 이미지는 절대 위치 지정을 사용합니다. 현재 나는 픽셀이 맞도록 추측하고 있지만 물론 이것은 정확하지 않고 유지 관리 노력이 너무 많습니다.

나는 jQuery의 .offset(). 그런 일이 있고 이것을 달성하는 가장 좋은 방법은 무엇입니까?


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

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을 얻는 경우 a measure(...)로 래핑 setTimeout하면 문제가 해결됩니다. 즉,

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

를 사용 onLayout하여 구성 요소를 사용할 수있는 가장 빠른 순간에 구성 요소 의 너비, 높이 및 상대적인 상위 위치 를 가져올 수 있습니다.

<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()것과 비교 하면 측정 값을 사용할 수 있는지 확인하기 위해 .measure()호출을 연기 할 setTimeout필요가 없다는 장점이 있지만, 상대적으로 오프셋을 제공하지 않는다는 단점이 있습니다. 전체 페이지, 요소의 부모와 관련된 페이지 만.


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'내 구성 요소를 가지고 있다고 가정합니다 .


비슷한 문제가 있었고 위의 답변을 결합하여 해결했습니다.

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

refs를 사용하여 계산할 때 최신 버전의 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)
    })
  }

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

반응형