Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

What is the React way to accomplish this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
448 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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:

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.

Here is the solution:

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

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...