【问题标题】:How to position a React component relative to its parent?如何相对于其父组件定位 React 组件?
【发布时间】:2016-04-12 03:39:31
【问题描述】:

我有一个包含子 React 组件的父 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>;
}

我不能在这里使用百分比值,因为顶部和左侧位置是子级和父级宽度和高度的函数。

React 的实现方式是什么?

【问题讨论】:

  • ????使用我强烈推荐react-popper
  • @Seth 你能澄清一下“因为顶部和左侧位置是孩子和父母的宽度和高度的函数”吗?你到底想达到什么目的?

标签: javascript css dom reactjs


【解决方案1】:

这个问题的答案是使用Refs to Components 中描述的引用。

潜在的问题是需要 DOM 节点(及其父 DOM 节点)来正确定位元素,但直到第一次渲染后才可用。来自上面链接的文章:

执行 DOM 测量几乎总是需要访问“本机”组件并使用 ref 访问其底层 DOM 节点。 Refs 是可靠地做到这一点的唯一实用方法之一。

解决办法如下:

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>;
}

这将在第一次渲染后立即正确定位元素。如果您还需要在更改 props 后重新定位元素,则在 componentWillReceiveProps(nextProps) 中进行状态更改。

【讨论】:

  • computeTopWithcomputeLeftWith 是反应函数吗?我需要导入它们吗?
  • @SimonH compute... 函数只是占位符;你需要提供逻辑。
  • @Seth - 你应该在评论中声明它们是 占位符,这是误导。
  • 你能完成答案吗?
【解决方案2】:

我就是这样做的

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>

【讨论】:

    【解决方案3】:

    正确的做法是使用 CSS。如果将position:relative 应用于父元素,则可以使用topleft 相对于该父元素移动子元素。您甚至可以使用百分比,例如 top:50%,它利用父元素的高度。

    【讨论】:

    • 我不能使用百分比;我更新了问题以澄清这一点。
    • @Seth 您是否尝试将position: relative 应用于父母?
    • 即使它是相对的,在您有多层嵌套元素的情况下,父元素也可能具有不同的高度。
    猜你喜欢
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2023-04-09
    • 2021-02-15
    • 2021-12-25
    相关资源
    最近更新 更多