outerRef与innerRef的offsetHeight对比异常问题咨询
问题分析与解决方法
核心问题1:Ref绑定逻辑错误
你把innerRef直接绑定在循环生成的每个<span>上,React中这种写法会导致this.innerRef.current只保留最后一个span的DOM引用,而非所有span的集合。这就导致你拿外层容器高度和最后一个span的高度对比,逻辑完全偏离预期。
核心问题2:代码语法错误
你的代码存在几处明显语法问题:
map回调写法错误,箭头函数返回JSX需用括号包裹,或加花括号配合return:// 正确写法1 {testList.map(({ item, index }) => ( <div key={index}> <span ref={this.innerRef}>{item.remark}</span> </div> ))} // 正确写法2 {testList.map(({ item, index }) => { return ( <div key={index}> <span ref={this.innerRef}>{item.remark}</span> </div> ); })}<span>标签未闭合,且{item.remark}未放在标签内部正确位置componentDidUpdate中的if语句缺少闭合的}
正确需求实现方案
如果你的目标是判断外层容器outerRef是否因内容过多出现溢出,根本不需要单独获取内部元素高度,直接用容器的scrollHeight和offsetHeight对比即可:
scrollHeight:容器内所有内容的总高度(含不可见部分)offsetHeight:容器的可见高度
修改后代码如下:
渲染部分
<div ref={this.outerRef}> {testList.map(({ item, index }) => ( <div key={index}> <span>{item.remark}</span> </div> ))} </div>
componentDidUpdate部分
componentDidUpdate() { const outer = this.outerRef.current; this.setState({ overflow: outer.scrollHeight > outer.offsetHeight }); }
若需获取所有内部span的总高度对比
可通过数组存储每个span的ref,再计算总高度:
// 初始化ref数组 constructor(props) { super(props); this.innerRefs = []; } // 渲染时收集每个span的ref <div ref={this.outerRef}> {testList.map(({ item, index }) => ( <div key={index}> <span ref={el => this.innerRefs[index] = el}>{item.remark}</span> </div> ))} </div> // 计算总高度并对比 componentDidUpdate() { const totalInnerHeight = this.innerRefs.reduce((sum, el) => sum + el.offsetHeight, 0); const outerHeight = this.outerRef.current.offsetHeight; this.setState({ overflow: totalInnerHeight > outerHeight }); }
内容的提问来源于stack exchange,提问作者Easy Money
相关产品推荐
相关产品推荐

