如何在for..of循环(TypeScript)中动态地给HTML元素一个唯一的ID?

时间:2019-05-15 08:29:20

标签: html reactjs typescript

我有一个数组,需要将相同的HTML元素放入其中。我有一个 for..of TypeScript循环,它将动态地将这些元素添加到数组中。我想用唯一的ID来区分每个元素。 for..of Typescript循环有可能吗?

以下是我的代码:

for (let row of this.props.users) {
    userRows.push(
            <tr>
                <td>
                    <input type="radio"
                        id="customRadio1" 
                        name="customRadio" />
                </td>
            </tr>
    );
}

现在IDcustomRadio1,并且将是每个元素的customRadio2。我希望下一个HTML元素具有customRadio3和下一个customerRadio + {counter},依此类推。

NB!我知道这可以通过在for..of循环上声明一个计数器变量并递增每次运行的计数来实现,以便该变量可以与文本customerRadio一起使用,例如row。我想知道仅通过在for..of循环中使用{{1}}变量是否可行以及如何实现?

3 个答案:

答案 0 :(得分:1)

怎么样?

for (let i in this.props.users) {
    /* Since i is a string, we need to convert it to a number before calculating 
       1-based index (to start with 'customRadio1') */
    let index = Number(i) + 1; 
    userRows.push(
        <tr>
            <td>
                <input type="radio"
                    id={'customRadio' + index}
                    name="customRadio" />
            </td>
        </tr>
    );
}

答案 1 :(得分:1)

真正的map解决方案应如下所示:

const userRows = this.props.users.map( (value, index) => (
  <tr>
    <td>
      <input type="radio" id={'customRadio' + {index}} name="customRadio" />
    </td>
  </tr>)
);

答案 2 :(得分:0)

xadm关于可能使用map的评论后,我决定将for..of循环改写为map,这似乎很方便并且有效:

   this.props.users.forEach((value: User, index: number) => {
        userRows.push(
            <tr>
                <td>
                    <input type="radio" id={'customRadio' + {index}} name="customRadio" />
                </td>
            </tr>);
    });

如果可以使用for..of循环解决此问题,请随时告诉我以获取进一步的知识。