我想有条件地显示和隐藏这个按钮组,这取决于从父组件传入的内容,看起来像这样:
<TopicNav showBulkActions={this.__hasMultipleSelected} />
__hasMultipleSelected: function() {
return false; //return true or false depending on data
}
var TopicNav = React.createClass({
render: function() {
return (
<div className="row">
<div className="col-lg-6">
<div className="btn-group pull-right {this.props.showBulkActions ? 'show' : 'hidden'}">
<button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
Bulk Actions <span className="caret"></span>
</button>
<ul className="dropdown-menu" role="menu">
<li><a href="#">Merge into New Session</a></li>
<li><a href="#">Add to Existing Session</a></li>
<li className="divider"></li>
<li><a href="#">Delete</a></li>
</ul>
</div>
</div>
</div>
);
}
});
然而,{this.props。showBulkActions吗?'show': 'hidden'}。我做错什么了吗?
正如其他人评论的那样,classnames实用程序是目前在ReactJs中处理条件CSS类名的推荐方法。
在你的例子中,解决方案看起来像:
var btnGroupClasses = classNames(
'btn-group',
'pull-right',
{
'show': this.props.showBulkActions,
'hidden': !this.props.showBulkActions
}
);
...
<div className={btnGroupClasses}>...</div>
顺便说一句,我建议您尽量避免同时使用show类和hidden类,这样代码就会更简单。大多数情况下,您不需要为默认显示的内容设置类。
2021年附录:为了提高性能,您可以将CLSX作为替代方案。
我已经试图调整我的答案,以包括所有最好的解决方案。
有很多不同的方法可以做到这一点。
1. 类内嵌
<div className={`... ${this.props.showBulkActions ? 'show' : 'hidden'}`}>
...
</div>
2. 使用值
var btnClass = classNames(
...
{
'show': this.props.showBulkActions,
'hidden': !this.props.showBulkActions
}
);
3.使用变量
let dependentClass = this.props.showBulkActions ? 'show' : 'hidden';
className={`... ${dependentClass }`}
4. 使用clsx
<div className={clsx('...',`${this.props.showBulkActions ? 'show' : 'hidden'}`)}>
...
</div>
<div className={['foo', condition && 'bar'].filter(Boolean).join(' ')} />
.filter(Boolean)从数组中删除“错误”值。由于类名必须是字符串,因此任何字符串以外的内容都不会包含在新的筛选数组中。
console.log(['foo', true && 'bar'].filter(Boolean)。Join (' '))
console.log(['foo', false && 'bar'].filter(布尔值)。Join (' '))
上面写为函数:
const cx = (...list) => list.filter(Boolean).join(' ')
// usage:
<div className={cx('foo', condition && 'bar')} />
var cx = (.. list) => list.filter(布尔兰)。join (' ')
1、log (ex(’foo’&&游戏机’bar’,1 &&’baz’))
log (ex(’foo’游戏机,0 &&’bar’,1 &&’baz’))
log (ex(’foo’游戏机,0 &&’bar’,0 &&’baz’))
如果你正在使用一个转译器(如Babel或Traceur),你可以使用新的ES6“模板字符串”。
以下是@spitfire109的答案,经过了相应的修改:
<div className={`btn-group pull-right ${this.props.showBulkActions ? 'shown' : 'hidden'}`}>
这个方法允许你做一些简洁的事情,呈现s-is-show或s-is-hidden:
<div className={`s-${this.props.showBulkActions ? 'is-shown' : 'is-hidden'}`}>