我决定在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)
答案 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" }
}
]