React組件自適應窗口寬高


很多時候我們需要組件能夠根據窗口變化改變寬高,有時候可以使用css,有時候需要隨數據調整則使用js計算。

比如說,當我們在頁面中放置一個iframe時,我們希望它的寬高隨着其父元素or窗口的變化而變化;

再比如說,當我們引用一個ant Table組件,並且動態傳入columns及dataSource時,由於需要控制sroll值我們需要獲得動態的width和height;

......

下面我們舉幾個栗子

 例1:使用antd layout布局,如下圖,content寬高會隨着窗口變化,我們希望iframe-component組件也隨之變化,以至於iframe高度超出時iframe顯示滾動條,該怎么寫呢?

我們知道layout是flex布局,所以即使我們用下面的css也不能實現需求,因為content沒有寬高,他的子元素使用height:100%起不到作用。

.iframe-component{
  width:100%;
  height:100%;  
}

.iframe{
  width:100%;
  height:calc(100% - 30px);  
}

怎么辦呢?我們可以使用vh單位給iframe-component設置寬高。這樣iframe-component的高度就永遠等於窗口的高度減去header的高度了

.iframe-component{
  width:100%;
  height:calc(100vh - 64px);  
}

.iframe{
  width:100%;
  height:calc(100% - 30px);  
}

解釋:

單位vh :1vh等於視口高度的1%

 

例2:antd Table組件的scroll屬性用來設置橫向或縱向滾動,也可用於指定滾動區域的寬高,可以設置為像素值,百分比,true和‘max-content’。

現在需要實現一個Table,希望它布滿整個父div,父div隨窗口變化大小;當父div高度小於Table總高度時Table顯示縱滾動條;父div寬度小於Table總寬度時Table顯示橫滾動條,另外他的列是動態生成,即列數及寬度不定

import {Table} from 'antd';
class MyTable extends React.Component { constructor(props) { super(props); this.state = { width: 0, height: 1000, } this.myRef=React.createRef(); }    componentWillMount() { this.widthReset(this.props.columns) } componentDidMount() { this.handleResize(); window.addEventListener('resize', this.handleResize); } componentWillUnmount() { window.removeEventListener('resize', this.handleResize); }   
 //取父div的height handleResize() { const divHeight = this.myRef.current.clientHeight; divHeight!=null && this.setState({height:divHeight}) }
   componentWillReceiveProps(props){ this.widthReset(props.columns) } widthReset=(columns)=>{ let width=0; columns.forEach((record)=>{ width+=record.width; });
   this.setState({width}) } render() { return ( <div className="table-div" > <Table
       columns={this.props.columns}
       dataSource={this.props.dataSource}
       style={{height:this.state.height}}
       scroll={ { x: this.state.width, y: (this.state.height-this.columnHeight) } }
     /> </div> ); } } ReactDOM.render( <MyTable columns={columns} dataSource={dataSource}/>, document.getElementById('root') );

相關解釋:

React的ref :可以將ref綁定到 render() 輸出的任何組件上,來獲取相應的支撐實例。

Element.clientHeight :這個屬性是只讀屬性,對於沒有定義CSS或者內聯布局盒子的元素為0,否則,它是元素內部的高度(單位像素),包含內邊距,但不包括水平滾動條、邊框和外邊距。

React生命周期

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM