我不知道如何只为单击的元素切换类。我该如何指出我只想为单击的元素更改类的反应。我该怎么办?
import React, { Component } from "react";
class RecipesList extends Component {
state = {
hasClass: false
};
toggleActive = () => {
this.setState({
hasClass: true
});
};
render() {
const { recipesList } = this.props;
const { hasClass } = this.state;
return (
<ul className="recipiesList">
{recipesList.map(item => (
<li
className={hasClass ? "active" : ""}
key={item.recipe_id}
onClick={this.toggleActive}
>
</li>
))}
</ul>
);
}
}
export default RecipesList;
答案 0 :(得分:0)
现在,您对所有商品都使用一个标志。如果要为每个项目标记,则有两个选择:
Recipe
组件:class Receipt extends Component {
constructor(props) {
this.state = {active: false};
this.toggleActive = this.toggleActive.bind(this);
}
toggleActive() {
this.setState(({active}) => ({active: !active}));
}
render() {
const {active} = this.state;
const {id} = this.props;
return <li
className={active ? "active" : ""}
key={id}
onClick={this.toggleActive}
/>;
}
}
class RecipesList extends Component {
state = {
hasClass: false
};
toggleActive = () => {
this.setState({
hasClass: true
});
};
render() {
const { recipesList } = this.props;
const { hasClass } = this.state;
return (
<ul className="recipiesList">
{recipesList.map(item => <Recipe id={item.recipe_id} />)}
</ul>
);
}
}
class RecipesList extends Component {
state = {
active: new Map()
};
toggleActive = (id) => {
this.setState(({active}) => {
active = new Map(active);
active.set(id, !active.get(id));
return {active};
});
};
render() {
const { recipesList } = this.props;
const { hasClass } = this.state;
return (
<ul className="recipiesList">
{recipesList.map(item => (
<li
className={hasClass ? "active" : ""}
key={item.recipe_id}
onClick={this.toggleActive.bind(null, item.recipe_id)}
>
</li>
))}
</ul>
);
}
}
答案 1 :(得分:0)
首先,您需要一个状态,将其称为activeItemId
,该状态存储所选项目的ID(此处为recipe_id)。那么您必须像这样className={this.state.activeItemId === item.recipe_id ? 'active' : ''}
更改className,这有助于我们仅将active
类赋予所选项目。然后,您要做的就是将recipe_id
传递到toggleActive函数(onClick={() => this.toggleActive(item.recipe_id)}
)并将其更改为:
toggleActive = (id) => {
this.setState({
activeItemId: id
});
};
因此,每次单击某个项目时,它的id
都以activeItem
状态存储,并且项目className
变为'active
',这是因为它的recipe_id等于activeItemId
所以在一起:
import React, { Component } from "react";
class RecipesList extends Component {
state = {
activeItemId: null
};
toggleActive = (id) => {
this.setState({
activeItemId: id
});
};
render() {
const { recipesList } = this.props;
const { activeItemId } = this.state;
return (
<ul className="recipiesList">
{recipesList.map(item => (
<li
className={activeItemId === item.recipe_id ? "active" : ""}
key={item.recipe_id}
onClick={() => this.toggleActive(item.recipe_id)}
>
</li>
))}
</ul>
);
}
}
export default RecipesList;