我正在浏览路由lessons以获取React
经过多次尝试,我得到了一个有效的应用程序,我可以使用:
var react = require("react");
var Render = require('react-dom');
Render((
<Router history={hashHistory}>
<Route path="/about" component={About}/>
</Router>
), document.getElementById('app'))
但是,Web上的大多数示例都使用import语句,例如:
import { Router, Route, hashHistory } from 'react-router'
render((
<Router history={hashHistory}>
<Route path="/" component={App}/>
</Router>
), document.getElementById('app'))
这是我的web.pack.config:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: [
'./src/app.js'
],
output: {
path: path.join(__dirname, 'public/js'),
filename: 'app.built.js'
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?
presets[]=es2015&presets[]=react'
}
]
}
}
我该怎么做才能开始使用import语句?
答案 0 :(得分:1)
错误是因为您没有导入ReactDOM。最好的方法是
import React from "react";
import ReactDOM from "react-dom";
import { Router, Route, IndexRoute, hashHistory } from "react-router";
import App from "./App";
const app = document.getElementById('app');
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={App}></Route>
</Router>, app);
考虑到您在同一目录中有一个名为App的组件,如下所示:
App.js
import React from "react";
export default class App extends React.Component {
render() {
return (
<div>My App!</div>
);
}
}