反应路由器传递参数到组件 [英] React Router Pass Param to Component

查看:43
本文介绍了反应路由器传递参数到组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const rootEl = document.getElementById('root');ReactDOM.render(<浏览器路由器><开关><路由精确路径="/"><母版页/></路线><路由精确路径="/details/:id" ><详情页/></路线></开关></BrowserRouter>,根);

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

向DetailsPage传递参数,但徒劳无功.

导出默认类DetailsPage extends Component {构造函数(道具){超级(道具);}使成为() {返回 (<div className="页面"><标题/><div id="mainContentContainer" >

);}}

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

解决方案

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

<路由精确路径="/details/:id" render={(props) =><DetailsPage globalStore={globalStore} {...props}/>}/>

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

this.props.matchthis.props.globalStore

需要{...props}来传递原始Route的props,否则在DetailPage<中只会得到this.props.globalStore/代码>.

const rootEl = document.getElementById('root');

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

I am trying access the id in the DetailsPage component but it is not being accessible. I tried

<DetailsPage foo={this.props}/>

to pass parameters to the DetailsPage, but in vain.

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

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

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

So any idea how to pass the ID on to the DetailsPage ?

解决方案

If you want to pass props to a component inside a route, the simplest way is by utilizing the render, like this:

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

You can access the props inside the DetailPage using:

this.props.match
this.props.globalStore

The {...props} is needed to pass the original Route's props, otherwise you will only get this.props.globalStore inside the DetailPage.

这篇关于反应路由器传递参数到组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆