当前位置: 移动技术网 > IT编程>开发语言>JavaScript > React组件自适应窗口宽高

React组件自适应窗口宽高

2019年06月20日  | 移动技术网IT编程  | 我要评论

很多时候我们需要组件能够根据窗口变化改变宽高:

比如说,当我们引用一个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,否则,它是元素内部的高度(单位像素),包含内边距,但不包括水平滚动条、边框和外边距。

react生命周期

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网