迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 >

在 React 中使用内联样式设置背景图像

作者:迹忆客 最近更新:2023/01/28 浏览次数:

在 React 中设置带有内联样式的背景图片:

  1. 在 img 元素上设置 style 属性。
  2. 在样式对象中设置 backgroundColor 属性。
  3. 例如,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 中添加事件监听器

发布时间:2023/03/08 浏览次数:179 分类:WEB前端

事件侦听器对于单页应用程序至关重要。在本文中,我们将探讨如何在 React 中添加它们。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便