IT이야기

리액션 구성 요소를 부모 구성 요소와 비교하여 배치하는 방법?

cyworld 2022. 4. 1. 21:09
반응형

리액션 구성 요소를 부모 구성 요소와 비교하여 배치하는 방법?

나는 Child React 구성 요소를 포함하는 부모 반응 구성 요소를 가지고 있다.

<div>
  <div>Child</div>
</div>

부모 안에서 위치를 정하기 위해 자식 구성요소에 스타일을 적용해야 하지만, 부모의 크기에 따라 위치가 달라진다.

render() {
  const styles = {
    position: 'absolute',
    top: top(),    // computed based on child and parent's height
    left: left()   // computed based on child and parent's width
  };
  return <div style={styles}>Child</div>;
}

나는 여기서 백분율 값을 사용할 수 없다. 왜냐하면 위와 왼쪽 위치는 아이의 기능이고 부모의 폭과 높이에 대한 기능이기 때문이다.

이를 달성하기 위한 리액션 방법은 무엇인가?

이 질문에 대한 답은 Refs to Components에 설명된 대로 ref를 사용하는 것이다.

기본적인 문제는 요소를 적절히 배치하기 위해 DOM 노드(및 그 상위 DOM 노드)가 필요하지만 첫 번째 렌더링 이후에나 사용할 수 있다는 것이다.위에 링크된 기사에서:

DOM 측정을 수행하려면 거의 항상 "원래" 구성요소에 접근하고 ref를 사용하여 기본 DOM 노드에 액세스해야 한다.ref는 이것을 신뢰성 있게 하기 위한 유일한 실용적인 방법들 중 하나이다.

해결책은 다음과 같다.

getInitialState() {
  return {
    styles: {
      top: 0,
      left: 0
    }
  };
},

componentDidMount() {
  this.setState({
    styles: {
      // Note: computeTopWith and computeLeftWith are placeholders. You
      // need to provide their implementation.
      top: computeTopWith(this.refs.child),
      left: computeLeftWith(this.refs.child)
    }
  })
},

render() {
  return <div ref="child" style={this.state.styles}>Child</div>;
}

이렇게 하면 첫 번째 렌더 직후에 요소가 적절하게 배치된다.소품 변경 후 요소의 위치를 변경해야 하는 경우 다음 위치에서 상태를 변경하십시오.componentWillReceiveProps(nextProps).

이렇게 했다.

const parentRef = useRef(null)

const handleMouseOver = e => {
    const parent = parentRef.current.getBoundingClientRect()
    const rect = e.target.getBoundingClientRect()

    const width = rect.width
    const position = rect.left - parent.left

    console.log(`width: ${width}, position: ${position}`)
}

<div ref={parentRef}>
    {[...Array(4)].map((_, i) => <a key={i} onMouseOver={handleMouseOver}>{`Item #${i + 1}`}</a>)}
</div>

이를 위한 올바른 방법은 CSS를 사용하는 것이다.신청하면position:relative상위 요소로 이동하면 하위 요소는 다음을 사용하여 이동할 수 있다.top, 그리고left그 부모에 관해서 말이야심지어 백분율 같은 것도 사용할 수 있다.top:50%, 상위 요소의 높이를 활용한다.

참조URL: https://stackoverflow.com/questions/34660385/how-to-position-a-react-component-relative-to-its-parent

반응형