gpt4 book ai didi

javascript - 如何向 ReactJS 组件添加多个类?

转载 作者:IT老高 更新时间:2023-10-28 13:12:28 25 4
gpt4 key购买 nike

我是 ReactJS 和 JSX 的新手,我对下面的代码有一点问题。

我正在尝试向每个 liclassName 属性添加多个类:

<li key={index} className={activeClass, data.class, "main-class"}></li>

我的 React 组件是:

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 &amp; Support &nbsp; <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"));

最佳答案

我使用 ES6 template literals .例如:

const error = this.state.valid ? '' : 'error'
const classes = `form-control round-lg ${error}`

然后渲染它:

<input className={classes} />

单行版本:

<input className={`form-control round-lg ${this.state.valid ? '' : 'error'}`} />

关于javascript - 如何向 ReactJS 组件添加多个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34521797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com