首頁  >  文章  >  web前端  >  如何在 React 元件中有條件地應用類別屬性?

如何在 React 元件中有條件地應用類別屬性?

Susan Sarandon
Susan Sarandon原創
2024-10-26 02:24:27852瀏覽

How to Conditionally Apply Class Attributes in React Components?

在React 中有條件地應用類別屬性

在React 中,經常需要根據從父組件傳遞的值有條件地顯示或隱藏元素。這可以透過操作子組件的類別屬性來實現。

範例:

<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>
        );
      }
    });

說明:

在React 中有條件地應用類別屬性的關鍵是在className 屬性的大括號內使用條件(三元)運算子。在此範例中,如果 this.props.showBulkActions 為 true,則套用顯示類,否則套用隱藏類別。

注意: 確保大括號位於字串之外,如上例所示。否則,表達式將被計算為字串,並且將不會套用所需的類別名稱。

以上是如何在 React 元件中有條件地應用類別屬性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn