javascript - 如何将道具传递给模态
问题描述
我有一个购物应用程序,我在其中映射一些产品并将它们呈现在屏幕上。用户可以增加/减少数量。当数量变为 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>
))}
有任何想法吗?
解决方案
我最近遇到了类似的情况。我使用 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)
}
}
推荐阅读
- java - 我有两种不同类型的用户,即司机和乘客。我想在登录页面中,如果它是驱动程序的登录唯一驱动程序应该授权
- java - 无法在java(客户端)的套接字上正确写入数据(类)并在c ++(服务器)上读取它
- asp.net - azure cli 中带有 json 文件的 azure appsettings
- xcode - Xcode 11 b5:首次启动错误消息 - 我应该担心吗?
- android - 从 Facebook 应用拦截链接以打开我的 Android 应用
- git - 防止 Jenkins 在提交时自动构建
- r - 如何将列表的所有对象应用于改变 dplyr tibble 的函数?
- javascript - 如何从js接收来自jsp的参数?
- apple-sign-in - ASAuthorizationController 因现有设置流程而失败
- rest - 如何使用带有邮递员的 REST API 获取 HP ALM 14 登录身份验证令牌