简体   繁体   中英

extends RouteComponentProps to accept more props?

I have this piece of typescript code in react, it's a render props component, I'm getting error because RouteComponentProps doesn't have a prop call component.

class Auth extends Component<RouteComponentProps> {
  render() {
    const { component: Component, ...rest } = this.props //error: Property 'component' does not exist on type 'Readonly<RouteComponentProps<{}, StaticContext, any>> & Readonly<{ children?: ReactNode; }>'.ts(2339)


    const isAuth = getUser()

    return (
      <Route
        {...rest}
        render={props =>
          isAuth ? (
            <Component {...props} />
          ) : (
            <Redirect
              to={{
                pathname: '/login'
              }}
            />
          )
        }
      />
    )
  }
}

export default withRouter(Auth)

You can define your own interface to handle it:

interface MyOwnProps {
  component: React.Component;
}

class Auth extends Component<MyOwnProps & RouteComponentProps> {
  render() {
    const { component, ...rest } = this.props;

This should fix the error you are encountering.

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