我正在尝试使用 react-router ( 版本 ^1.0.3 )做一个简单的重定向到另一个视图。
import React from 'react';
import {Router, Route, Link, RouteHandler} from 'react-router';
class HomeSection extends React.Component {
static contextTypes = {
router: PropTypes.func.isRequired
};
constructor(props, context) {
super(props, context);
}
handleClick = () => {
console.log('HERE!', this.contextTypes);
// this.context.location.transitionTo('login');
};
render() {
return (
<Grid>
<Row className="text-center">
<Col md={12} xs={12}>
<div className="input-group">
<span className="input-group-btn">
<button onClick={this.handleClick} type="button">
</button>
</span>
</div>
</Col>
</Row>
</Grid>
);
}
};
HomeSection.contextTypes = {
location() {
React.PropTypes.func.isRequired
}
}
export default HomeSection;
我需要的只是将使用发送到’/login’,就是这样。
我能做些什么 ?
控制台中的错误:
未捕获的 ReferenceError:未定义 PropTypes
用我的路线归档
// LIBRARY
/*eslint-disable no-unused-vars*/
import React from 'react';
/*eslint-enable no-unused-vars*/
import {Route, IndexRoute} from 'react-router';
// COMPONENT
import Application from './components/App/App';
import Contact from './components/ContactSection/Contact';
import HomeSection from './components/HomeSection/HomeSection';
import NotFoundSection from './components/NotFoundSection/NotFoundSection';
import TodoSection from './components/TodoSection/TodoSection';
import LoginForm from './components/LoginForm/LoginForm';
import SignupForm from './components/SignupForm/SignupForm';
export default (
<Route component={Application} path='/'>
<IndexRoute component={HomeSection} />
<Route component={HomeSection} path='home' />
<Route component={TodoSection} path='todo' />
<Route component={Contact} path='contact' />
<Route component={LoginForm} path='login' />
<Route component={SignupForm} path='signup' />
<Route component={NotFoundSection} path='*' />
</Route>
);
原文由 Reacting 发布,翻译遵循 CC BY-SA 4.0 许可协议
对于简单的答案,您可以使用
react-router
中的Link
组件,而不是button
。有一些方法可以改变 JS 中的路线,但似乎你在这里不需要。要在 1.0.x 中以编程方式执行此操作,您可以在 clickHandler 函数中这样做:
this.history.pushState(null, 'login');
取自升级文档 here
您应该通过
react-router
将this.history
放置在您的路由处理程序组件上。如果它是routes
定义中提到的子组件,您可能需要进一步传递它