在 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 作为参数。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。