在 React 中使用内联样式设置背景图像
在 React 中设置带有内联样式的背景图片:
- 在 img 元素上设置 style 属性。
-
在样式对象中设置
backgroundColor
属性。 -
例如,
backgroundImage: url(${MyBackgroundImage})
。
// 👇️ import the image
import MyBackgroundImage from './background-image.webp';
export default function App() {
const externalImage =
'https://example.com/images/blog/react-prevent-multiple-button-clicks/thumbnail.webp';
return (
<div
style={{
backgroundImage: `url(${MyBackgroundImage})`,
// backgroundImage: `url(${externalImage})`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center',
height: '500px',
}}
>
<h2 style={{color: 'white'}}>Hello world</h2>
</div>
);
}
该示例展示了如何使用内联 React 样式将本地或外部图像设置为背景图像。
该示例假定我们在与 App 组件相同的文件夹中有一个名为 background-image.webp
的图像。
对于本地图片,请确保指定正确的图片文件路径(包括扩展名)。
例如,如果我们从一个目录向上导入图像,我们将导入为 import MyImage from '../background-image.webp'
。
图片必须位于项目的 src 目录中。
我们可以将导入的图像传递给 url()
CSS 函数或指向外部图像的远程 URL。
下面是一个使用远程背景图像的示例。
export default function App() {
const externalImage =
'https://example.com/images/blog/react-prevent-multiple-button-clicks/thumbnail.webp';
return (
<div
style={{
backgroundImage: `url(${externalImage})`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center',
height: '500px',
}}
>
<h2 style={{color: 'white'}}>Hello world</h2>
</div>
);
}
请注意
,我们使用模板文字在字符串中插入变量。
请注意,字符串包含在反引号 `` 中,而不是单引号中。
美元符号和花括号语法允许我们使用被评估的占位符。
const externalImage = 'https://example.com/img.png';
const result = `url(${externalImage})`;
// 👇️ url(https://example.com/img.png)
console.log(result);
默认情况下,模板文字将各个部分连接成一个字符串。
这正是我们所需要的,因为 url()
CSS 函数用于包含一个文件,并将绝对 URL、相对 URL 或数据 URL 作为参数。
相关文章
在 React 中使用 onChange 事件
发布时间:2023/03/08 浏览次数:88 分类:WEB前端
-
onChange 是 React 中最常见的输入事件之一。本文将帮助你了解它的工作原理。
获取 onKeyDown 事件以在 React 中使用 Div
发布时间:2023/03/08 浏览次数:154 分类:WEB前端
-
在 React 中处理事件是构建现代 Web 应用程序的关键。这是处理 div 上的 onKeyDown 事件的方法
从 React 中的子组件访问路由参数
发布时间:2023/03/08 浏览次数:77 分类:WEB前端
-
在本文中,我们将探索 React Router 中的所有基本组件,并展示如何从子组件访问参数。