繁体   English   中英

如何将代码从路由传输到组件

[英]How to transfer code from a route to a component

我有路线

            <BrowserRouter>
                <Navbar />
                <div className="container pt-4">
                    <Switch>
                        <Route path="/" exact component={Home}></Route>
                        <Route path="/files" component={Files}></Route>
                        <Route path="/signin" component={SignIn}></Route>
                        <Route path="/signup" component={SignUp}></Route>
                        <Route path="/:url_code" component={File}></Route>
                    </Switch>
                </div>
            </BrowserRouter>

如何传递:url_code File页面。

import React, { Fragment } from 'react';

import { Item } from './../components/Item.component';

export const File = () => {
    return (
        <Fragment>
            <h3>test</h3>
            <hr />
            <Item />
        </Fragment>
    );
};

你需要让你的组件访问 react-router 的match object。 您可以使用名为withRouter的高阶组件来完成此操作。 这使您可以访问locationhistorymatch作为传递给组件的道具。 从那里您可以通过match.params提取您的url_code片段。

import React, { Fragment } from 'react';
import { withRouter } from "react-router";

import { Item } from './../components/Item.component';
const File = ({ match }) => {
    return (
        <Fragment>
            <h3>{match.params.url_code}</h3>
            <hr />
            <Item />
        </Fragment>
    );
};

export withRouter(File)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM