Set*_*eth 23 javascript css dom reactjs
我有一个包含子React组件的父React组件.
<div>
<div>Child</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我需要将样式应用于子组件以将其定位在其父组件中,但其位置取决于父组件的大小.
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>;
}
Run Code Online (Sandbox Code Playgroud)
我不能在这里使用百分比值,因为顶部和左侧位置是孩子和父母的宽度和高度的函数.
React的方法是什么?
Set*_*eth 18
这个问题的答案是使用refs to Components上描述的ref .
根本问题是需要DOM节点(及其父DOM节点)才能正确定位元素,但在第一次渲染之后它才可用.从上面链接的文章:
执行DOM测量几乎总是需要使用ref来访问"本机"组件并访问其底层DOM节点.参考是可靠地实现这一目标的唯一实用方法之一.
这是解决方案:
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>;
}
Run Code Online (Sandbox Code Playgroud)
这将在第一次渲染后立即正确定位元素.如果您还需要在更改道具后重新定位元素,则进行状态更改componentWillReceiveProps(nextProps)
.
我就是这样做的
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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
41920 次 |
最近记录: |