我有一个父反应组件包含一个子反应组件.
<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所述的参考.
基本的问题是需要DOM节点(及其父DOM节点)才能正确定位元素,但直到第一次渲染才能使用.从上面链接的文章:
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)中进行状态更改.
原文地址:https://www.jb51.cc/js/155239.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。