[英]onClick is not working in my react component
onClick(handleRecipeAdd),onClick(handleRecipeDelete)不工作
我最近正在学习反应,我需要一些帮助。 下面我已经粘贴了所有代码。
App.js 代码:
const [recipes, setRecipes] = useState(sampleRecipes)
function handleRecipeAdd(){
const newRecipe = {
id: uuidv4(),
name: 'New',
servings: 1,
cookTime: '1:00',
instructions: 'Instr.',
ingredients: [{id: uuidv4(), name: 'Name', amount: '1 Tbs'}]
}
setRecipes([...recipes, newRecipe])
}
function handleRecipeDelete(id){
setRecipes(recipes.filter(recipe=>recipe.id !== id))
}
return (
<RecipeList recipes={sampleRecipes} handleRecipeAdd={handleRecipeAdd} handleRecipeDelete={handleRecipeDelete}/>
)
}
食谱清单代码
export default function RecipeList({recipes, handleRecipeAdd, handleRecipeDelete}) {
return (
<div className='recipe-list'>
<div>
{recipes.map(recipe => {
return (
<Recipe key={recipe.id} {...recipe} handleRecipeDelete={handleRecipeDelete}/>
)
})}
</div>
<div className="recipe-list__add-recipe-btn-container">
<button onClick={handleRecipeAdd} className='btn btn--primary'>Add Recipe</button>
</div>
</div>
)
}
配方代码
export default function Recipe({handleRecipeDelete}) {
return (
<div className='recipe'>
<div className='recipe__header'>
<button className='btn btn--primary mr-1'>Edit</button>
<button onClick={()=>handleRecipeDelete(id)} className='btn btn--danger'>Delete</button>
</div>
</div>
)
}
我不明白,我搜索了很多,没有发现任何错误。 所以帮我解决这个问题。
<button onClick={(event)=>handleDelete(event.targrt.id)}>Delete</button>
您在这里使用 props 钻孔,这不是一个好方法,但您正在学习所以没关系,在 props 尝试学习 React Context API 之后,它将帮助您处理来自任何组件的用例。
来解决你的问题
在 App.js 中,您正在传递像这样的道具<RecipeList recipes={sampleRecipes}.../>
但它应该像这样<RecipeList recipes={recipes}.../>
为什么要使用食谱,因为这是原始的 state将来会更新或修改的默认值。
要删除或过滤数据,您需要一个 id 或索引,对吗? 但是身份证最好。 您正在传递带有 id 的 function 但您没有 id 用于通过,您必须将 id 传递给该组件。 你的代码<Recipe key={recipe.id} {...recipe} handleRecipeDelete={handleRecipeDelete}/>
新代码替换 {...recipe} -> id={recipe.id} <Recipe key={recipe.id} id={recipe.id} handleRecipeDelete={handleRecipeDelete}/>
并在 Recipe 组件上接收 id 作为参数 Recipe({id, handleRecipeDelete}),您的代码将正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.