我有一个父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的实现方式是什么?
该问题的答案是使用Refs to Components中描述的ref 。
潜在的问题是需要DOM节点(及其父DOM节点)来正确放置元素,但是直到第一次渲染后该元素才可用。从上面链接的文章中:
执行DOM测量几乎总是需要接触“本机”组件并使用ref访问其基础DOM节点。引用是可靠地做到这一点的唯一实用方法之一。
解决方法如下:
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)。
componentWillReceiveProps(nextProps)