我有多个重复<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>
)
}
如果你希望每个值都有 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>
))
如果你需要"分块"它,你可以用array::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>
);
})
你可以为行和设置道具创建新组件,如下所示:
const Row = (props) => {
return <td className={props.tdClass}
onDoubleClick={(e) => {props.show(e.target.innerText)}}>
{props.value}
</td>
}
查看游乐场的完整示例:https://jscomplete.com/playground/s510805