[英]How to get onClick in React to work on a single element with multiple siblings?
I am new to React and have a problem with trying to fire an onClick event.我是 React 新手,在尝试触发 onClick 事件时遇到问题。 I have the event working, when it gets clicked, the div appears and reappears.
我有事件工作,当它被点击时,div 出现并重新出现。 The problem that is that if I press a button for a particular item, all of the divs appear instead of the div that I just clicked the button on.
问题是,如果我按下特定项目的按钮,则会出现所有 div,而不是我刚刚单击按钮的 div。 How do I make it so that that the button I clicked on will only fire on that particular element.
如何使我单击的按钮仅在该特定元素上触发。
Here is my code:这是我的代码:
class App extends React.Component { class 应用扩展 React.Component {
constructor(props) {
super(props)
this.state = {
userInput: '',
getRecipe: [],
ingredients: "none"
}
}
handleChange = (e) => {
this.setState({
userInput: e.target.value
})
}
handleSubmit = (e) => {
e.preventDefault()
const getData = () => {
fetch(`https://api.edamam.com/search?q=${this.state.userInput}&app_id=${APP_ID}&app_key=${APP_KEY}&from=0&to=18`)
.then(res => {
return res.json()
}).then(data => {
this.setState({
getRecipe: data.hits
})
})
}
getData()
}
// this is where the button logic comes in
getIngredients = (e) => {
e.preventDefault()
if (this.state.ingredients === 'none') {
this.setState({
ingredients: "block"
})
} else {
this.setState({
ingredients: "none"
})
}
}
render() {
return (
<div className="recipes">
<Nav changed={this.handleChange} submit={this.handleSubmit} />
<Content
userInput={this.state.userInput}
recipe={this.state.getRecipe}
getIngredients={this.getIngredients}
ingredients={this.state.ingredients} />
</div>
)
}
}
const Content = ({ userInput, recipe, getIngredients, ingredients }) => {
return (
<div>
<h2 className="userinputtitle"> {userInput} </h2>
<div className="containrecipes">
{recipe.map(rec => {
return (
<div key={rec.recipe.label} className="getrecipes">
<h1 className="recipetitle" key={rec.recipe.label}>{rec.recipe.label.toUpperCase()}</h1>
<img src={rec.recipe.image}></img>
<h4 className="health"> Health Labels: {rec.recipe.healthLabels.join(', ')}</h4>
<h4 > Diet Label: {rec.recipe.dietLabels}</h4>
<h4 > Calories: {Math.floor(rec.recipe.calories)}</h4>
<h4 className="cautions"> Cautions: {rec.recipe.cautions}</h4>
<div>
<h4>{rec.recipe.digest[0].label + ":" + " " + Math.floor(rec.recipe.digest[0].total) + "g"}</h4>
<h4>{rec.recipe.digest[1].label + ":" + " " + Math.floor(rec.recipe.digest[1].total) + "g"}</h4>
<h4>{rec.recipe.digest[2].label + ":" + " " + Math.floor(rec.recipe.digest[2].total) + "g"}</h4>
</div>
// the button is clicked here, yet all div fire at the same time
<button onClick={getIngredients} className="getingredients">Ingredients</button>
{rec.recipe.ingredients.map(i => {
return (
<div style={{ display: ingredients }} className="containingredients">
< ul className="ingredients">
<li className="ingredient">{i.text}</li>
</ul>
</div>
)
})}
</div>
)
})}
</div>
</div>
)
}
Update getIngredients
to consume also a recipe ID and save that in state instead.更新
getIngredients
以使用配方 ID 并将其保存在 state 中。
this.state = {
userInput: '',
getRecipe: [],
ingredientsId: null
}
...
getIngredients = recipeId => e => {
e.preventDefault();
this.setState(prevState => ({
ingredientsId: prevState.ingredientsId ? null : recipeId,
}));
}
...
<Content
userInput={this.state.userInput}
recipe={this.state.getRecipe}
getIngredients={this.getIngredients}
ingredientsId={this.state.ingredientsId} // <-- pass id
/>
Conditionally set the display style in Content
.有条件地在
Content
中设置显示样式。
const Content = ({ userInput, recipe, getIngredients, ingredientsId }) => {
...
<button
onClick={getIngredients(recipe.id)} // <-- pass id
className="getingredients"
>
Ingredients
</button>
<div
style={{
// set display style
display: ingredientsId === recipe.id ? "block" : "none"
}}
className="containingredients"
>
<ul className="ingredients">
<li className="ingredient">{i.text}</li>
</ul>
</div>
...
Same as above with minor changes与上述相同,略有改动
State is map State 是 map
this.state = {
userInput: '',
getRecipe: [],
ingredientsId: {},
}
Toggle id in handler在处理程序中切换 id
getIngredients = recipeId => e => {
e.preventDefault();
this.setState(prevState => ({
ingredientsId: {
...prevState.ingredientsId,
[recipeId]: !prevState.ingredientsId[recipeId]
},
}));
}
Look up recipeId in passed map在传递的 map 中查找 recipeId
style={{
// set display style
display: ingredientsId[recipe.id] ? "block" : "none"
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.