我正在尝试构建一个父子耦合组件,基于反应教程,我编写了以下代码。但是,它给出了此错误消息:TypeError: this.context.router.createHref is not a function
。
有任何想法吗?
Index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter as Router } from 'react-router-dom';
ReactDOM.render(<Router>
<App />
</Router>, document.getElementById('root'));
App.js:
import React, { Component } from 'react';
import './App.css';
import Header from './Component/Header';
import Button1 from './Component/Button1';
import Home from './Component/Home';
import { BrowserRouter as Router, Route, Link, Switch} from 'react-router-dom';
class App extends Component {
render() {
const Main = () => (
<div>
<Router>
<Route path="/" component={Home} />
<Route path="/button1" component={Button1} />
</Router>
</div>
);
return (
<div className="App">
<Header />
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/button1">Button1</Link></li>
</ul>
<Main />
</div>
);
}
}
export default App;
答案 0 :(得分:1)
所有react-router
和react-router-dom
组件都必须是您<Router />
的孩子。
尝试进行以下更改;
class App extends Component {
render() {
const Main = () => (
<div>
<Route path="/" component={Home} />
<Route path="/button1" component={Button1} />
</div>
);
return (
<Router>
<div className="App">
<Header />
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/button1">Button1</Link></li>
</ul>
<Main />
</div>
</Router>
);
}
}
export default App;
如果您不希望同时呈现这两个组件,您可能还想将exact
添加到<Route exact path="/" component={Home} />
。
答案 1 :(得分:0)
将react-router-dom升级到V4.1.2,它可以工作!
答案 2 :(得分:-1)
根据this issue report,如果您执行npm install react-router-dom@next
,您的示例应该有效。默认情况下,它会安装v0.0.0
。