How to pass props to a modal

2019-02-28 07:48发布

问题:

I have a shopping application where I map over some products and render them on screen. users can increase/decrease quantity. when the quantity gets to 1 and the user hits decrease, some middleware jumps in and asks if they are sure they want to remove it from the basket. if they click no then it will close the modal and leave it in the basket. if they click yes, it will close the modal and remove it from basket

how can I pass props to the modal to make sure I delete the correct product?

so far I have this. all the functionality is there and the ability to remove is there. I'm just not sure how to pass the particular product to the modal? the reason that the increment/decrement work is because they are part of the map that maps over each product. obviously when the modal loads, it is not part of the map. I have tried including it in the map but obviously this renders a modal for each product which isn't useful

<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>
))}

any ideas?

回答1:

I faced a similar scenario recently. I managed it using redux/global state as I had to keep track of many modals. Similar approach with local 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)
    }
}