You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React重构电影列表网站:实现点击电影卡片打开对应模态框的方法

How to Implement Modal Toggle on Button Click in React for Movie Cards

Got it, let's fix this modal toggle functionality for your movie cards. Instead of using direct DOM selection (like you probably did in the static site), we'll use React's state management to control when the modal shows up—this aligns with React's data-driven UI approach and avoids potential inconsistencies.

Here's the updated version of your Movies component with the click handlers and modal visibility logic:

import React, { useState } from "react"; // Add useState hook
const IMG_URL = 'https://image.tmdb.org/t/p/w500';

function getColor(vote) {
  if(vote >= 8){
    return 'green';
  }else if (vote >= 5){
    return 'orange';
  }else{
    return 'red';
  }
}

function Movies ({title, id, poster_path, overview, vote_average, release_date}) {
  // Add state to track if the modal is open
  const [isModalOpen, setIsModalOpen] = useState(false);

  return (
    <div className="movie-modal-container">
      <div className="movie">
        {/* Add onClick handler to open the modal */}
        <button 
          className="myBtn"
          onClick={() => setIsModalOpen(true)}
        >
          <img src={IMG_URL+poster_path} alt={title}/>
          <div className="movie-info">
            <h3>{title}</h3>
            <span className={getColor(vote_average)}>{vote_average}</span>
          </div>
          <div className="overview">
            <div className="overview-header">
              <h3>Overview</h3>
              <div className="addBtn">
                <i className="fas fa-plus"></i> {/* Fixed class to className for React */}
              </div>
            </div>
            <p>{overview}</p>
          </div>
        </button>
      </div>
      {/* Control modal visibility with state */}
      <div 
        className="modal"
        style={{ display: isModalOpen ? 'block' : 'none' }} // Toggle display based on state
      >
        <div className="modal-content">
          {/* Add onClick handler to close the modal */}
          <span onClick={() => setIsModalOpen(false)}>
            <i className="fas fa-times"></i> {/* Fixed class to className */}
          </span>
          <div className="modal-poster">
            <img src={IMG_URL+poster_path} alt={title}/>
          </div>
          <div className="modal-info">
            <h2>{title}</h2>
            <span>{vote_average}/10</span>
            <h3 className="releasedate">Release Date</h3>
            <p>{release_date}</p>
            <h3>Overview</h3>
            <p className="modal-overview">{overview}</p>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Movies;

Key Changes Explained:

  1. Added useState Hook: We imported and initialized the isModalOpen state variable to track whether the modal should be visible. It starts as false (closed).
  2. Button Click Handler: The movie card button now has an onClick prop that sets isModalOpen to true, triggering the modal to open.
  3. Modal Visibility Control: Instead of relying on ID-based DOM selection, we use inline styling (or you could toggle a CSS class) to show/hide the modal based on the isModalOpen state.
  4. Close Button Handler: The close button (times icon) now has an onClick prop that sets isModalOpen back to false, closing the modal.
  5. Fixed class to className: React uses className instead of class for HTML element classes, so I updated those instances to avoid warnings/errors.

Optional Enhancement:

If you prefer using CSS classes instead of inline styles for visibility, you can define a modal-active class in your CSS that sets display: block, then update the modal's className like this:

<div className={`modal ${isModalOpen ? 'modal-active' : ''}`}>

Just make sure your base .modal class has display: none by default.

This approach keeps your component self-contained and follows React's best practices for state management.

内容的提问来源于stack exchange,提问作者Dead

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 00:38:15