类型中缺少不应手动传递给子组件的属性

Leo*_*vdb 6 typescript reactjs react-router

在我的子组件中,我定义了 Props 接口并将其包含在 React.Component 中。

然后需要将这些 Props 从父组件传递给子组件。到目前为止一切顺利,这一切都说得通..

但是,当我使用来自 react-router Typescript 的 RouteComponentProps 扩展 Props 接口时,还需要我传递“历史、位置、匹配”,我认为我不应该手动传递这些信息......

我认为它与 RouteComponentProps 没有特别的关系,因为在某些情况下,我在使用 MapDispatchToProps 和 PropsFromDispatch 接口时遇到了同样的错误——这里对这种情况进行了更详细的解释

这是我的代码:

/Child.tsx

import * as React from 'react'
import { RouteComponentProps } from 'react-router';

interface Props extends RouteComponentProps { }

class Child extends React.Component<Props> {
    render() {
        return (
            <div>

            </div>
        )
    }
 }

export default Child;
Run Code Online (Sandbox Code Playgroud)

/Parent.tsx

import * as React from 'react'
import Child from './Child';

export default class Parent extends React.Component {
    render() {
        return (
            <div>
                <Child />
             </div>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

/Parent.tsx 中的错误:

<Child/>

Type '{}' is missing the following properties from type 
'Readonly<Props>': history, location, match - ts(2739)
Run Code Online (Sandbox Code Playgroud)

打字稿和反应版本:

“打字稿”:“^3.2.1”,“反应”:“^16.6.3”,“@types/react”:“^16.7.13”

感谢您的任何建议!

Har*_*oni 5

所以问题是由类Props中标记为必需的那些引起的RouteComponentProps

当您解决方法时,您需要导出您的 class as any,它将导出您的 class 没有任何类型。

import * as React from 'react'
import { RouteComponentProps, withRouter } from 'react-router';

interface Props extends RouteComponentProps { }

class ChildImpl extends React.Component<Props> {
    render() {
        return (
            <div>

            </div>
        )
    }
 }
const Child = withRouter(ChildImpl as any);//Note: It is a workaround not an actual solution
export default Child;
Run Code Online (Sandbox Code Playgroud)

然后在你的父母:

import * as React from 'react'
import Child from './Child';
export default class Parent extends React.Component {
    render() {
        return (
            <div>
                <Child />
             </div>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

不需要道具通过。

  • 这是正确的,但如果您不想将道具传递给您的组件,只需使用 RouteComponentProps 作为道具即可解决问题。此外,您不需要“按任何方式”导出。 (2认同)