通过动态更新 className 更改 table 行颜色

Change table row color by dynamically updating the className

我创建此 Typescript class 是为了更改 table 中的行颜色。我的目标是为 tr 动态更新 className。一切都按预期显示,但当我 check/uncheck 框时没有任何反应。我该如何解决这个问题?

import React from 'react';
import './App.css';

let classname: string = "checkbox-row1";

function getColor(pvalue: boolean) {
  if (pvalue) {
    classname = "checkbox-row1-red";
  }
  else {
    classname = "checkbox-row1-blue";
  }
}

export default function App() {

  return (
    <div className="App">
      <header className="App-header">
        <div className="checkbox-div">
          <table className="checkbox-table">
            <tr className={classname}>
              <td className="checkbox-row1"><label className="my-label">Check: <input type="checkbox" onClick={() => getColor(true)} name="change-color"></input></label></td>
              <td className="tr2-td2">2</td>
              <td className="tr3-td3">3</td>
            </tr>
          </table>
        </div>
      </header>
    </div>
  );
}
.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
  }
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.checkbox-row1 {
  background-color: #ffffff;
}

.checkbox-row1-blue {
  background-color: blue;
}

.checkbox-row1-red {
  background-color: red;
}

.my-label {
  color: black;
}

您想在 React 组件中使用 React 钩子 useState()。 (https://reactjs.org/docs/hooks-reference.html#usestate) 当状态发生变化时,re-render 将按预期更新您的行 class。

import { useState } from "react";
export default function App() {
    const [classname,setClassname] = useState<string>("checkbox-row1");

    function getColor(pvalue: boolean) {
      if (pvalue) {
         setClassname("checkbox-row1-red");
      }
      else {
        setClassname("checkbox-row1-blue");
      }

return ( ...