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

如何在React.js中使用弹窗展示recipe变量?

React 实现弹窗展示 Recipe 内容方案

下面是改造后的完整代码,直接替换你现有组件即可实现弹窗展示功能:

import { useParams, useState } from "react-router-dom";

function DisplayRecipe({ searchResult }) {
  const { idMeal } = useParams();
  const recipe = searchResult.find((item) => item.idMeal === idMeal);
  const [isModalOpen, setIsModalOpen] = useState(false);

  const openModal = () => setIsModalOpen(true);
  const closeModal = () => setIsModalOpen(false);

  // 处理找不到对应食谱的情况
  if (!recipe) {
    return <div>未找到对应食谱</div>;
  }

  return (
    <>
      {/* 触发弹窗的按钮 */}
      <button onClick={openModal}>查看食谱详情</button>

      {/* 弹窗遮罩层 */}
      {isModalOpen && (
        <div style={modalOverlayStyle} onClick={closeModal}>
          {/* 弹窗内容区,阻止事件冒泡避免点击内容关闭弹窗 */}
          <div style={modalContentStyle} onClick={(e) => e.stopPropagation()}>
            <button style={closeButtonStyle} onClick={closeModal}>×</button>
            
            {/* 食谱内容 */}
            <h2>{recipe.strMeal}</h2>
            <p><strong>食材1:</strong>{recipe.strIngredient1}</p>
            <h3>制作步骤</h3>
            <p>{recipe.strInstructions}</p>
          </div>
        </div>
      )}
    </>
  );
}

// 弹窗基础样式
const modalOverlayStyle = {
  position: 'fixed',
  top: 0,
  left: 0,
  width: '100%',
  height: '100%',
  backgroundColor: 'rgba(0, 0, 0, 0.5)',
  display: 'flex',
  justifyContent: 'center',
  alignItems: 'center',
  zIndex: 1000,
};

const modalContentStyle = {
  backgroundColor: 'white',
  padding: '2rem',
  borderRadius: '8px',
  maxWidth: '600px',
  width: '90%',
  position: 'relative',
};

const closeButtonStyle = {
  position: 'absolute',
  top: '1rem',
  right: '1rem',
  border: 'none',
  backgroundColor: 'transparent',
  fontSize: '1.5rem',
  cursor: 'pointer',
};

export default DisplayRecipe;

关键改动说明

  • 新增useState管理弹窗的显示/隐藏状态,默认弹窗处于关闭状态。
  • 添加触发按钮,点击即可打开弹窗查看食谱详情。
  • 弹窗分为两层:半透明遮罩层占满整个视口,点击遮罩可关闭弹窗;中间内容区居中展示食谱信息,点击内容不会触发关闭,避免误操作。
  • 增加了食谱不存在时的兜底渲染,防止因找不到对应ID导致页面报错。
  • 用内联样式实现基础弹窗布局,你也可以把样式提取到单独的CSS文件中优化维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 16:22:41