1. 程式人生 > >react之應用多個類名

react之應用多個類名

react開發過程中,經常會需要動態向元素內新增樣式style或className,那麼應該如何動態新增呢???

一、react向元素內,動態新增style

例如:有一個DIV元素, 需要動態新增一個 display:block | none 樣式, 那麼:

<div style={{display: (index===this.state.currentIndex) ? "block" : "none"}}>此標籤是否隱藏</div>

或者, 多個樣式寫法:

<div style={{display: (index===this.state.currentIndex) ? "block" : "none", color:"red"}}>此標籤是否隱藏</div>

二、react向元素內,動態新增className

比如:

1、DIV標籤中,沒有其他class,只需要動態新增一個.active的className,來顯示內容是否被選中狀態,則:

<div className={index===this.state.currentIndex?"active":null}>此標籤是否選中</div>

2、如果DIV標籤本身有其他class,又要動態新增一個.active的className,來顯示內容是否被選中狀態,則:

<div className={["container tab", index===this.state.currentIndex?"active":null].join(' ')}>此標籤是否選中</div>

或者,使用ES6寫法(推薦使用ES6寫法):

<div className={`container tab ${index===this.state.currentIndex?"active":null}`}>此標籤是否選中</div>

轉自  https://blog.csdn.net/suwyer/article/details/81481507