2017-07-28 48 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