我的getBoundingClientRect总是返回一个包含0值的对象。我想是和异步有关吧?下面是获取组件宽度和x的函数的定义。
componentDidMount () {
this.setState({
left: Math.round(this.container.getBoundingClientRect().width),
x: Math.round(this.container.getBoundingClientRect().x)
});
}
以下是呈现函数的开始:
render() {
const containerStyle = {
left : `-${Math.min(this.state.left, this.state.x) - 35}px`,
};
return ( !!this.state.visible &&
<div
className={styles.container}
style={containerStyle}
ref={(element) => { this.container = element; }}
>
以下是来自getBoundingClientRect
的响应
DOMRect {x: 0, y: 0, width: 0, height: 0, top: 0, …}
bottom : 0
height : 0
left : 0
right : 0
top : 0
width : 0
x : 0
y : 0
发布于 2017-10-05 10:54:46
试一试
componentDidMount () {
window.requestAnimationFrame(() => {
this.setState({
left: Math.round(this.container.getBoundingClientRect().width),
x: Math.round(this.container.getBoundingClientRect().x)
});
}
}
DOM实际上是可用的,componentDidMount正在调用,这有一些微妙之处;使用requestAnimationFrame将确保它在油漆发生后被调用。
发布于 2017-10-05 10:31:35
您需要使用ref回调,而不是内联ref。当您使用内联ref时,第一个呈现传递该ref将为空。当传入回调时,它只在元素加载后触发。
applyRef(ref) {
this.container = ref;
}
...
<div
className={styles.container}
style={containerStyle}
ref={this.applyRef}
>
https://stackoverflow.com/questions/46591978
复制相似问题