我正在研究一个示例reactjs应用程序(在学习过程中)。我有一个页面,其中列出了用户列表和一个添加按钮以添加新用户。
当我单击添加按钮时,我应该导航到用户表单以创建新用户。
在用户表单中单击“提交”按钮后,它应导航回到第一页,在该页面中应列出用户列表以及新用户。
如何在页面之间导航做出反应?
您可以使用React Router来完成。这是React Router教程。
用户列表是打开站点时显示的第一页,即您的索引页,所有其他页均为路线。
因此,您可以执行以下操作:
您可以使用路线创建一个单独的文件:
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应该看起来像这样:
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'));
在这里,您将其包装在Routerfrom的来源之下,然后在其中react- router传递您要使用的历史道具并路由该道具。您可以使用browserHistory和hashHistory。BrowserHistory显示更干净的URL。使用哈希历史记录,您可以得到类似someurl.com/#/something
Router
react- router
browserHistory
hashHistory
someurl.com/#/something
现在,在您的应用中,您可以执行以下操作:
export default class App extends Component { render() { return ( <div> {this.props.children} </div> ); } }
{this.props.children} 从路由文件渲染所有路由,因为您已经为主路由指定了App组件。
{this.props.children}
在添加用户按钮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> ); }
希望这可以帮助。