我将React与TypeScript一起使用,并且创建了无状态函数。为了便于阅读,我从示例中删除了无用的代码。
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>; };
一切都很好,此代码可以正常工作。但有我的问题:我怎么可以定义defaultProps为CenterBox组件?
defaultProps
CenterBox
正如在react docs中提到的那样:
(…)它们是输入的纯函数转换,带有零样板。但是,仍然可以通过将.propTypes和 .defaultProps 设置为函数的属性来指定 它们,就像在ES6类上进行设置一样。(…)
它应该很容易,因为:
CenterBox.defaultProps = { minHeight: 250 }
但是这段代码会产生TSLint错误: error TS2339: Property 'defaultProps' does not exist on type '(props: CenterBoxProps) => Element'.
error TS2339: Property 'defaultProps' does not exist on type '(props: CenterBoxProps) => Element'.
再说一遍:如何正确定义defaultProps上述堆栈(React + TypeScript)?
寻找解决方案2个小时后, 它开始起作用 。
如果要定义defaultProps,则箭头函数应如下所示:
export const CenterBox: React.SFC<CenterBoxProps> = props => { (...) };
然后,您可以定义道具,例如:
CenterBox.defaultProps = { someProp: true }
请注意,这React.SFC是的别名React.StatelessComponent。
React.SFC
React.StatelessComponent
我希望这个问题(和答案)能帮助到别人。确保您已经安装了最新的React类型。