我是 ReactJS 和 JSX 的新手,我对下面的代码有一点问题。
我正在尝试为className每个属性添加多个类li:
className
li
<li key={index} className={activeClass, data.class, "main-class"}></li>
我的反应组件是:
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"));
当决定(不)使用的类需要大量逻辑时,我会使用类名。一个 过于简单的例子 :
... var liClasses = classNames({ 'main-class': true, 'activeClass': self.state.focused === index }); return (<li className={liClasses}>{data.name}</li>); ...
也就是说,如果您不想包含依赖项,那么下面有更好的答案。