2016-05-16 91 views
9

我正在使用React与TypeScript并创建了无状态函数。为了便于阅读,我从示例中删除了无用的代码。与TypeScript反应 - 在无状态函数中定义defaultProps

interface CenterBoxProps extends React.Props<CenterBoxProps> { 
    minHeight?: number; 
} 

export const CenterBox = (props: CenterBoxProps) => { 
    const minHeight = props.minHeight || 250; 
    const style = { 
     minHeight: minHeight 
    }; 
    return <div style={style}>Example div</div>; 
}; 

一切都很好,这段代码工作正常。但是我的问题是:如何为CenterBox组件定义defaultProps?正确哪能:

正如在react docs提到:如此反复error TS2339: Property 'defaultProps' does not exist on type '(props: CenterBoxProps) => Element'.

CenterBox.defaultProps = { 
    minHeight: 250 
} 

但这个代码生成TSLint错误:

(...) They are pure functional transforms of their input, with zero boilerplate. However, you may still specify .propTypes and .defaultProps by setting them as properties on the function, just as you would set them on an ES6 class. (...)

,因为它应该很容易在我的上面的堆栈(React + TypeScript)中定义defaultProps

回答

10

经过2个小时寻找解决方案... 它的工作

如果你想定义deufaultProps你的函数定义行应该是这样的:

export const CenterBox: React.SFC<CenterBoxProps> = props => { 
    (...) 
}; 

然后,你可以这样定义道具:

CenterBox.defaultProps = { someProp: true } 

注意React.SFC是别名React.StatelessComponent

我希望这个问题(和答案)有助于某人。确保你已经安装了最新的React类型。

+2

你可以在如何获得defaultProps工作上添加一个更具体的例子吗?感谢:D –

2

下面是它如何工作的状态功能,以防其他人偶然发现这一点。 关键是声明defaultProps作为一个静态变量。

interface IBoxProps extends React.Props<IBoxProps> { 
    x?: number; 
    y?: number; 
    height?: number; 
    width?: number; 
} 

interface IBoxState { 
    visible?: boolean; 
} 

export default class DrawBox extends React.Component<IBoxProps, IBoxState> { 
    static defaultProps: IBoxProps; 

    constructor(props: IBoxProps) { 
     super(props); 
    } 
    ... 
} 

DrawBox.defaultProps = { 
    x=0; 
    y=0; 
    height=10; 
    weight=10; 
}; 
相关问题