【发布时间】:2016-07-18 09:30:00
【问题描述】:
我有一个显示标签列表的组件,用户可以选择标签来关注它们。所以当用户点击一个标签时,我想把它存储在tagsSelectedList中并添加一个新的类名selected_tag。但如果标签已经存在于 tagsSelectedList 中,请从 tagsSelectedList 中删除该标签,同时删除类名 selected_tag。
我很困惑如何检查标签对象是否存在于 tagSelectedList 中并从列表中删除该特定标签项。我怎么做?您的帮助和指导将不胜感激。谢谢。
component.js:
let tags = [
{id: "1", tagName: "Arts"},
...
...
{id: "59", tagName: "Writing"}
];
var tagsSelectedList = [];
export default class SignUpSubscribeTags extends React.Component {
constructor(props){
super(props);
}
selectTag = (e) => {
// if the tag is not present in the tagsSelectedList then add the tag in the tagsSelectedList also add the tag_selected class name
var isTagPresent = tagsSelectedList.filter(function(item) {
return item.id === e.target.dataset.pk
});
if(isTagPresent) {
console.log(e.target.dataset.pk, 'present in tagsSelectedList');
}
else {
console.log(e.target.dataset.pk, 'not present in tagsSelectedList');
}
// if the tag is present in tagsSelectedList then remove the tag object from the tagsSelectedList also remove the tag_selected class name
}
render() {
let tagList = tags.map((Tag) => {
return (
<li id={Tag.tagName} class="tag" data-pk={ Tag.id } key={Tag.id} onClick={this.selectTag}>{Tag.tagName}</li>
);
});
return(
<div id="signup-process-wrapper-addTags">
<div id="add_tags">
<ul id="tag_list">
{tagList}
</ul>
</div>
</div>
);
}
}
【问题讨论】:
-
你在项目中使用 underscore.js/lodash.js 吗?
-
这可能会有所帮助:stackoverflow.com/a/2155786/3783478
标签: javascript arrays object reactjs