如何在react-router中使用组件中的参数?

时间:2016-05-18 11:48:54

标签: javascript reactjs ecmascript-6 react-router

我的路由器:

import React from 'react';
import Application from './Application';
import { Route } from 'react-router';
import JobsScreen from './jobs-screen/JobScreen'
import TaskScreen from './task-screen/TaskScreen'

const routes = (
    <Route name="app" path="/" component={Application}>
        <Route name="jobs_screen" path="jobs" component={JobsScreen}/>
        <Route name="task_screen" path="task/:enquiryid" component={TaskScreen}/>
    </Route>
);

export default routes;

我的组件渲染:

render() {
    return (
        <div>
            {this.props.enquiryid}
        </div>
    );
}

但这不起作用,如何访问目标组件中的route参数?

1 个答案:

答案 0 :(得分:0)

你应该使用params

const { enquiryid } = this.props.params

来自文档源代码的示例:

路由器

  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <Route path="user/:userID" component={User}>
        <Route path="tasks/:taskID" component={Task} />
        <Redirect from="todos/:taskID" to="tasks/:taskID" />
      </Route>
    </Route>
  </Router>

组件

class User extends Component {
  render() {
    const { userID } = this.props.params

    return (
      <div className="User">
        <h1>User id: {userID}</h1>
        <ul>
          <li><Link to={`/user/${userID}/tasks/foo`} activeClassName="active">foo task</Link></li>
          <li><Link to={`/user/${userID}/tasks/bar`} activeClassName="active">bar task</Link></li>
        </ul>
        {this.props.children}
      </div>
    )
  }
}