2017-09-13 66 views
-1

我需要更新CSS,自然我使用jQuery,但我被告知不要在React中使用jQuery。- 如何在我的React組件中轉換jQuery代碼?

我該如何正確地做到這一點。如果需要,我可以添加更多的代碼。我只是簡單地切換一個div的底部邊框

toggleMarker() { 
    if (this.state.previous && (this.state.current !== this.state.previous)) { 
     $('#nav_' + this.state.previous).css("border-bottom", ''); 
    } 
    if (this.state.previous !== this.state.current) { 
     $('#nav_' + this.state.current).css("border-bottom", this.color); 
    } 
    this.setState({previous: this.state.current}); 
    } 
+0

你給不使用jQuery的原因是什麼? –

回答

2

您可以在行內操作組件樣式,並且可以根據狀態變量給出條件。

render(){ 
    return(
     <div style={{ borderBottom: ((this.state.previous && (this.state.current !== this.state.previous)) ? 'none' : 1) }}> 
      // ... 
     </div> 
    ) 
} 
0

當談到反應,有很多方法來樣式包括內聯樣式的成分,在CSS和進口定義樣式,使用樣式組件,並使用一些小JS庫例如classnames

classnames支持任何JS表達式作爲HTML元素的類名稱。您可以使用上述鏈接探索更多內容。

只是一個簡單的例子:

import styles from './yourcss.css' 
import { classnames } from './classnames/bind' 
const cx = classnames.bind(styles) 

<div className={cx('divStyle')}> 
</div> 
0

我會建議有在該州從可變基準內聯CSS。考慮這個,

//define state 
this.state={ 
    toggleState : false} 

//have toggler function 
togglerFunction(){ 
    var temp = this.state.toggleState 
    this.setState({ 
     toggleState : !temp}) 
} 

//in render you can have your element like this 
render(){ 
... 
//start of your element suppose a div 
{this.state.toggleState == false ? <div style=   
{{borderBottom:"YourValueForFalseHere"}}></div>:<div style=     
{{borderBottom:"YourValueForTrueHere"}}></div>} 
//...End of your element 
... 
}