【问题标题】:How to pass props to a modal如何将道具传递给模态
【发布时间】:2018-12-20 10:08:33
【问题描述】:

我有一个购物应用程序,我在其中映射一些产品并将它们呈现在屏幕上。用户可以增加/减少数量。当数量变为 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>
))}

有什么想法吗?

【问题讨论】:

标签: javascript reactjs react-redux


【解决方案1】:

我最近遇到了类似的情况。我使用 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)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 2020-12-22
    • 2017-10-03
    相关资源
    最近更新 更多