我有多个<td>重复,如下面的示例代码所示。我想把它们放在一个函数中,这样我就可以模块化代码了。我无法更改代码中的任何内容。其他解决方案并不适用于像<td> {this.insertRow} </td>这样的解决方案。我想把整个<td>放在一个函数中。如果我直接这样做,那么<td>将被呈现为一个HTML。注意我的<td>是如何具有动态className和doubleClick()的。这就是为什么其他解决方案行不通的原因。这里只显示了相关代码。我有10多个<tr>,都有类似的结构,有多个<td>。
render() {
return (
<div>
<table>
<tbody>
<tr>
<td className="class1">00</td>
<td className={this.tdClass()}
onDoubleClick={(e) => {this.show(e.target.innerText)}}
>
{values[index++]}
</td>
<td className={this.tdClass()}
onDoubleClick={(e) => {this.show(e.target.innerText)}}
>
{values[index++]}
</td>
<td className={this.tdClass()}
onDoubleClick={(e) => {this.show(e.target.innerText)}}
>
{values[index++]}
</td>
<td className={this.tdClass()}
onDoubleClick={(e) => {this.show(e.target.innerText)}}
>
{values[index++]}
</td>
</tr>
</tbody>
<tbody>
<tr>
<td className="class1">00</td>
<td className={this.tdClass()}
onDoubleClick={(e) => {this.show(e.target.innerText)}}
>
{values[index++]}
</td>
<td className={this.tdClass()}
onDoubleClick={(e) => {this.show(e.target.innerText)}}
>
{values[index++]}
</td>
<td className={this.tdClass()}
onDoubleClick={(e) => {this.show(e.target.innerText)}}
>
{values[index++]}
</td>
<td className={this.tdClass()}
onDoubleClick={(e) => {this.show(e.target.innerText)}}
>
{values[index++]}
</td>
</tr>
</tbody>
<tbody>
<tr>
<td className="class1">00</td>
<td className={this.tdClass()}
onDoubleClick={(e) => {this.show(e.target.innerText)}}
>
{values[index++]}
</td>
<td className={this.tdClass()}
onDoubleClick={(e) => {this.show(e.target.innerText)}}
>
{values[index++]}
</td>
<td className={this.tdClass()}
onDoubleClick={(e) => {this.show(e.target.innerText)}}
>
{values[index++]}
</td>
<td className={this.tdClass()}
onDoubleClick={(e) => {this.show(e.target.innerText)}}
>
{values[index++]}
</td>
</tr>
</tbody>
<div>
)
}发布于 2020-06-08 07:13:24
如果要对每个值使用X个相同的td元素,则可以映射values对象。
values.map((value, i) => (
<td
key={i} // or something unique to the value among siblings
className={this.tdClass()}
onDoubleClick={(e) => {this.show(e.target.innerText)}}
>
{value}
</td>
))如果您需要将它“块”起来,您可以使用数组::slice对它进行块预处理,然后映射它。
values.slice(startIndexInclusive, endIndexExclusive)
.map((value, i) => (
<td
key={i} // or something unique to the value among siblings
className={this.tdClass()}
onDoubleClick={(e) => {this.show(e.target.innerText)}}
>
{value}
</td>
))如果this.tdClass依赖于全局index,则可以手动增加它。
values.slice(startIndexInclusive, endIndexExclusive)
.map((value, i) => {
index++;
return (
<td
key={i}
className={this.tdClass()}
onDoubleClick={(e) => {this.show(e.target.innerText)}}
>
{value}
</td>
);
})发布于 2020-06-08 07:18:17
您可以为行和设置道具创建新组件,如下所示:
const Row = (props) => {
return <td className={props.tdClass}
onDoubleClick={(e) => {props.show(e.target.innerText)}}>
{props.value}
</td>
}参见操场上的完整示例:https://jscomplete.com/playground/s510805
https://stackoverflow.com/questions/62256701
复制相似问题