改变状态但不改变风格Reactjs

时间:2017-07-28 03:57:30

标签: css reactjs state

当我尝试通过在用户mouseOver按钮时更改状态来更改此部分的样式时,这很奇怪。 h1标签的内容已更改,但该部分的样式不是。有人可以帮我吗?

    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 个答案:

答案 0 :(得分:1)

使用以下行代替设置背景图像

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

要详细了解详情,请here&amp; here

并检查webpack的css-loader问题到here

希望这会对你有帮助!

答案 1 :(得分:0)

代码没有什么特别的错误,只是因为一个简单的原因你的事件没有被解雇。

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

在这里,RaisedButton不是本机DOM元素,它完全取决于您如何定义它。在这里,您提供的mouseOver事件只是一个属性,并不算作事件。要解决此问题,您需要将事件传递给本机DOM元素,将组件包装在div周围并将事件传递给它,就像这样。

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

我希望这可以解决您的问题:)