【问题标题】:Remove backgroundImage on componentDidMount删除 componentDidMount 上的 backgroundImage
【发布时间】:2016-11-24 14:56:06
【问题描述】:

我目前有一个<Login/> 页面和一个<Dashboard/>

登录页面的背景为#222,当您登录时,Dashboard 的背景为whitesmoke

我这样做的方式是在 body css 上使用它:

body {
    background-color: #222222;
}

这个在Dashboard.js:

componentWillMount() {
  document.body.style.backgroundColor = "whitesmoke";
}
componentWillUnmount() {
    document.body.style.backgroundColor = null;
}

到目前为止,这是有效的。但是我现在在登录页面上有一个图像作为我的背景,如下所示:

body {
    background-color: #222222;
    background: url('../../public/img/bg.png');
    background-repeat: repeat;
}

但我的仪表板继承了背景图像,即使我放了这样的东西:

componentWillMount() {
  document.body.style.backgroundImage = null;
  document.body.style.backgroundColor = "whitesmoke";
}
componentWillUnmount() {
  document.body.style.backgroundColor = null;
}

我该如何解决这个问题? 谢谢

【问题讨论】:

  • null 不是 backgroundImage 的有效值,它会被浏览器忽略。使用document.body.style.backgroundImage = 'none';

标签: javascript css reactjs


【解决方案1】:

为什么不使用类呢?


componentWillMount() {
  $('body').addClass('has-background');
}
componentWillUnmount() {
  $('body').removeClass('has-background');
}

此外,您可能希望抽象出那些 addClass / removeClass 并使用 emits

【讨论】:

    猜你喜欢
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-03
    • 1970-01-01
    • 2015-01-04
    相关资源
    最近更新 更多