首页 > 解决方案 > 如何修复代码,以便仅针对点击的国家/地区显示附加卡?

问题描述

当我单击一个国家的行时,会出现整个国家列表的附加卡。如何使附加卡仅针对点击的国家/地区打开?

    /*const countries = useCountry();*/
    const [showCard, setShowCard] = useState('none');

    const currentView = {
        display: showCard
    }

    const ShowOnClick = () =>{
        let display = 'flex'
        setShowCard(display)
    }       

    if(!data){
        return(
            <h1>Loading...</h1>
        )
    }

    return (
    <table>
        <thead>
            <tr>
                <th>№&lt;/th>
                <th>Country</th>
                <th>Total Confirmed</th>
            </tr>
        </thead>
        <tbody>
            {data.map((country, index) => (
                <>
                <tr onClick={ShowOnClick} key={index}>
                    <td>{index + 1}</td>
                    <td>{country.Country}</td>
                    <td>{country.TotalConfirmed}</td>
                    {/*<td className="deaths">{country.TotalDeaths}</td>
                    <td>{country.TotalRecovered}</td>*/}
                </tr>
                 <div  className="card" style={currentView}>
                    <h4>{country.Country}</h4>
                </div>
                </>
            ))}
        </tbody>
    </table>
    )
};```

标签: javascriptreactjs

解决方案


您可以创建一个名为 TableRow 的新组件并在其中包含状态。这样每一行都会有自己的状态。

const TableRow = ({ country, rowNo }) => {
  const [showCard, setShowCard] = useState('none');
 
  const ShowOnClick = () =>{
    setShowCard(display)
}   

  return (
    <>
    <tr onClick={ShowOnClick} key={index}>
        <td>{rowNo}</td>
        <td>{country.Country}</td>
        <td>{country.TotalConfirmed}</td>
        {/*<td className="deaths">{country.TotalDeaths}</td>
        <td>{country.TotalRecovered}</td>*/}
    </tr>
     <div  className="card" style={{ display: showCard}}>
        <h4>{country.Country}</h4>
    </div>
    </>
  )
}

现在您可以将其用作

<tbody>
        {data.map((country, index) => (
           <TableRow key={index} country={country} rowNo={index + 1}  />
        ))}
</tbody>

这种方法的优点是现在单击一行将仅重新呈现该行而不是所有其他行,如果您的状态位于呈现所有行的组件中,则会发生这种情况。


推荐阅读