我正在学习 React,并尝试从列表中删除一个项目。我尝试了几种解决方案,但找不到任何可以使其发挥作用的方法。我需要额外的眼睛来看看我错过了什么......
我的调用删除函数的代码
handleDeletePrice = deletePrice => {
this.setState(prevState => ({
// spreads out the previous list and delete the price with a unique id(date)
priceArr: prevState.priceArr.filter(item => item.date !== deletePrice)
}));
};
这是我在 hook(?) 组件中调用函数的地方。这会显示价格列表,每个价格框中都有一个删除按钮。
{this.state.priceArr.map((props) => (
<PriceBox
{...props}
key={props.date}
toggleEditing={this.toggleItemEditing}
handleDeletePrice={this.handleDeletePrice}
onChange={this.handleItemUpdate}
/>
))}
在单一价格框组件中,我在此处添加了删除价格的点击:
{this.props.handleDeletePrice && (
<button
type="button"
className="delete-btn"
onClick={() => this.props.handleDeletePrice()}
>
X
</button>
)}
要查看我的完整代码,您可以在 CodeSandBox 上查看我的演示,我在其中加载了 github 存储库以显示我的代码。 https://codesandbox.io/s/github/kikidesignnet/caissa
在此演示中,您单击价格
按钮并打开一个弹出窗口。这是这个单页应用程序中的另一个页面。在此窗口中,您可以看到价格列表以及每个价格框中的 X
按钮。我还尝试使用日期
作为唯一的ID,因为每个价格应该每天输入一次。换句话说,我尝试使用日期
作为唯一ID来删除价格框。
我错过了什么?
最佳答案
我不了解业务领域,但我认为这种方法可以提供帮助
{this.state.priceArr.map((props) => (
<PriceBox
{...props}
key={props.date}
price={props.price}
toggleEditing={this.toggleItemEditing}
handleDeletePrice={this.handleDeletePrice}
onChange={this.handleItemUpdate}
/>
))}
{this.props.handleDeletePrice && (
<button
type="button"
className="delete-btn"
onClick={() => this.props.handleDeletePrice(this.props.price)}
>
X
</button>
)}
关于javascript - React 尝试从列表中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61194902/