【问题标题】:How to add props to the component using typescript and react?如何使用打字稿向组件添加道具并做出反应?
【发布时间】:2020-11-23 07:11:08
【问题描述】:

我有一个父组件,我通过如下所示的 RouteComponentprops,

function Parent({ history }: RouteComponentProps) {
    //some logic
}

现在我想向父组件添加一个道具 OpenByDefault,如下所示,

interface Props {
    OpenByDefault?: boolean;
}

function Parent({OpenByDefault = false}: Props) {
    //some logic
}

我也不确定如何将 {history: RouteComponentProps} 添加到此道具中。我是使用打字稿的新手。有人可以帮我解决这个问题。谢谢。

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    您至少有两个选择:

    1. 在定义Props 时扩展RouteComponentProps
    2. 使用intersection type

    这里是#1的一个例子:

    interface Props extends RouteComponentProps {
        OpenByDefault?: boolean;
    }
    

    然后在Parent 上使用Props 而不是RouteComponentProps

    function Parent({ history, OpenByDefault }: Props) {
        // ...
    }
    

    这里是#2的一个例子:

    function Parent({ history, OpenByDefault }: RouteComponentProps & Props) {
        // ...
    }
    

    RouteComponentProps & Props 表示Parent 接受的参数是RouteComponentPropsProps 的组合。


    既然你说你是这个东西的新手:按照惯例,OpenByDefault 应该被称为openByDefault(小写首字母)。在 JavaScript 和 TypeScript 中,首字母大写几乎只用于构造函数名称。 (在 React 中,它也用于组件函数,即使它们不是构造函数。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-14
      • 2020-04-08
      相关资源
      最近更新 更多