首页 > 解决方案 > 如何将道具传递给模态

问题描述

我有一个购物应用程序,我在其中映射一些产品并将它们呈现在屏幕上。用户可以增加/减少数量。当数量变为 1 并且用户点击减少时,一些中间件会介入并询问他们是否确定要从篮子中删除它。如果他们单击否,那么它将关闭模式并将其留在购物篮中。如果他们单击是,它将关闭模式并将其从购物篮中删除

如何将道具传递给模态以确保删除正确的产品?

到目前为止,我有这个。所有功能都在那里,并且可以删除。我只是不确定如何将特定产品传递给模态?增加/减少工作的原因是因为它们是map映射每个产品的一部分。显然,当模态加载时,它不是地图的一部分。我已经尝试将它包含在地图中,但显然这会为每个产品呈现一个没有用的模式

<h4> Bag </h4>
<Modal />
{bag.products.map((product, index) => (
  <div key={index}>
    <div>{product.name}</div>
    <div>£{product.price}</div>
    <div>
      <span> Quantity:{product.quantity} </span>
      <button onClick={() => this.props.incrementQuantity(product, product.quantity += 1)}> + </button>
      <button onClick={() => this.props.decrementQuantity(product)}> - </button>
    </div>
  </div>
))}

有任何想法吗?

标签: javascriptreactjsreact-redux

解决方案


我最近遇到了类似的情况。我使用 redux/global state 管理它,因为我必须跟踪许多模态。与当地状态类似的方法

//****************************************************************************/

constructor(props) {

    super(props)


    this.state = {
      isModalOpen: false,
      modalProduct: undefined,
    }
}

//****************************************************************************/

render() {

    return (
        <h4> Bag </h4>
        {this.state.isModalOpen & (
          <Modal 
            modalProduct={this.state.modalProduct}
            closeModal={() => this.setState({ isModalOpen: false, modalProduct: undefined})
            deleteProduct={ ... }
          />
        )

        {bag.products.map((product, index) => (
        <div key={index}>
            <div>{product.name}</div>
            <div>£{product.price}</div>
            <div>
            <span> Quantity:{product.quantity} </span>
            <button onClick={() => this.props.incrementQuantity(product, product.quantity += 1)}> + </button>
            <button onClick={() => this.decrementQuantity(product)}> - </button> // <----
            </div>
        </div>
        ))}
    )
}

//****************************************************************************/

decrementQuantity(product) {

    if(product.quantity === 1) {
        this.setState({ isModalOpen: true, modalProduct: product })
    } else {
        this.props.decrementQuantity(product)
    }
}

推荐阅读