我正在自学 React,这很困难,请原谅我的糟糕措辞,因为这对我来说仍然很新。
我正在尝试编写一个组件,该组件将根据给定的 Prop 在特定页面上渲染背景图像。我发现通过插值这可能会起作用,但是我没有达到我想要的效果。
所以假设在我的名为 blog.js
的组件中我有
<BgImage image="blog" />
然后我的组件应该渲染我的背景:
import React from 'react';
import styled from 'styled-components';
import blog from '../../static/blog.jpg';
import about from '../../static/about.jpg';
import contact from '../../static/contact.jpg';
import projects from '../../static/projects.jpg';
const BgBackground = styled.div`
width: 100%;
height: 400px;
position: absolute;
&::after {
background-size: cover;
content: "";
opacity: 0.25;
height: 400px;
top: 0;
left: 0;
bottom: 0;
right: 0;
position: absolute;
z-index: -1;
}
`
class BgImage extends React.Component {
render() {
return (
<BgBackground style={{background: 'url' + this.props.image}} />
);
}
}
export default BgImage;
我没有收到错误,但收到这些警告,因为没有使用任何内容:
3:8 warning 'blog' is defined but never used no-unused-vars
4:8 warning 'about' is defined but never used no-unused-vars
5:8 warning 'contact' is defined but never used no-unused-vars
6:8 warning 'projects' is defined but never used no-unused-vars
我很茫然,不知道接下来该怎么办。有什么想法吗? (我非常清楚有什么问题或损坏,但我就是无法弄清楚)
最佳答案
试试这个。请记住,在 React 中,props 已更改为驼峰命名法,因此带有破折号的属性无效:
<BgBackground style={{backgroundImage: 'url( "${this.props.image}" )' }} />
关于javascript - react 背景 url 的插值不渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44232260/