我想有条件地显示和隐藏这个按钮组,这取决于从父组件传入的内容,看起来像这样:

    <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'}。我做错什么了吗?


当前回答

基于this.props.showBulkActions的值,您可以动态地切换类,如下所示。

<div ...{...this.props.showBulkActions 
? { className: 'btn-group pull-right show' } 
: { className: 'btn-group pull-right hidden' }}>

其他回答

更优雅的解决方案,更有利于维护和可读性:

const classNames = ['js-btn-connect'];

if (isSelected) { classNames.push('is-selected'); }

<Element className={classNames.join(' ')}/>

替换:

<div className="btn-group pull-right {this.props.showBulkActions ? 'show' : 'hidden'}">`

:

<div className={`btn-group pull-right ${this.props.showBulkActions ? 'show' : 'hidden'}`}

你可以使用这个npm包。它处理所有事情,并基于变量或函数为静态类和动态类提供选项。

// Support for string arguments
getClassNames('class1', 'class2');

// support for Object
getClassNames({class1: true, class2 : false});

// support for all type of data
getClassNames('class1', 'class2', null, undefined, 3, ['class3', 'class4'], { 
    class5 : function() { return false; },
    class6 : function() { return true; }
});

<div className={getClassNames('show', {class1: true, class2 : false})} /> // "show class1"

根据@spitfire109的回答,我们可以这样做:

rootClassNames() {
  let names = ['my-default-class'];
  if (this.props.disabled) names.push('text-muted', 'other-class');

  return names.join(' ');
}

然后在渲染函数中:

<div className={this.rootClassNames()}></div>

保持JSX简短

花括号在字符串内部,因此它被计算为字符串。他们需要在外面,所以这个应该有用:

<div className={"btn-group pull-right " + (this.props.showBulkActions ? 'show' : 'hidden')}>

注意“右拉”后面的空格。您不希望意外地提供类“拉右秀”而不是“拉右秀”。括号也要在这里。