如何在 React 组件实例上使用 onClick 侦听器更新 State Hook

How to update State Hook with onClick listener on React Component Instance

我正在尝试将 onClick 添加到组件实例,它会更改 useState 挂钩的状态,并将其打印到控制台。但是,单击组件实例时不会触发任何内容。

我尝试将其包装在 JSX div 元素中,并向 div 添加 onClick 以打印到控制台,但状态未更新,因为始终显示未定义。

最终目标是在点击后将状态传递给另一个组件(链接页面)。

这是我的代码。

Card.js

export default function Card(props) {
  return (
    <div className="card" style={{ background: `${props.background}` }}>
      <h2>{props.taskName}</h2>
      <p>{props.description}</p>
    </div>
  );
}

Home.js

import { Link } from "react-router-dom";
import { useState, useEffect } from "react";
import Card from "../components/Card";
import "../pages/Home.scss";
import ProfileButton from "../components/ProfileButton";
import Header from "../components/Header";
import "./PlayerPage";

export default function Home() {
  const date = new Date();
  const time = date.getHours();
  let timeOfDay;

  if (time < 12) {
    timeOfDay = "Morning";
  } else if (time >= 12 && time < 6) {
    timeOfDay = "Afternoon";
  } else {
    timeOfDay = "Evening";
  }

  const [task, setTask] = useState();

  useEffect(() => {
    console.log(task);
  })

 return (
  <>
   <Header />
    <main className="home-main">
     <div className="main-wrap">
      <section className="card-container">
       <h1>Good {timeOfDay}</h1>
        <h1>Choose Your Work Style</h1>

         <div className="card-wrap">
          <Link to="/PlayerPage">
           <Card onClick={() => {console.log("hey") }}
            taskName="Short Task"
            description="Lorem ipsum dolor sit amet, consectetur adipiscing elit."
         />
          </Link>
     </div>
</>
);
}

PlayerPage.js - (需要显示更新状态的组件)

export default function PlayerPage() {
  return (
    <>
      <Header />
      <main className="player-page-main">
        <div className="player-page-main-wrap">
          <div className="timer-title-wrap">
            <Timer />
            <h2 className="task-title">{Updated state here}</h2>
          </div>
        </div>
      </main>
    </>
  );
}

Card 组件需要将传递的 onClick 处理程序属性附加到 DOM 元素。

示例:

export default function Card(props) {
  return (
    <div
      className="card"
      style={{ background: `${props.background}` }}
      onClick={props.onClick}
    >
      <h2>{props.taskName}</h2>
      <p>{props.description}</p>
    </div>
  );
}