我正在寻找一种方法,当用户单击按钮时,使用 react-router
更改reactJS中的路由。
以下是我的 jsx
文件中的相关代码(为简洁起见,省略了组件的详细信息):
var React = require('react');
var ReactDOM = require('react-dom');
var {Route, Router, IndexRoute, hashHistory, browserHistory} = require('react-router');
var {Link, IndexLink} = require('react-router');
var Main = React.createClass({
render: function(){
return(
<div>
<header>
<Router history={hashHistory}>
<Route path='/' component={Splash}></Route>
<Route path='login' component={Login}/>
</Router>
</header>
<footer>
<Button_/>
</footer>
</div>
);
}
});
var Login = React.createClass({
render: function(){
return(
<div>This is the login component</div>
);
}
});
var Button_ = React.createClass({
handleClick: function(e){
e.preventDefault();
},
render: function(){
return(
<Link to='/login' activeClassName='active'>LOGIN</Link>
);
}
});
var Splash = React.createClass({
render: function(){
return(
<div>This is the Splash component</div>
);
}
});
ReactDOM.render(<Main/>, document.getElementById('app'));
正如您现在可能看到的,Splash
组件是页面上显示的默认组件。当用户单击 Button_
组件中的 Link
时,我希望将 Splash
组件替换为 Login
DOM 中的组件。
我正在运行 python 服务器进行测试,因此 URL 看起来像 http://localhost:8000/public/#/?_k=hqkhl0
我目前拥有的代码没有执行我想要的操作。如果我手动输入 http://localhost:8000/public/#/login
,页面会发生变化,但单击按钮不起作用。
我还尝试通过在“Button_”的“handleClick”函数中使用 browserHistory.push()
手动更改页面(并且还在正确的位置),但这并没有给我想要的结果。
我第一次尝试
browserHistory.push('/#/login');
这导致重定向到http://localhost:8000/#/login
,显然是不对的。
然后我尝试了
browserHistory.push('public/#/login');
这导致重定向到http://localhost:8000/public/public/#/login
,同样,不正确。
如何成功路由到Login
组件?
最佳答案
在你的handleClick函数中试试这个:
this.props.router.replace('login')
这是“react-router”:“^3.0.2”,
关于ReactJS:根据点击事件更改路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36714723/