如何在响应中向组件添加CSS类? [英] how to add css classes to a component in react?
问题描述
所以基本上我在做什么是遍历数据数组并创建某种列表。我要在这里实现的是单击CSS类应附加的特定列表项。
So basically what I am doing is iterating through an array of data and making some kind of list. What I want to achieve here is on clicking on a particular list item a css class should get attached.
迭代生成列表
var sports = allSports.sportList.map((sport) => {
return (
<SportItem icon= {sport.colorIcon} text = {sport.name} onClick={this.handleClick()} key= {sport.id}/>
)
})
单个列表项
<div className="display-type icon-pad ">
<div className="icons link">
<img className="sport-icon" src={icon}/>
</div>
<p className="text-center">{text}</p>
</div>
我无法弄清楚处理handleClick的方法,因此如果我单击特定列表
I am not able to figure out what to do with handleClick so that If I click on a particular list it gets highlighted.
推荐答案
保持单独的状态变量,用于可以选择并使用类名库,以便有条件地将类作为facebook 推荐。
Keep a separate state variable for every item that can be selected and use classnames library to conditionally manipulate classes as facebook recommends.
编辑:好的,您提到一次只能选择1个元素,这意味着我们只需要存储其中一个即可被选中(我将使用所选项目的ID)。而且我还注意到您的代码中有一个错字,您需要在声明组件时链接该函数,而不是调用它
ok, you've mentioned that only 1 element can be selected at a time,it means that we only need to store which one of them was selected (I'm going to use the selected item's id). And also I've noticed a typo in your code, you need to link the function when you declare a component, not call it
<SportItem onClick={this.handleClick} ...
(请注意 handleClick
不再包含()
)。
现在将使用handleClick 处理程序nofollow>部分应用-绑定
方法:
And now we're going to pass the element's id along with the event to the handleClick
handler using partial application - bind
method:
<SportItem onClick={this.handleClick.bind(this,sport.id} ...
就像我说过的那样,我们想在状态中存储所选商品的ID,因此 handleClick
可能看起来像:
And as I said we want to store the selected item's id in the state, so the handleClick
could look like:
handleClick(id,event){
this.setState({selectedItemId: id})
...
}
现在我们需要将 selectedItemId
传递给 Spor tItem
实例,以便他们知道当前的选择:< SportItem selectedItemId = {selectedItemId} ...
。此外,不要忘记将 onClick = {this.handleClick}
回调附加到需要的位置,调用该方法将触发父状态的更改:
Now we need to pass the selectedItemId
to SportItem
instances so they're aware of the current selection: <SportItem selectedItemId={selectedItemId} ...
.Also, don't forget to attach the onClick={this.handleClick}
callback to where it needs to be, invoking which is going to trigger the change of the state in the parent:
<div onClick={this.props.onClick} className={classNames('foo', { myClass: this.props.selectedItemId == this.props.key}); // => the div will always have 'foo' class but 'myClass' will be added only if this is the element that's currently selected}>
</div>
这篇关于如何在响应中向组件添加CSS类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!