我想在名为“App”的顶级 React 组件上使用 withRouter。
我是这样使用的:
import React from "react";
import { render } from "react-dom";
import {Router, Link, hashHistory, Route, IndexRoute, withRouter} from "react-router";
import VoteView from "./voteview/Voteview.jsx";
import OverView from "./overview/Overview.jsx";
import AppBar from 'material-ui/AppBar';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import injectTapEventPlugin from 'react-tap-event-plugin';
//Needed for onTouchTap
//Can go away when react 1.0 release
//Check this repo:
//https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();
const App = React.createClass({
render() {
return (
<div>
<AppBar
title="Democratizer"
onTitleTouchTap={()=>this.props.router.push('/')}
>
</AppBar>
<br/>
{this.props.children}
</div>
);
}
});
render((
<MuiThemeProvider muiTheme={getMuiTheme()}>
<Router history={hashHistory}>
<Route path="/" component={App}>
<Route path="voteview/:baselineId" component={VoteView}/>
<IndexRoute component={OverView}/>
</Route>
</Router>
</MuiThemeProvider>
), document.getElementById('app'));
module.exports = withRouter(App);
我想使用 withRouter(App) 以使 Appbar 标题可点击。如果用户点击它,应该打开默认的“/”路径。这就是我尝试通过 onTitleTouchTap={()=>this.props.router.push('/')}
实现的目标。
我的问题是路由器不存在。当用户点击 Appbar 中的标题时,会触发错误:Uncaught TypeError: Cannot read property 'push' of undefined
。
withRouter(SomeComponent) 对于组件树中更靠下的组件对我来说效果很好。但在这种情况下我无法让它运行。
知道我做错了什么吗?
最佳答案
发生这种情况是因为您在渲染 React 应用程序后注入(inject)路由器。
const App = React.createClass({
render() {
return (
<div>
<AppBar
title="Democratizer"
onTitleTouchTap={()=>this.props.router.push('/')}
>
</AppBar>
<br/>
{this.props.children}
</div>
);
}
});
App = withRouter(App);
render((
<MuiThemeProvider muiTheme={getMuiTheme()}>
<Router history={hashHistory}>
<Route path="/" component={App}>
<Route path="voteview/:baselineId" component={VoteView}/>
<IndexRoute component={OverView}/>
</Route>
</Router>
</MuiThemeProvider>
), document.getElementById('app'));
更好的解决方案是为 App 创建一个文件,就像您对其他组件所做的那样。
const App = React.createClass({
render() {
return (
<div>
<AppBar
title="Democratizer"
onTitleTouchTap={()=>this.props.router.push('/')}
>
</AppBar>
<br/>
{this.props.children}
</div>
);
}
});
module.exports = withRouter(App);
并将其导入到您的 index.js 中。
关于javascript - react -路由器withRouter不注入(inject)路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37225592/