如何在使用react时动态调整元素大小

How can I resize elements dynamically while using react?

本文关键字:调整 动态 元素 react      更新时间:2023-09-26

我有一个组件网格,每行3个。

它们是表示产品的div,具有价格和描述等内部组件。这些产品有时有较长的标题,这会将其他组件向下推。

这很好,但当发生这种情况时,我希望同一行中其他组件的标题具有相同的高度,以便下一个组件(价格、评级)垂直对齐。因此,一行中每种产品的价格都是相同的。

然后,我想使行的高度为该行中三个元素的最大高度。

有没有一种好的方法可以动态地操纵将与react一起工作的元素的高度?

我会在所有子组件中注入一个函数,该函数在子组件渲染后调用。

示例:

var Product = React.createClass({
  componentDidMount: function() {
    var height = 200; // calculate height of rendered component here!
    // set height only one time
    if (this.props.findHeight) {
        this.props.setHeight(height);
    }
  },
  render: function() {
    return <div style={{height:this.props.height,backgroundColor:'green'}}>
            Product
        </div>;
  }
});
var Main = React.createClass({
  getInitialState: function() {
    return {
      maxHeight:0,
      findHeight: true
    }
  },
  componentDidMount: function() {
    this.setState({
        maxHeight: this.state.maxHeight,
        findHeight: false
    });
  },
  setMaxHeight: function(maxHeight) {
    if (maxHeight > this.state.maxHeight) {
      this.setState({maxHeight: maxHeight})
    }
  },
  render: function() {
    return (<div>
             <Product setHeight={this.setMaxHeight} height={this.state.maxHeight} findHeight={this.state.findHeight} />
           </div>);
  }
});

如何计算组件的实际高度是另一个问题。你可以用jQuery(如何在px维度中获得<div>的高度)来解决这个问题。不幸的是,我不能回答香草js的问题,但我相信当你问谷歌时,你会很快找到答案:-)

问候

通过扩展CapCa提供的答案,您可以通过Element.getBoundingClientRect().获得组件的实际高度

let domRect = element.getBoundingClientRect();

你也可以通过使用react Ref.来瞄准你的目标react组件的顶部元素。你的代码可能是这样的,

let domRect = this.TargetedElementRef.getBoundingClientRect(),
    elementHeight = domRect.height,
    elementWidth = domRect.width;   // you can get the width also