How to add multiple classes to a ReactJS Component?(如何向 ReactJS 组件添加多个类?)
问题描述
I am new to ReactJS and JSX and I am having a little problem with the code below.
I am trying to add multiple classes to the className
attribute on each li
:
<li key={index} className={activeClass, data.class, "main-class"}></li>
My React component is:
var AccountMainMenu = React.createClass({
getInitialState: function() {
return { focused: 0 };
},
clicked: function(index) {
this.setState({ focused: index });
},
render: function() {
var self = this;
var accountMenuData = [
{
name: "My Account",
icon: "icon-account"
},
{
name: "Messages",
icon: "icon-message"
},
{
name: "Settings",
icon: "icon-settings"
}
/*{
name:"Help & Support <span class='font-awesome icon-support'></span>(888) 664.6261",
listClass:"no-mobile last help-support last"
}*/
];
return (
<div className="acc-header-wrapper clearfix">
<ul className="acc-btns-container">
{accountMenuData.map(function(data, index) {
var activeClass = "";
if (self.state.focused == index) {
activeClass = "active";
}
return (
<li
key={index}
className={activeClass}
onClick={self.clicked.bind(self, index)}
>
<a href="#" className={data.icon}>
{data.name}
</a>
</li>
);
})}
</ul>
</div>
);
}
});
ReactDOM.render(<AccountMainMenu />, document.getElementById("app-container"));
I use classnames when there is a fair amount of logic required for deciding the classes to (not) use. An overly simple example:
...
var liClasses = classNames({
'main-class': true,
'activeClass': self.state.focused === index
});
return (<li className={liClasses}>{data.name}</li>);
...
That said, if you don't want to include a dependency then there are better answers below.
这篇关于如何向 ReactJS 组件添加多个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何向 ReactJS 组件添加多个类?


基础教程推荐
- Bokeh Div文本对齐 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01