React Router 将参数传递给组件

新手上路,请多包涵
const rootEl = document.getElementById('root');

ReactDOM.render(
    <BrowserRouter>
        <Switch>
            <Route exact path="/">
                <MasterPage />
            </Route>
            <Route exact path="/details/:id" >
                <DetailsPage />
            </Route>
        </Switch>
    </BrowserRouter>,
    rootEl
);

我正在尝试访问 DetailsPage 组件中的 id ,但它无法访问。我试过了

<DetailsPage foo={this.props}/>

将参数传递给DetailsPage,但徒劳无功。

 export default class DetailsPage extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div className="page">
            <Header />
            <div id="mainContentContainer" >

            </div>
            </div>
    );
    }
}

那么知道如何将 ID 传递给 DetailsPage 吗?

原文由 M T 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 720
2 个回答

如果你想将 props 传递给路由内的组件,最简单的方法是利用 render ,如下所示:

 <Route exact path="/details/:id" render={(props) => <DetailsPage globalStore={globalStore} {...props} /> } />

您可以使用以下方法访问 DetailPage 中的道具:

 this.props.match
this.props.globalStore

{...props} 是传递原始 Route 的 props 所必需的,否则你只会在 this.props.globalStore DetailPage

原文由 Win 发布,翻译遵循 CC BY-SA 3.0 许可协议

我用它来访问组件中的 ID:

 <Route path="/details/:id" component={DetailsPage}/>

在详细信息组件中:

 export default class DetailsPage extends Component {
  render() {
    return(
      <div>
        <h2>{this.props.match.params.id}</h2>
      </div>
    )
  }
}

这将呈现 h2 中的任何 ID。

原文由 Alexander Luna 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进