【发布时间】:2021-03-06 17:19:43
【问题描述】:
我在使用 React.createRef() 获取子组件中元素的高度时遇到了困难。
困难仅在于使用地图创建的三个子组件中的第一个。
子组件显示为实际票证(见下文)。
左边和右边是不同的div。
如果用户提交的票证名称较长且占用的空间多于一行中的可用空间,则票证标题(“早起的鸟”等)的(红色)背景颜色将具有更大的高度。
我希望票证右侧的红色 div 的高度与左侧包含票证标题的 h1 的高度相匹配。
我正在使用 React.createRef() 来查找 h1 的高度,并通过内联样式将其应用于右侧的 div。
这适用于第二张和第三张票,但不适用于第一张票。
//父组件
{this.state.userEvent.tickets
.map((e, i) => {
return (
<div key={i}>
<ColmTicket
ticketType={e.ticketType}
description={e.ticketDescription}
price={e.price}
refunds={e.refunds}
chargeForNoShows={e.chargeForNoShows}
hold={e.hold}
quantity={e.buy.numTicketsSought}
changeQuantity={this.changeQuantity}
i={i}
/>
</div>
);
})}
//Child Component
class ColmTicket extends React.Component {
constructor(props) {
super(props);
this.state = {
height: 0,
};
this.containerRef = React.createRef();
}
componentDidMount() {
const { offsetHeight } = this.containerRef.current;
this.setState({
height: offsetHeight,
});
}
render() {
return (
<div>
<h1 ref={this.containerRef}>
{this.props.ticketType}
</h1>
<div className="event-eye" style={{ height: this.state.height }}></div>
</div>
);
}
}
我也在 componentDidMount 中运行 console.logs。第一张票 - 有问题的票 - 在控制台记录时不显示给出票名的道具(下面的第 17 行)。其他两张票在 console.logged 时确实提供了这个道具。
这让人相信,对于第一个组件,调用componentDidMount时prop还没有被渲染?这可能吗?如果可以,我可以解决它吗?
// Console Log results
ColmTicket.js:17
ColmTicket.js:18 this.containerRef {current: h1.event-ticket-title}
ColmTicket.js:19 this.containerRef.current <h1 class="event-ticket-title">…</h1>
ColmTicket.js:22 offsetHeight 20
ColmTicket.js:23 ---------
ColmTicket.js:17 General Admission
ColmTicket.js:18 this.containerRef {current: h1.event-ticket-title}
ColmTicket.js:19 this.containerRef.current <h1 class="event-ticket-title">…</h1>
ColmTicket.js:22 offsetHeight 48
ColmTicket.js:23 ---------
ColmTicket.js:17 Skip The Queue
ColmTicket.js:18 this.containerRef {current: h1.event-ticket-title}
ColmTicket.js:19 this.containerRef.current <h1 class="event-ticket-title">…</h1>
ColmTicket.js:22 offsetHeight 48
ColmTicket.js:23
【问题讨论】:
标签: reactjs components react-props