【问题标题】:react-bootstrap-table: How to programmatically set the height of a BootstrapTable element?react-bootstrap-table:如何以编程方式设置 BootstrapTable 元素的高度?
【发布时间】:2017-05-11 14:00:21
【问题描述】:

我需要以编程方式设置BootstrapTable 元素的高度(因为我想确保表格占据浏览器窗口底部的可用空间)。我尝试使用 CSS 类 react-bs-table 设置 div 的 CSS 属性 height(如果我在 BootstrapTable 元素的 height 属性中设置它,这就是高度的位置)。看起来像这样:

componentDidMount() {
   // Calculate the height
   let height = 200; // Only simluated here!

   // Set the height
   const tableElement = document.getElementsByClassName('react-bs-table')[0];
   tableElement.style.height = height + 'px';
}

这种方法的问题是BootstrapTable 的数据行溢出了它的底部边框。似乎这个溢出的高度就是标题的高度。

Fiddle

如何正确设置BootstrapTable 的高度(数据行不会溢出元素)?

【问题讨论】:

    标签: reactjs react-bootstrap-table


    【解决方案1】:

    您应该使用<BootstrapTable>maxHeight 属性(not height)来设置高度,而不是修改 DOM 元素。

    看看official docs

    使用maxHeight 设置表格的最大高度。您需要提供一个带有单位(px)值的字符串,例如height:

    只需进行以下更改:

    componentDidMount() {
      let height = 200;
      this.setState({tableHeight: height + "px"});
    }
    
    render() {
      ...
      <BootstrapTable maxHeight={this.state.tableHeight} id="table" data={this.state.products} striped hover>
      ...
    }
    

    您可能还想在构造函数中初始化this.state.tableHeight...

    jsfiddle


    如果您仍然想以您的方式更新样式,直接通过 DOM 而不是使用 React(尽管不鼓励),您可以这样做:

    componentDidMount() {
      let height = 200;
      const tableElement = document.getElementsByClassName('react-bs-container-body')[0];
      tableElement.style.maxHeight = height + 'px';
    }
    

    请注意,我使用的是react-bs-container-body,而不是react-bs-table

    jsfiddle

    【讨论】:

    • React 解决方案完美运行。我只是不知何故没有想到将高度或 maxHeight 绑定到状态属性。无论如何,我使用了高度,因为我想让表格始终到达页面底部(减去带有按钮的页脚)。
    • 太棒了!很高兴我能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 2016-10-27
    • 2013-12-15
    相关资源
    最近更新 更多