我正在尝试使用react路由器实现导航示例并陷入错误。请找到代码
app.js
-------
import React from 'react';
import ReactDOM from 'react-dom';
import Routes from './routes';
ReactDOM.render(Routes, document.getElementById('react-container'));
routes.js
---------
import { React,Component } from 'react';
import { DefaultRoute, Link, Route, RouteHandler,Router } from 'react-router';
import Page1 from './page1';
import Home from './home';
export default class Routes extends Component {
constructor() {
super();
}
render() {
return (
<Router >
<Route path="/" component={Home}>
<Route name="page1" path="/1" component={ Page1 }/>
</Route>
</Router>
);
}
}
home.js
-------
import React, { Component } from 'react';
export default class Home extends Component {
constructor() {
super();
}
render() {
return (
<div>
<Header />
{this.props.children}
</div>
);
}
}
page1.js
--------
import React, { Component } from 'react';
export default class Page1 extends Component {
constructor() {
super();
}
render() {
return (
<div>
<h1> Page 1 </h1>
</div>
);
}
}
我有babel变换器从es6转换为es5,我在加载应用时出现以下错误,
Uncaught Invariant Violation: ReactDOM.render(): Invalid component element. Instead of passing a component class, make sure to instantiate it by passing it to React.createElement.
有人可以帮我解决这个问题吗?
答案 0 :(得分:4)
问题在于你的routes.js。您将路由包装在组件内部,然后将其传递给routes.js
---------
import React from 'react'
import { Router, Route } from 'react-router'
import Page1 from './page1'
import Home from './home'
let routes =
<Router>
<Route path="/" component={Home}>
<Route name="page1" path="/1" component={Page1}/>
</Route>
</Router>
export default routes
。你应该直接传递jsx。我的建议是从你的类中解开路由,然后导出jsx。
React.createElement
错误是抱怨您正在传递一个类,而不是调用let someElement = <div>Hello</div>
。请记住:
var someElement = React.createElement(
"div",
null,
"Hello"
)
将变成这个:
gcc