我想将背景图像应用于仅一个组件的主体

问题描述 投票:0回答:1

我对React非常陌生,因此请您为错误事先表示歉意。

在我的React应用中,说我有2个组件,并且CSS样式是全局的,它从所有文件中拾取CSS样式。

但是,我希望将完整的背景图像添加到我可以通过在CSS文件中使用此代码实现的组件之一:

body {
  background-image: url("../image.jpg");
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

问题在于,同一图像也被应用于另一个组件。我阅读了一些答案,发现可以使用ComponentDidMount挂钩并将图像添加到此处的body标签中。我试过了,但是什么也没显示。

  componentDidMount() {
    document.body.style.backgroundImage = "url('../image.jpg')";
    document.body.style.backgroundPosition = "center";
    document.body.style.backgroundRepeat = "no-repeat";
    document.body.style.backgroundSize = "cover";
  }

编辑

我意识到我对这个问题的措词有误。我的意思是说我在React中有两个页面。对于其中一页,我需要完整的背景图像。但是,由于CSS样式是全局样式,因此背景图片将应用于所有页面。

css reactjs
1个回答
0
投票

您可以通过向一个组件的顶部元素分配特定的类或ID来使用内联样式或特定样式。

INLINE STYLING Example:

// If Background variable has url to the background image.
const style = {
  backgroundImage: `url(${Background})`
}


// in component use that inline style

return (
<div style={style}></div>
);

如果您只想和身体一起工作...然后将一个类添加到组件A安装的主体上,并删除组件B安装的主体。并将background属性附加到该类。

© www.soinside.com 2019 - 2024. All rights reserved.