代码之家  ›  专栏  ›  技术社区  ›  Alex Craft

Svelte contenteditable未正确更新

  •  0
  • Alex Craft  · 技术社区  · 3 年前

    我用Svelte创建了电子表格,但它似乎无法正确更新单元格。

    我将“2”后缀附加到每个单元格,当我编辑内容时(比如将jim中的第一个字母固定为大写),它应该以两个“2”作为“Jim22”结束。但最终只有一个“2”作为“Jim2”。

    我还有JSON输出来检查的值 rows ,并且它发生了变化,因此组件被正确更新,但可编辑单元格没有更新为“Jim22”,而是“Jim2”。

    为什么,以及如何解决?

    playground

    enter image description here

    密码

    <script>
      let rows = [
        ["jim"],
        ["Kate"]
      ]
    
      function update(i, j, event) {
            rows[i][j] = event.target.innerText
      }
    </script>
    
    <table>
      {#each rows as row, i}
        <tr>
          {#each row as cell, j}
            <td contenteditable="true" on:blur="{(event) => update(i, j, event)}">{cell}2</td>
          {/each}
        </tr>
      {/each}
    </table>
    
    <pre>{JSON.stringify(rows, null, 2)}</pre>
    
    0 回复  |  直到 3 年前
        1
  •  2
  •   Long Vu    3 年前

    只需为每个语句添加关键字。根据 document

    <script>
      let rows = [
        ["Jim",  "Raynor"],
        ["Kate", "Bishop"]
      ]
    
      function update(i, j, event) {
            rows[i][j] = event.target.innerText
      }
    </script>
    
    <table>
      {#each rows as row, i (row)}
        <tr>
          {#each row as cell, j (cell)}
            <td contenteditable="true" on:blur="{(event) => update(i, j, event)}">{cell}2</td>
          {/each}
        </tr>
      {/each}
    </table>
    
    <pre>{JSON.stringify(rows, null, 2)}</pre>
    
        2
  •  1
  •   Allan Chain    3 年前

    我不认为龙武的回答是问题的根本原因,因为它无法解释为什么问题评论中提到的修改有效。添加密钥是一种变通方法。

    经过一些调试和搜索,我发现了这个问题: Repeat words in plain text aren't reactive 。尝试更新时 "Jim" "Jim2" ,苗条的用途 set_data function ,比较 text.wholeText === data 虽然 text.data “Jim” , text.wholeText data 都是 “Jim2” ,因此跳过更新。

    About wholeText :

    这个 Text.wholeText 只读属性返回所有的全文 Text 在逻辑上与该节点相邻的节点。

    因此,通过检查 childNodes 的属性 td :

    • <td>{cell}2</td> 有两个 文本 节点: “Jim” "2" 全文 “Jim2”
    • <td>{cell + "2"}</td> 有一个 文本 节点,没有问题
    • <td>{@html cell}2</td> 未使用 设置数据 功能,精细

    同样正如问题中所说,将svelte降级为v3.23.2使 <td>{cell}2</td> 工作如预期。