TypeScript中React StatelessComponent的DefaultProps

时间:2016-09-16 09:21:39

标签: javascript reactjs typescript typescript1.8 typescript-typings

我想在defaultProps中使用typescript中的react stateless组件。

我无法找到解决方案如何使用能够在 TypeScript 项目中使用 defaultProps 而不使用菱形语法的输入法。

class Child extends Parent {
  constructor() {
    console.log('C constructor');
    super();
  }
  _init() {
    super._init();
    console.log('C _init()');
    this.childProp = 'child';
  }
  …

2 个答案:

答案 0 :(得分:2)

键入 React.SFC 允许附加 defaultProps 以响应无状态组件。

Bellow您可以使用 defaultProps 找到 React.SFC 的简化示例。

import {Link} from "react-router";

interface LinkProps {
    ...
}

const LinkPresenter = (props: LinkProps): JSX.Element =>
    <Link
        ...
    >
        ...
    </Link>;

LinkPresenter.defaultProps = { // !!! unresolved variable defaultProps
    ...
};

答案 1 :(得分:1)

为了扩展我们的对话,以下是使用TS / ES6默认属性方法的替代方法:

import {Link} from "react-router";

interface LinkProps {
    to?: HistoryModule.LocationDescriptorObject;
    onClick?: (event: React.FormEvent) => void;
    children?: React.ReactNode;
}

let defaultProps : LinkProps = {
  to: {
        pathname: `/homepage`,
        query: {
            default: 'someDefault'
        }
  },
  onClick: () => {},
  children: <span>Hello world</span>
}

const LinkPresenter = (props: LinkProps = defaultProps): JSX.Element =>
    <Link
        className="link"
        to={props.to}
        onClick={props.onClick}
    >
        {props.children}
    </Link>;
相关问题