【问题标题】:Change state but don't change style Reactjs更改状态但不更改样式 Reactjs
【发布时间】:2017-07-28 03:57:29
【问题描述】:

当我尝试通过更改用户 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>
  }

【问题讨论】:

  • 我昨天遇到了这个问题,而不是直接更改 CSS。让您的 CSS 有两个不同的类,并在事件更改时切换这些类。另外,请确保您有检查状态更改的条件,您是否在代码中这样做?
  • 就我而言,我没有任何条件渲染。因为背景图片的数量是动态的。我不能在这里使用课程。 :(
  • 您能否发布一些更详细的代码,以便我了解问题所在?
  • style={{'backgroundImage': 'url('+this.state.background+')'}} 如果背景包含图片路径,则使用这个
  • 请告诉我它对你有没有帮助

标签: css reactjs state


【解决方案1】:

使用下面一行代替设置背景图片

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

如需了解更多详情,请发送至herehere

还要检查 webpack 的 css-loader 问题到here

希望对您有所帮助!

【讨论】:

    【解决方案2】:

    代码通常没有任何问题,只是由于一个简单的原因,您的事件没有触发。

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

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

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

    我希望这能解决你的问题:)

    【讨论】:

    • 我可以确保触发此事件,因为当我将鼠标悬停在此组件上时,它会记录并且标记 p 的值会发生变化。 ^^
    • 问题是css:backgroundImage
    • 他正在传递一个匿名函数,所以它应该可以工作
    猜你喜欢
    • 1970-01-01
    • 2016-10-02
    • 2014-04-13
    • 2018-07-08
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 2022-11-06
    • 2014-01-01
    相关资源
    最近更新 更多