gpt4 book ai didi

javascript - 如何在使用 React 时动态调整元素大小?

转载 作者:行者123 更新时间:2023-11-30 16:08:18 25 4
gpt4 key购买 nike

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

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

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

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

有什么好方法可以动态地操纵元素的高度,这将与 React 一起工作?

最佳答案

我会在所有子组件中注入(inject)一个函数,该函数在子组件呈现后调用。

示例:

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(How to get height of <div> in px dimension)。不幸的是我无法回答 vanilla js 的问题,但我相信当你问谷歌时你会很快找到答案:-)

问候

关于javascript - 如何在使用 React 时动态调整元素大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36676604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com