簡體   English   中英

具有相同ID的多個按鈕的Onclick功能?

[英]Onclick function for multiple buttons with same ID?

我有這個組件用按鈕加載一些數據。 我有一個函數,它通過 ID 獲取按鈕並將狀態/變量更新為該按鈕值,然后基於該值加載數據。 但是,由於所有按鈕 ID 都相同,因此它僅適用於第一個按鈕...

我不確定如何為每個按鈕設置唯一 ID,因為它們是通過 map() 函數生成的,即使我知道,我也不確定我的函數將如何定位每個按鈕而不為它編寫函數每一個...

編輯:我現在已經為按鈕設置了唯一 ID,仍然需要解決另一個問題。

  return member.map((player, index) => (
    <>
      {" "}
      <React.Fragment key={index}>
        <br />{" "}
        <div>
          <br />
          {player.map((stats) => (
            <React.Fragment key={stats.player}>
              <div class="flex-child">
                <button id={'btn' + index} value={stats.player}>
                  {stats.player}
                </button>
                <p>{stats.role}</p>
                <p>{stats.win_rate}</p>
                <p>{stats.matches}</p>
                <p>{stats.total_battles} Total Battles</p>
                <p>{stats.score} / Points Earned</p>
              </div>
            </React.Fragment>
          ))}
        </div>
        <br />
      </React.Fragment>
    </>
  ));
};

export default SquadMembers;

這是 index.js

import Head from "next/head";
import React, { useState } from "react";
import Teams from "../components/Teams";
import styles from "../../styles/Home.module.css";
import SquadMembers from "../components/SquadMembers";
import SquadData from "../components/SquadData";

export default function Home() {
  const [teams, setTeams] = useState([]);
  const [squads, setSquads] = useState([]);
  const [player, setPlayer] = useState("Player Name");
  const [squad, setSquad] = useState("default");
  const [loading, setLoading] = useState(false);

  function clicky() {
    if (!document.getElementById("btn")) {
    } else {
      setPlayer(document.getElementById("btn").value);
      loadPeople();
    }
  }

  if (typeof window === "object") {
    if (!document.getElementById("btn")) {
    } else {
      document.getElementById("btn").onclick = function () {
        clicky();
      };
    }
  }

  function handleChange(e) {
    setSquad(e.target.value);
  }

  const loadPeople = async () => {
    setLoading(true);
    const req = await fetch(`/api/player/${player}`);
    const json = await req.json();
    setTeams(json);
    setLoading(false);
  };

  const loadSquad = async () => {
    setLoading(true);
    const req = await fetch(`/api/squad/${squad}`);
    const json = await req.json();
    setSquads(json);
    setLoading(false);
    setTeams([]);
  };

  return (
    <div className={styles.main}>
      <main className={styles.main}>
        <h1>Silph Team Finder</h1>
        <br />
        <div>
          <select value={squad} onChange={handleChange}>
            <option value="default" selected disabled hidden>
              Choose here
            </option>
            <option value="a342">Lots of options, cut them to save space</option>
          </select>
          <button onClick={() => loadSquad()}>Load</button>

          <input
            value={player}
            id="player"
            onChange={(e) => setPlayer(e.target.value)}
          />
          <button onClick={() => loadPeople()} id="pbtn">
            Load
          </button>
          {loading && <div className={styles.load}>LOADING</div>}
        </div>
        <div className={styles.teams}>
          <SquadData squadz={squads} />
          <Teams teams={teams} />
          <div class="player-container">
            <SquadMembers squadz={squads} />
          </div>
        </div>
      </main>
    </div>
  );
}

擁有類似的東西會容易得多:

<button value={stats.player} onClick={() => handleClick(stats.player)}>
   {stats.player}
</button>

...

const handleClick = (player) => {
   setPlayer(player);
   loadPeople();
}

通過這種方式,您不需要id button 不僅如此,您還可以避免對多個元素的相同 id 發出警告。

然后我想談談loadPeople() 如果我在這個函數中理解正確,你正在使用由setPlayer設置的player 這不是一個好方法。 setPlayer是異步的,您可以使用player的舊值。 最好將最后一個player值直接傳遞給loadPeople函數。 就像是:

const handleClick = (player) => {
   setPlayer(player);
   loadPeople(player);
}

const loadPeople = async (newPlayer) => {
   setLoading(true);
   const req = await fetch(`/api/player/${newPlayer}`);
   const json = await req.json();
   setTeams(json);
   setLoading(false);
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM