React Router Pass Param to Component

后端 未结 10 1225
南方客
南方客 2020-11-30 20:06
const rootEl = document.getElementById(\'root\');

ReactDOM.render(
    
        
            
              


        
相关标签:
10条回答
  • 2020-11-30 20:38

    Since react-router v5.1 with hooks:

    import { useParams } from 'react-router';
    
    export default function DetailsPage() {
      const { id } = useParams();
    }
    

    See https://reacttraining.com/blog/react-router-v5-1/

    0 讨论(0)
  • 2020-11-30 20:39

    In addition to Alexander Lunas answer ... If you want to add more than one argument just use:

    <Route path="/details/:id/:title" component={DetailsPage}/>
    
    export default class DetailsPage extends Component {
      render() {
        return(
          <div>
            <h2>{this.props.match.params.id}</h2>
            <h3>{this.props.match.params.title}</h3>
          </div>
        )
      }
    }
    
    0 讨论(0)
  • 2020-11-30 20:42

    if you are using class component, you are most likely to use GSerjo suggestion. Pass in the params via <Route> props to your target component:

    exact path="/problem/:problemId" render={props => <ProblemPage {...props.match.params} />}
    
    0 讨论(0)
  • 2020-11-30 20:45

    Here's typescript version. works on "react-router-dom": "^4.3.1"

    export const AppRouter: React.StatelessComponent = () => {
        return (
            <BrowserRouter>
                <Switch>
                    <Route exact path="/problem/:problemId" render={props => <ProblemPage {...props.match.params} />} />
                    <Route path="/" exact component={App} />
                </Switch>
            </BrowserRouter>
        );
    };
    

    and component

    export class ProblemPage extends React.Component<ProblemRouteTokens> {
    
        public render(): JSX.Element {
            return <div>{this.props.problemId}</div>;
        }
    }
    

    where ProblemRouteTokens

    export interface ProblemRouteTokens { problemId: string; }

    0 讨论(0)
  • 2020-11-30 20:55

    try this.

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

    In details page try this...

    this.props.id
    
    0 讨论(0)
  • 2020-11-30 20:57

    I used this to access the ID in my component:

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

    And in the detail component:

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

    This will render any ID inside an h2, hope that helps someone.

    0 讨论(0)
提交回复
热议问题