我有一个react组件,需要提前知道它的尺寸,before it renders itself.
当我在jquery中制作一个小部件时,我只需要$('#container').width()
,就可以在构建组件时提前获得容器的宽度.
<div id='container'></div>
这些容器的维度在CSS中定义,以及页面上的一系列其他容器.谁定义React中组件的高度、宽度和位置?我已经习惯了这样做,并且能够访问它.但在React中,我似乎只能在组件渲染后才能访问这些信息.
我有一个react组件,需要提前知道它的尺寸,before it renders itself.
当我在jquery中制作一个小部件时,我只需要$('#container').width()
,就可以在构建组件时提前获得容器的宽度.
<div id='container'></div>
这些容器的维度在CSS中定义,以及页面上的一系列其他容器.谁定义React中组件的高度、宽度和位置?我已经习惯了这样做,并且能够访问它.但在React中,我似乎只能在组件渲染后才能访问这些信息.
正如前面已经提到的,在将任何元素呈现到DOM之前,您无法获得该元素的维度.在Reaction中可以做的是只呈现一个容器元素,然后获取它的大小(单位为componentDidMount
),然后呈现内容的睡觉.
我得了working example分.
请注意,在componentDidMount
中使用setState
是一种反模式,但在本例中是可以的,因为这正是我们要实现的目标.
干杯
代码:
import React, { Component } from 'react';
export default class Example extends Component {
state = {
dimensions: null,
};
componentDidMount() {
this.setState({
dimensions: {
width: this.container.offsetWidth,
height: this.container.offsetHeight,
},
});
}
renderContent() {
const { dimensions } = this.state;
return (
<div>
width: {dimensions.width}
<br />
height: {dimensions.height}
</div>
);
}
render() {
const { dimensions } = this.state;
return (
<div className="Hello" ref={el => (this.container = el)}>
{dimensions && this.renderContent()}
</div>
);
}
}