2017-07-28 60 views
0

當我嘗試通過更改用戶mouseOver按鈕時的狀態來更改本節的樣式時,這很奇怪。 h1標籤的內容已更改,但款式不是。有人可以幫助我嗎?更改狀態但不改變樣式Reactjs

export class Jumbotron extends Component { 

    constructor (props) { 
    super(props) 
    this.state = { 
     style: { 
     backgroundImage: 'none' 
     } 
    } 

    this.handleSubjectMouseOver = this.handleSubjectMouseOver.bind(this) 
    } 

    handleSubjectMouseOver (bg) { 
    console.log(bg) 
    this.setState({ 
     style: { 
     backgroundImage: bg 
     } 
    }) 
    } 

    render() { 
    return <section className="jumbotron container" style= 
    {this.state.style}> 
     <h1>{this.state.style}</h1> 
     <div className="jumbotron-content"> 
     <h2 style={{marginBottom: 3, marginTop: 40}}>Learning is fun with 
     LIVE</h2> 
     <div style={{marginLeft: 10}}>Body ........</div> 
     <div style={{marginBottom: 20, marginTop: 80}} 
      className="subjects-title">TOP CLASSES, TUTORIAL & TIPS TO EXCEL IN: 
     </div> 
     <div className="subjects" style={{backgroundImage: this.state.background}}> 
      <RaisedButton label="MATH" secondary onMouseMove={() => { this.handleSubjectMouseOver(mathBg) }} /> 
      <RaisedButton label="PHYSICS" secondary onMouseMove={() => { this.handleSubjectMouseOver(physicBg) }} /> 
      <RaisedButton label="CHEMISTRY" secondary onMouseMove={() => { this.handleSubjectMouseOver(chemistryBg) }} /> 
      <RaisedButton label="BIOLOGY" secondary onMouseMove={() => { this.handleSubjectMouseOver(biologyBg) }} /> 
      <RaisedButton label="COMP SCIENCE" secondary 
         onMouseMove={() => { this.handleSubjectMouseOver(computerBg) }} /> 
     </div> 
     </div> 
    </section> 
    } 
+2

昨天我有這個問題,而不是直接改變CSS。讓你的CSS有兩個不同的類,在事件發生變化時,切換這些類。另外,確保你有檢查狀態變化的條件,你是否在你的代碼中這樣做? – Legolas

+0

在我的情況下,我沒有任何有條件的渲染。因爲背景圖像的數量是動態的。我不能在這裏使用課程。 :( –

+1

您能否發佈一些更詳細的代碼,以便我能夠理解問題所在? – Legolas

回答

1

使用以下命令行的部位設定背景圖片

style={{'backgroundImage': 'url('+this.state.background+')'}} 

要在這個細節讀更多here & here的。

並且還檢查webpack的css-loader問題到here

希望這會幫助你!

0

代碼沒什麼問題,只是因爲一個簡單的原因你的事件沒有被觸發。

<RaisedButton onMouseMove={() => { this.handleSubjectMouseOver(mathBg) }} /> 

這裏,RaisedButton是不是原生的DOM元素,這完全取決於你如何定義它。在這裏,您提供的mouseOver事件只是一個屬性,並不算作事件。爲了解決這個問題,你需要將一個事件傳遞給一個本地DOM元素,將你的組件包裹在一個div上,並將事件傳遞給它,就像這樣。

<div className="raisedButtonClass" onMouseMove={someFunction}> 
    <RaisedButton ......./> 
</div> 

我希望這能解決你的問題:)

+0

我可以確保這個事件被觸發,因爲它記錄了,當mouseOver這個組件時,標籤p的值發生了變化。 ^^ –

+0

問題是CSS:[backgroundImage](https://developer.mozilla.org/en-US/docs/Web/CSS/background-image) – btzr

+0

他傳遞一個匿名函數,所以它應該工作 – btzr