很多时候我们需要组件能够根据窗口变化改变宽高:
比如说,当我们引用一个ant Table组件,并且动态传入columns及dataSource时,由于需要控制sroll值我们需要获得动态的width和height;
再比如说,当我们在页面中放置一个iframe时,我们希望它的宽高随着其父元素or窗口的变化而变化,width我们可以用css{width:100%},但是height就需要我们动态获取;
......
下面举例一个如何自己封装一个Table组件,它可以根据columns变化scroll-x,根据视口的大小改变height及scroll-y
class MyTable extends React.Component { constructor(props) { super(props); this.state = { width: 0, height: 1000, } this.myRef=React.createRef(); } componentWillMount() { this.widthReset(this.props) } componentDidMount() { this.handleResize(); window.addEventListener(‘resize‘, this.handleResize); } componentWillUnmount() { window.removeEventListener(‘resize‘, this.handleResize); } handleResize() { const divHeight = this.myRef.current.clientHeight; divHeight!=null && this.setState({height:divHeight}) } componentWillReceiveProps(props){ this.widthReset(props) } widthReset=(props)=>{ let width=0; props.columns.forEach((record)=>{ width+=record.width; });
this.setState({width}) } render() { return ( <div className="table-div"> {`${this.state.width} x ${this.state.height}`} <div className="table" style={ { width: this.state.width, height: this.state.height } }></div> </div> ); } } ReactDOM.render( <MyTable columns={columns}/>, document.getElementById(‘root‘) );
以下为相关解释:
React的ref :可以将ref绑定到 render() 输出的任何组件上,来获取相应的支撑实例。
Element.clientHeight :这个属性是只读属性,对于没有定义CSS或者内联布局盒子的元素为0,否则,它是元素内部的高度(单位像素),包含内边距,但不包括水平滚动条、边框和外边距。
原文:https://www.cnblogs.com/JerryD/p/11052741.html