【问题标题】:scalajs-react: How to know index of the entry while looping a Seq?scalajs-react:如何在循环 Seq 时知道条目的索引?
【发布时间】:2021-11-25 20:34:09
【问题描述】:

在 scalajs-react 组件中循环集合时如何获取索引?所以基本上我有这样的代码:

<.div(
          employees.map( employee =>
            <.form(
              <.label("Name of the employee:",
                <.input(^.`type` := "text", ^.cls := "form-control",
                  ^.value := employee.name)),
              <.br,
              <.label("Addresses:",
                <.input(^.`type` := "textarea", ^.rows := 100, ^.cols := 20,^.cls := "form-control",
                  ^.value := employee.addresses.mkString(",")))
              
            )
    )
)

所以如果用户更改了一个字段,我需要知道员工中的哪个员工被更改。所以我需要知道相应的索引或者是否有其他更好的方法。

【问题讨论】:

    标签: reactjs scala scala.js scalajs-react


    【解决方案1】:

    您可以使用标准的 Scala zipWithIndex 方法:

    employees.zipWithIndex.map{ case (employee, index) =>
    

    然后使用index 标记适当的input 元素。

    【讨论】:

      【解决方案2】:

      第二个参数是循环的索引。

      <.div(
                employees.map( (employee,index) =>
                  <.form(
                    <.label("Name of the employee:",
                      <.input(^.`type` := "text", ^.cls := "form-control",
                        ^.value := employee.name)),
                    <.br,
                    <.label("Addresses:",
                      <.input(^.`type` := "textarea", ^.rows := 100, ^.cols := 20,^.cls := "form-control",
                        ^.value := employee.addresses.mkString(",")))
                    
                  )
          ))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-19
        • 2018-10-17
        • 1970-01-01
        • 2016-10-27
        • 1970-01-01
        相关资源
        最近更新 更多