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

React中如何通过onClick获取按钮组件数据并在页面展示?

解决方案

1. 给ItemsCategoryButton添加点击事件并传递菜品数据

先修改ItemsCategoryButton组件,让它接收一个点击回调的props,然后在内部按钮上绑定该回调,把当前菜品数据作为参数传递:

// ItemsCategoryButton.jsx
function ItemsCategoryButton({ item, onClick }) {
  return (
    <button 
      className="item-btn"
      onClick={() => onClick(item)}
    >
      <div>{item.name}</div>
      <div>¥{item.price}</div>
      <div>库存:{item.stock}</div>
    </button>
  );
}

接着在父组件HomeOrderPage中定义点击处理函数,渲染子组件时把这个函数传进去:

// HomeOrderPage.jsx
import { useState } from 'react';
import ItemsCategoryButton from './ItemsCategoryButton';

function HomeOrderPage() {
  // 假设你已有的分类和菜品数据
  const [selectedCategory, setSelectedCategory] = useState('');
  const [foodItems] = useState([/* 你的本地菜品数据 */]);
  const [selectedItem, setSelectedItem] = useState(null);

  // 处理菜品点击事件
  const handleItemClick = (item) => {
    setSelectedItem(item);
    // 若需跳转页面,这里可加路由逻辑
  };

  return (
    <div>
      {/* 分类按钮区域 */}
      <div className="category-buttons">
        {/* 你的分类切换逻辑 */}
      </div>
      {/* 菜品列表区域 */}
      <div className="items-list">
        {foodItems
          .filter(item => item.category === selectedCategory)
          .map(item => (
            <ItemsCategoryButton 
              key={item.id} 
              item={item} 
              onClick={handleItemClick}
            />
          ))}
      </div>
      {/* 当前页面展示选中菜品信息 */}
      {selectedItem && (
        <div className="item-detail">
          <h3>{selectedItem.name}</h3>
          <p>价格:¥{selectedItem.price}</p>
          <p>库存:{selectedItem.stock}</p>
        </div>
      )}
    </div>
  );
}

2. 是否需要使用Axios?

不需要。Axios是用于发起HTTP请求获取远程服务器数据的工具,你当前使用本地定义的数据,直接调用即可。只有后续需要从后端接口拉取菜品数据时,才需要用到Axios或浏览器原生的fetch API。

3. Props和Hooks的实现思路

核心逻辑

  • Props:用于组件间传递数据和回调。父组件将菜品数据、点击回调传给子组件ItemsCategoryButton,子组件负责渲染UI并触发回调告知父组件用户点击了哪个菜品。
  • Hooks:用useState管理选中菜品的状态,状态更新会触发页面重渲染,从而展示选中的菜品信息;如果需要跳转页面,结合React Router的useNavigate hook实现跳转并传递数据。

页面跳转的实现(可选)

若需跳转到单独的菜品详情页,先配置React Router,再修改点击处理逻辑:

// HomeOrderPage.jsx
import { useNavigate } from 'react-router-dom';

function HomeOrderPage() {
  const navigate = useNavigate();

  const handleItemClick = (item) => {
    // 跳转至详情页并携带菜品数据
    navigate('/item-detail', { state: { item } });
  };
}

在详情页中获取并展示数据:

// ItemDetailPage.jsx
import { useLocation } from 'react-router-dom';

function ItemDetailPage() {
  const location = useLocation();
  const item = location.state?.item;

  if (!item) return <div>未选中菜品</div>;

  return (
    <div>
      <h2>{item.name}</h2>
      <p>价格:¥{item.price}</p>
      <p>库存:{item.stock}</p>
    </div>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:36:23