如何相对于其父级定位React组件? [英] How to position a React component relative to its parent?

查看:249
本文介绍了如何相对于其父级定位React组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含子React组件的父React组件。

I have a parent React component that contains a child React component.

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

我需要将样式应用于子组件以将其定位在其父组件中,但其位置取决于父母的大小。

I need to apply styles to the child component to position it within its parent, but its position depends on the size of the parent.

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

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

I can't use percentage values here, because the top and left positions are functions of the child and parent's widths and heights.

React的方法是什么?

What is the React way to accomplish this?

推荐答案

这个问题的答案是使用上描述的引用参考组件

The answer to this question is to use a ref as described on Refs to Components.

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

The underlying problem is that the DOM node (and its parent DOM node) is needed to properly position the element, but it's not available until after the first render. From the article linked above:


执行DOM测量几乎总是需要联系本机组件并使用a访问其底层DOM节点REF。 Refs是可靠的唯一实用方法之一。

Performing DOM measurements almost always requires reaching out to a "native" component and accessing its underlying DOM node using a ref. Refs are one of the only practical ways of doing this reliably.

以下是解决方案:

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

componentDidMount() {
  this.setState({
    styles: {
      top: computeTopWith(this.refs.child),
      left: computeLeftWith(this.refs.child)
    }
  })
},

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

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

This will properly position the element immediately after the first render. If you also need to reposition the element after a change to props, then make the state change in componentWillReceiveProps(nextProps).

这篇关于如何相对于其父级定位React组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆