简体   繁体   中英

how to pass react-router-dom props & normal props

I know the way use react-router-dom props. that is like this

import React from 'react';
import { RouteComponentProps } from 'react-router-dom';

const  AAA : React.FC<RouteComponentProps> = ({history}) => {
.
.
.
}

and I know how to use props sended by parent component that is like this

import React from 'react';

const AAA = props => {
.
.
.
}

but I don't know how to use both of this.

please give me advice.

{history} prop that you are using is using object destructuring.

You can either do this:

  1. You can directly use history and sampleProp in your code.
<ChildComponent samepleProp />
const ChildComponent = ({history, samepleProp}) = {}
  1. Or you can do it like this.

You have to use props.history and props.sampleProp

<ChildComponent samepleProp />
const ChildComponent = (props) = {}

When you perform destructuration on an Object. You will have access only to properties which you specify.

As all props pass to a component are accessible via the argument which It's constructor receive generally named as props you can access them via props.prop_name

If you have a ChildComponent within which you want to have access to router properties like history, location, match and properties which It receive from it parent you can perform that like this.

consider in the ParentComponent you render the ChildComponent like this

<ChildComponent name="The child component" />

To access both router parameter and props receive from the parent you do this

import { withRouter } from 'react-router-dom';

const ChildComponent = (props) => {

    // Here you have access to react-router-dom parameter

    const {history, location, match} = props;

    return <div>
         
         {/* 
             to access name props receive from the parent
             component you perform it like below 
         */}

         {props.name} 

    </div>
}

export default withRouter(ChildComponent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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