代码之家  ›  专栏  ›  技术社区  ›  Anirudh Agrawal

如何比较react+tsx中的两个tsx元素

  •  0
  • Anirudh Agrawal  · 技术社区  · 1 年前

    我想比较两个反应tsx元素。我对react和tsx还是新手。但即使复制并粘贴了要比较的确切元素,我也不能这样做。你能告诉我为什么以及如何修复它吗?

    这就是我想比较的地方

    function placeTile(index: number) {
        if (
          tiles[index] ===                  //Compare here
          (
            <div className="filler" id=".">
              .
            </div>
          )
        ) {
          let updateTile = tiles.slice();
          updateTile[index] = (
            <div className="filled" id={move}>
              {move}
            </div>
          );
          console.log("Filled a spot");
          setTiles(updateTile);
        } else {
          console.log("This is filled spot " + index);
        }
      }
    

    “tiles”是一个由如下声明的tsx元素组成的数组

    let createTileSetup = Array(9).fill(
        <div className="filler" id=".">
          .
        </div>
      );
    
    const [tiles, setTiles] = useState(createTileSetup);
    

    使用类似的东西 tiles[index].id 拿到身份证不起作用。它只是说它没有定义

    如果有其他方法,请告诉我。他们的ID不同,但我也不知道如何比较。任何帮助都将不胜感激

    2 回复  |  直到 1 年前
        1
  •  0
  •   garlic_bread_eater    1 年前

    你的策略不起作用的原因是,对于Javascript对象 === 运算符测试身份(即:它们是否引用同一个对象),而不是结构上的任何等价性。

    要解决这个问题,请使用其他测试来检查对象的相等性。例如,要测试您的className <div> s、 你可以写

    
    if (
          // .props.className gets the className of an HTML tag
          tiles[index].props.className === 'filler'
        )
    {
        // Do something
    }
    

    请注意,如果你这样做,你还必须检查每个 tiles[index] 实际上是一个HTML标签。否则, tiles[index].props.className 可能会导致错误 accessing property className of undefined .

    希望这能有所帮助。

        2
  •  0
  •   GifftyCode    1 年前

    比较元素的属性,而不是元素本身。与其直接比较JSX元素,不如比较图块的id属性。如果id与预期值(在本例中为“.”)匹配,请在指定索引处更新磁贴。

    const initialTiles = Array(9).fill({ className: "filler", id: ".", content: "." });
    const [tiles, setTiles] = useState(initialTiles);
    function placeTile(index: number) {
      if (tiles[index].id === ".") {  // Compare the id property
        let updateTile = [...tiles];
        updateTile[index] = { className: "filled", id: move, content: move }; 
        setTiles(updateTile);
      } else {
        console.log("This is a filled spot " + index);
      }
    }
    return (
      <div className="tile-container">
        {tiles.map((tile, index) => (
          <div
            key={index}
            className={tile.className}
            id={tile.id}
            onClick={() => placeTile(index)}
          >
            {tile.content}
          </div>
        ))}
      </div>
    );