在React JS中添加背景图像

时间:2017-10-09 17:14:31

标签: reactjs

我决定在React中使用内联JS样式。除了图像,一切都很好。在这里,我尝试向div添加背景图像,但是我收到了错误。

import React, {Component} from 'react';
import ReactDOM from "react-dom";

var styles = {
color:'violet',
backgroundImage: 'url(' + require('./sun.png') + ')' 
};

class App extends React.Component {
  render() {
    return (
    <div>
        <h1>How to make smth</h1>
        <div style={styles}>test</div>
    </div>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('root'));

我收到错误,我只是不知道我需要什么加载器以及如何将其添加到webpack config(或package.json)

here is what i get

1 个答案:

答案 0 :(得分:6)

尝试

import React, {Component} from 'react';
import ReactDOM from "react-dom";
import image from './sun.png';

var styles = {
color:'violet',
backgroundImage: 'url('+image+')'
};

添加加载器: 在webpack配置中,您正在使用更改

module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-0'],
          plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
        }
      }
    ] 

module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-0'],
          plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
        }
      },
      {
        test: /\.png$/,
        loader: "url-loader",
        query: { mimetype: "image/png" }
      }
    ]