How to pass props to a modal

后端 未结 1 1897
盖世英雄少女心
盖世英雄少女心 2021-01-22 10:01

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 decre

相关标签:
1条回答
  • 2021-01-22 10:43

    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)
        }
    }
    
    0 讨论(0)
提交回复
热议问题