我有一个子组件,该子组件可以映射items
数组中的图像。单击任何项目后,我会调用addFavorite
,它是从父级传入的。
我试图找到一种方法,也可以将className添加到 only 仅单击的特定图像。我尝试过的任何方法都会在onClick上将类添加到所有映射的元素中。
var classNames = require('classnames');
class Results extends Component {
render() {
let items = this.props.items
var resultClass = classNames({
'result': true,
});
return (
<div className="resultst" key="results">
{items.map(item =>
<div className = {resultClass}
key={item.id}
onClick= {() => {
this.props.addFavorite(item)
}
}>
<img alt= "" src={item.images.downsized.url} />
</div>
)}
</div>
);
}
}
答案 0 :(得分:0)
您可以在父组件中创建一个单独的favorites
数组,在其中存储所有喜欢的项目,然后将其发送到子组件,并查看该项目是否包含在favorites
数组中:
示例
class App extends Component {
state = {
items: [{ id: 1, text: "item 1" }, { id: 2, text: "item 2" }],
favorites: []
};
addFavorite = item => {
const { items, favorites } = this.state;
const copyFavorites = [...favorites];
if (!favorites.some(favorite => favorite.id === item.id)) {
copyFavorites.push(item);
this.setState({ favorites: copyFavorites });
}
};
render() {
const { items, favorites } = this.state;
const { addFavorite } = this;
return (
<div>
<Results
items={items}
favorites={favorites}
addFavorite={addFavorite}
/>
</div>
);
}
}
class Results extends Component {
render() {
const { items, favorites, addFavorite } = this.props;
return (
<div>
{items.map(item => (
<div
key={item.id}
onClick={() => {
addFavorite(item);
}}
>
{favorites.includes(item) && 'Favorite: '}
{item.text}
</div>
))}
</div>
);
}
}