【发布时间】:2016-10-17 06:29:04
【问题描述】:
我正在开发一个示例 reactjs 应用程序(在学习过程中)。我有一个列出用户列表的页面和一个添加新用户的添加按钮。
当我点击添加按钮时,我应该导航到用户表单以创建新用户。
单击用户表单中的提交按钮后,它应该导航回第一页,其中应该列出用户列表以及新用户。
如何在 react 中的页面之间导航?
【问题讨论】:
标签: reactjs
我正在开发一个示例 reactjs 应用程序(在学习过程中)。我有一个列出用户列表的页面和一个添加新用户的添加按钮。
当我点击添加按钮时,我应该导航到用户表单以创建新用户。
单击用户表单中的提交按钮后,它应该导航回第一页,其中应该列出用户列表以及新用户。
如何在 react 中的页面之间导航?
【问题讨论】:
标签: reactjs
你用反应路由器来做。这是react router tutorial。
您的用户列表是您打开网站时显示的第一页,因此这是您的索引页,所有其他页面都是路由。
因此你可以这样做:
您可以使用您的路线创建一个单独的文件:
import UserList from 'path/to/user/list';
import AddUserForm from 'path/....';
const routes = (
<Route path="/" component={App}>
<IndexRoute component={UserList}/>
<Route path="addUser" component={AddUserForm}/>
</Route>
);
export default routes;
那么你的index.js 应该是这样的:
import React from 'react';
import ReactDOM from 'react-dom';
import {Router, browserHistory} from 'react-router';
import routes from 'path/to/routes';
ReactDOM.render(<Router history={browserHistory} routes={routes}/>, document.getElementById('root'));
在这里,您将其包装在来自react-router 的Router 下,并在那里传递您要使用的历史道具和路由道具。您可以使用browserHistory 和hashHistory。 BrowserHistory 显示更简洁的 url。有了哈希历史,你就有了类似someurl.com/#/something
现在您可以在您的应用中执行下一步操作:
export default class App extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
{this.props.children} 渲染路由文件中的所有路由,因为您已经为主路由指定了 App 组件。
在添加用户按钮 onClick 事件中,您可以使用 browserHistory 导航到添加用户表单,因此:
import { browserHistory } from 'react-router;
.........
onClick(){
browserHistory.push("/addUser");
}
.......
render(){
return (
//Userlist with the button
<button onClick={this.onClick.bind(this)}>Add New user</button>
);
}
然后在按钮上点击添加用户表单,同样的过程,你只需要导航到带有"/"的索引路由,因此:
import { browserHistory } from 'react-router;
.........
onClick(){
//Your code to add user to the list of users
browserHistory.push("/");
}
.......
render(){
return (
//Add user form
<button onClick={this.onClick.bind(this)}>Add User</button>
);
}
希望这会有所帮助。
【讨论】:
除了browserHistory,您还可以通过从react-router 导入hashHistory 来使用它。
import {hashHistory} from 'react-router';
hashHistory.push('/addUser')
【讨论】: