我从此答案中找到了跟踪页面大小的代码段。我想用$("#list_container").height
切换window.innerHeight
:
constructor(props) {
super(props);
this.state = { width: 0, height: 0 };
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
}
componentDidMount() {
this.updateWindowDimensions();
window.addEventListener('resize', this.updateWindowDimensions);
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateWindowDimensions);
}
updateWindowDimensions() {
// !!! This works:
this.setState({ width: window.innerWidth, height: window.innerHeight });
// !!! This doesn't work:
this.setState({ width: $("#list_container").width(), height: $("#list_container").height() });
}
编辑:已更新为 .width()
和 .height()
,但都尝试过,但都不对我有用。
列表容器在与外部div的模块中定义:
render() {
return (
<div id="list_container">
<ListGroup>
<VirtualList
width='100%'
height={this.state.height}
itemCount={this.state.networks.length}
itemSize={50}
renderItem={({index, style}) =>
<ListGroupItem
onClick={() => this.updateNetwork(this.state.networks[index].ssid, this.state.networks[index].security)}
action>
{this.state.networks[index].ssid}
</ListGroupItem>
}
/>
</ListGroup>
<Modal/>
// ...
注意:
如果我这样做:
<p>{this.state.height}</p>
它不是0
只是空的,示例不起作用。
如果您使用的是jQuery,则width()
和height()
是函数,而不是属性。尝试:
this.setState({ width: $("#list_container").width(), height: $("#list_container").height() });
您需要使用REFS,因为JS可能在组件渲染到DOM之前运行。
Ref Refs React文档
render() {
return (
<div id="list_container" ref={ el => this.componentName = el }>
// ...
要在此组件中引用此DOM节点,您只需要调用this.componentname
updateWindowDimensions = () => {
$(this.componentName).height() // returns height
}
使用refs在ERIC上进行扩展,在没有jQuery的情况下将其拉开,您可以使用getBoundingClientRect:
const listRect = document.getElementById('list_container').getBoundingClientRect();
或使用ERIC的参考答案:
const listRect = this.componentName.getBoundingClientRect();
接着
this.setState({
width: listRect.width,
height: listRect.height
});
我建议这个页面,以便在没有jQuery的情况下进行一些很好的生活例子。
另外,我强烈建议拒绝调整大小处理程序。