如何在React内联样式中设置背景图片?
在ReactJS中,我们可以使用CSS的‘backgroundImage’属性来为组件或特定的HTML元素(如div)设置背景图片。在这里,我们将学习如何使用内联样式来设置背景图片。
此外,我们将使用绝对和相对URL来设置背景图片。
语法
用户可以按照以下语法使用React内联样式来设置背景图片。
<div Style = {{ backgroundImage: 'url("image-url")', }} > Div content </div>
在上面的语法中,我们使用了‘backgroundImage’ CSS属性来为div元素设置背景图片。
示例
我们在下面的示例中创建了div元素并应用了内联CSS。我们使用URL设置了背景图片。此外,我们还使用CSS设置了div元素的高度和宽度。此外,我们还为背景图片设置了一些CSS属性。
import React from "react";
export default function App() {
return (
<div>
<h2>
{" "}
Using the <i> React inline styles </i> to set a background image
</h2>
<br></br>
<div
class = "image"
style = {{
height: "350px",
width: "550px",
backgroundImage:
'url("https://is2-ssl.mzstatic.com/image/thumb/Purple123/v4/b2/1f/21/b21f21a8-e4f6-b7d2-1fec-8e5430273077/AppIcon-0-0-1x_U007emarketing-0-0-0-7-0-0-sRGB-0-0-0-GLES2_U002c0-512MB-85-220-0-0.png/1200x630wa.png")',
backgroundSize: "contain",
backgroundRepeat: "no-repeat",
}}
>
This div contains a background image.
</div>
</div>
);
}
输出

示例
在下面的示例中,我们在函数组件的return语句之外创建了imageStyle对象。我们在imageStyle对象中添加了背景图片。
之后,我们将imageStyle对象用作div的内联样式。在输出中,用户可以看到div元素的背景图片。
import React from "react";
export default function App() {
let imageStyle = {
height: "350px",
width: "600px",
backgroundImage:
'url("https://img.freepik.com/free-photo/wide-angle-shot-singletree-growing-clouded-sky-during-sunset-surrounded-by-grass_181624-22807.jpg")',
backgroundSize: "contain",
backgroundRepeat: "no-repeat",
color: "white",
};
return (
<div>
<h2>
{" "}
Using <i> React inline styles </i> to set a background image
</h2>
<br></br>
<div class = "image" style = {imageStyle}>
This div contains a background image.
</div>
</div>
);
}
输出

示例
在下面的示例中,我们使用了相对URL来设置背景图片。用户可以将图片添加到React应用程序的‘public’目录中。之后,我们可以使用相对路径,例如‘/image_name’,或者如果我们将图片添加到public目录内的任何文件夹中,我们需要使用相对路径,例如‘/folder_path/image_name’。
在这里,我们使用相对路径显示React应用程序的logo作为背景图片。
import React from "react";
export default function App() {
return (
<div>
<h3>
{" "}
Using relative URLs with React inline styles to set background image
</h3>
<div
class = "image"
style = {{
height: "400px",
width: "550px",
backgroundImage:
'url("https://tutorialspoint.com/reactjs/images/reactjs-minilogo.jpg")', backgroundSize: "contain", backgroundRepeat: "no-repeat",
}}
>
This div contains a background image.
</div>
</div>
);
}
输出

在本教程中,我们学习了如何使用React内联样式设置背景图片。我们使用了绝对和相对URL来使用‘backgroundImage’ CSS属性设置背景图片。
此外,用户还可以使用CSS属性来自定义背景图片,例如将背景图片固定在div中并避免重复。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP