javascript - 如何在 ReactJS 中将删除函数作为道具传递
问题描述
我正在构建一个食谱应用程序,但在使用删除功能时遇到了问题。
它的工作原理是单击“添加配方”按钮,然后弹出一个模式,让您填写一些新配方的输入字段。在该表单中是一个成分字段和一个“添加成分”按钮。您单击“添加”,该成分将添加到成分列表中。它的行为与待办事项列表完全相同,但它位于表单组件内部。我还希望能够去除一种成分。
我的应用程序组件的结构如下:
- RecipeBook.js(父)
- RecipeCardForm.js(子)
这是位于父组件中的表单组件:
<RecipeCardForm
handleRemoveIngredients={this.handleRemoveIngredients}
/>
父组件中还有函数removeIngredient
:
handleRemoveIngredient = id => {
const filteredIngredientList = this.state.ingredientList.filter(ingredient => id !== ingredient.id);
this.setState({ingredientList: filteredIngredientList})
}
在子组件中,这是在<ul>
显示成分列表的 a 中返回的:
{this.props.ingredientList.map(ingredient => {
return (
<li key={ingredient.id}>
<span>{ingredient.amount}</span>
<span>{ingredient.ingredient}</span>
<span ><button type='button' className='btn btn-danger'
onClick={ this.props.removeIngredient }>X</button></span>
</li>
)
})}
由于它的结构,我无法弄清楚如何传递通常会在父组件中删除道具的删除函数中传递的 id。
通常,我会做这样的事情:
this.state.items.map(item => {
<List
handleRemoveItem={() => this.handleRemoveItem(item.id)} />
但是由于父组件中没有映射任何内容,因此我无法传递 id。
因此,当我在removeIngredient
函数中记录 id 时,它显示为未定义。我知道它在那里。当我在添加函数中记录它时,有一个 id,当我在映射子组件中的每个成分时记录它时,它也在那里。我什至可以在删除成分按钮的 onClick 中访问它:
<button
type='button'
className='btn btn-danger'
onClick={ () => console.log(ingredient.id)}>Delete</button>
这也给了我id。
我只是想不通如何在不映射父组件的情况下传递它,但实际上没有什么可以映射到父组件中。当然,传递“this.state.id”只会给我一个空字符串的初始状态。
任何帮助将不胜感激,以帮助我了解如何做到这一点。提前致谢!
解决方案
没关系,刚刚想通了。
解决方案确实是onClick={ () => this.props.removeIngredient(ingredient.id) }
我的问题是当我将道具传递给子组件时,handleRemoveIngredient={this.handleRemoveIngredient}
我将它作为没有参数的函数传递,handleRemoveIngredient={() => this.handleRemoveIngredient()}
并且由于某种原因导致 id 返回未定义。
谢谢您的帮助!!
推荐阅读
- c - 尝试将 fmemopen 文件描述符与标准输入关联时出现错误的文件描述符错误
- git - 你如何删除/取消设置 GIT_EDITOR 变量
- security - 您可以将散列密码以纯文本形式发回给用户吗?
- terraform - Terraform 中单个字符串中的多个输出
- powershell - PowerShell ISE:如何运行新的 PowerShell 版本
- java - 从文件夹spring boot加载文件
- python-3.x - 在 Webdriver 的不同实例中维护 Session
- python - 字典中的唯一组合值
- rest - 一对一资源的 REST 端点应该是什么?
- html - 引导标签和输入字段对齐问题