反应插值背景网址不渲染

时间:2017-05-28 21:39:01

标签: javascript reactjs ecmascript-6

我教自己React,这很难,请原谅我这里的不良措辞,因为它对我来说还是一个新鲜事。

我试图编写一个组件,根据给定的道具在某个页面上渲染背景图像。我已经提出过插值可能会有效但是我没有达到我想要的效果。

所以,让我们在我的组件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

我不知所措,不知道该怎么做。有什么想法吗? (我非常清楚某些事情是错误的或破碎的,我只是无法弄清楚)

2 个答案:

答案 0 :(得分:1)

试试这个。请记住,在React中,props会更改为camelCase,因此带有破折号的属性不起作用:

<BgBackground style={{backgroundImage: 'url( "${this.props.image}" )' }} />

答案 1 :(得分:0)

<BgBackground style={{background-image: 'url( "${this.props.image}" )' }} />