onClick 函数不会为映射的组件触发

onClick function won't fire for mapped component

相关代码如下:

const Members = () => {
  // array of each video in selected grade
  const videosMap = (videos) => {
    return videos.map((video) => (
      <VideoCard
        key={video.id}
        thumbnail={video.thumbnail}
        title={video.title}
        description={video.description}
        onClick={() => {
          handleVideoClick();
        }}
      />
    ));
  };

  // updates state of shown videos & page heading
  const handleGradeButtonClick = (videos, heading) => {
    setShowVideos(videosMap(videos));
    setVideosHeading(heading);
  };

  const handleVideoClick = () => {
    console.log("test");
  };

  // controls state of which grade's videos to show
  const [showVideos, setShowVideos] = useState(videosMap(kinder_videos));
  // controls states heading to display depending on selected grade
  const [videosHeading, setVideosHeading] = useState("Kindergarten");

  const [showVideoDetails, setShowVideoDetails] = useState(null);

handleVideoClick 函数在我单击映射的 VideoCard 组件之一时不起作用。

如果你想看的话,这里是完整的代码: https://github.com/dblinkhorn/steam-lab/blob/main/src/components/pages/Members.js

当我在 React DevTools 中查看其中一个 VideoCard 组件时,它显示以下内容:

onClick: *f* onClick() {}

如果我不将其包装在箭头函数中,它会执行,但会在组件加载时执行,而不是在单击时执行。感觉和我用.map渲染这个组件有关系,但是没搞清楚

感谢您的帮助!

你的映射方法没有问题,你只需要将 onClick 方法作为 prop 传递给你的 VideoCard 组件即可:

在您的 VideoCard 组件上执行此操作:

const VideoCard = (props) => {
  const { thumbnail, description, title, onClick } = props;

  return (
    <div className="video-card__container" onClick={onClick}>
      <div className="video-card__thumbnail">
        <img src={thumbnail} />
      </div>
      <div className="video-card__description">
        <div className="video-card__title">
          <h3>{title}</h3>
        </div>
        <div className="video-card__text">{description}</div>
      </div>
    </div>
  );
};

export default VideoCard;