ReactJS中JSX内函数未返回元素:表格无法生成额外行
React表格额外行代码未执行的原因及修复方案
嘿,我仔细看了你的代码,问题其实很直观:你写的那段生成额外空行的代码,只是定义了一个函数,但从来没调用它,React自然不会执行里面的逻辑,更不会渲染出空行。
具体问题出在哪?
你在<tbody>里放了两段代码:
results.map(...):这部分是对的,map会返回一个元素数组,React会正常渲染这些<tr>。{ () => { ... } }:这是一个匿名函数表达式,React遇到这种情况时,只会把它当作一个普通的JS值,不会主动执行它。就像你在JS里写了function() { console.log('hi') }但从来没加()调用一样,这段代码完全不会运行。
而且还有个小坑:就算你执行了这个函数,原来的代码在for循环里直接return,这样只会生成第一行空行就停止了,根本生成不了diff数量的空行。
修复方案
我给你两种可行的修复方式,选哪种都可以:
方式1:用立即执行函数(IIFE)
把那段函数改成立即执行的形式,同时把空行收集到数组里再返回:
{ (() => { console.log(this.props.rowsCount > results.length); if (this.props.rowsCount > results.length) { const diff = this.props.rowsCount - results.length; const extraRows = []; for (let m = 0; m < diff; m++) { let rowNodes = []; rowNodes.push(<td className="hidden"></td>); if (this.props.gridNumber === 1) { rowNodes.push(<td className="in-td-item"></td>); } else { rowNodes.push(<td className="in-td-item hidden"></td>); } for (let n = 0; n < 24; n++) { rowNodes.push(<td className="in-td"></td>); } if (this.props.gridNumber === this.props.totalGrids) { rowNodes.push(<td className="in-td-addcolumn in-td"></td>); } // 给每个空行加唯一key,避免React警告 extraRows.push(<tr key={`empty-row-${m}`}>{rowNodes}</tr>); } return extraRows; } return null; })() }
方式2:直接用数组map(更简洁)
其实没必要包裹函数,直接用Array.from生成对应长度的数组,再用map渲染空行,代码更清爽:
{ this.props.rowsCount > results.length ? ( Array.from({ length: this.props.rowsCount - results.length }).map((_, index) => { let rowNodes = []; rowNodes.push(<td className="hidden"></td>); if (this.props.gridNumber === 1) { rowNodes.push(<td className="in-td-item"></td>); } else { rowNodes.push(<td className="in-td-item hidden"></td>); } for (let n = 0; n < 24; n++) { rowNodes.push(<td className="in-td"></td>); } if (this.props.gridNumber === this.props.totalGrids) { rowNodes.push(<td className="in-td-addcolumn in-td"></td>); } return <tr key={`empty-row-${index}`}>{rowNodes}</tr>; }) ) : null }
额外提醒
- 所有动态生成的React元素一定要加唯一的key,我这里用
empty-row-${index}来标识空行,避免React渲染时出现警告。 - 把
==换成===,这是JS的最佳实践,避免隐式类型转换带来的意外问题。
内容的提问来源于stack exchange,提问作者anesthetic
相关产品推荐
相关产品推荐

