React中映射通用组件时,如何在不同页面显示不同按钮?
解决方案
有两种简单的实现方式,按需选择:
方式一:直接传递按钮文本(推荐,灵活性更高)
给InventoryItem组件新增一个buttonText属性,默认值设为'Delete'(适配其他页面),首页使用时传入'Update'即可。
修改后的InventoryItem组件代码:
import React from 'react'; import { Card } from 'react-bootstrap'; const InventoryItem = ({ product, buttonText = 'Delete' }) => { const { productName, productImage, productPrice, productQuantity, productSupplier, productDetails } = product; return ( <div className='col-12 col-md-6 col-lg-6'> <Card className='h-100 items-card d-block d-md-block d-lg-flex flex-row align-items-center border border-0'> <div className='text-center card-image-container'> <Card.Img variant="top" src={productImage} className='card-image img-fluid' /> </div> <Card.Body className='card-details'> <Card.Title>{productName}</Card.Title> <Card.Text>{productDetails}</Card.Text> <div className='d-lg-flex align-items-center justify-content-between mb-3'> <p className='mb-0'>Price: ${productPrice}</p> <p className='me-2 mb-0'>Stock: {productQuantity}</p> </div> <div className='d-flex align-items-center justify-content-between'> <p className='mb-0'>Supplier:{productSupplier}</p> {/* 替换为传入的按钮文本 */} <button className='btn btn-dark'>{buttonText}</button> </div> </Card.Body> </Card> </div> ); }; export default InventoryItem;
页面使用示例:
- 首页生成卡片时,传入
buttonText="Update":
{products.map(product => ( <InventoryItem key={product.id} product={product} buttonText="Update" /> ))}
- 其他页面生成卡片时,无需额外传参,自动使用默认的'Delete':
{products.map(product => ( <InventoryItem key={product.id} product={product} /> ))}
方式二:传入页面标识(语义化更强)
给组件新增一个isHome布尔属性,默认值为false,组件内部根据这个标识判断按钮文本。
修改后的InventoryItem核心代码:
const InventoryItem = ({ product, isHome = false }) => { // 根据标识确定按钮文本 const buttonText = isHome ? 'Update' : 'Delete'; // ... 其余原有代码不变 // 按钮处使用变量 <button className='btn btn-dark'>{buttonText}</button> };
页面使用示例:
- 首页传入
isHome={true}:
{products.map(product => ( <InventoryItem key={product.id} product={product} isHome={true} /> ))}
- 其他页面无需传参,默认显示'Delete'。
内容的提问来源于stack exchange,提问作者Shakil Ahmed
相关产品推荐
相关产品推荐

