Mat*_*łło 21 typescript reactjs
我正在使用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>;
};
Run Code Online (Sandbox Code Playgroud)
一切都很棒,这段代码工作正常.但有我的问题:我怎么可以定义defaultProps为CenterBox组件?
正如反应文档中提到的那样:
(...)它们是输入的纯函数变换,没有样板.但是,您仍然可以通过将它们设置为函数的属性来指定.propTypes和 .defaultProps,就像在ES6类上设置它们一样.(......)
它应该很容易:
CenterBox.defaultProps = {
minHeight: 250
}
Run Code Online (Sandbox Code Playgroud)
但是此代码生成TSLint错误: error TS2339: Property 'defaultProps' does not exist on type '(props: CenterBoxProps) => Element'.
再说一遍:我怎样才能defaultProps在上面的堆栈中正确定义(React + TypeScript)?
Mat*_*łło 23
经过2个小时的寻找解决方案...... 它正在发挥作用.
如果要定义defaultProps函数定义行应该如下所示:
export const CenterBox: React.SFC<CenterBoxProps> = props => {
(...)
};
Run Code Online (Sandbox Code Playgroud)
然后你可以定义道具,如:
CenterBox.defaultProps = { someProp: true }
Run Code Online (Sandbox Code Playgroud)
请注意,这React.SFC是别名React.StatelessComponent.
我希望这个问题(和答案)对某人有所帮助.确保您已安装最新的React类型.
小智 21
我相信比 React 文档中描述的更好的方法是简单地使用 Javascript / Typescript 默认参数。
这里有一个答案:https : //stackoverflow.com/a/54569933/484190但为了方便起见,这里有一个例子:
import React, { FC } from "react";
interface CompProps {
x?: number;
y?: number;
}
const Comp: FC<CompProps> = ({ x = 10, y = 20 }) => {
return <div>{x}, {y}</div>;
}
export default Comp;
Run Code Online (Sandbox Code Playgroud)
这将使 Typescript 知道您不必提供道具,并且它永远不会在您的组件中“未定义”
Mar*_*son 10
以下是有关状态函数的工作原理,以防其他人偶然发现这种情况.关键是将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;
};
Run Code Online (Sandbox Code Playgroud)
对于React 16.7.0 起的功能组件,'React.SFC' 类型被弃用,取而代之的是 ' '。React.FC
type TFuncComp = React.FC<{ text: string }>
const FuncComp: TFuncComp = props => <strong>{props.text}</strong>
FuncComp.defaultProps = { text: 'Empty Text' }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10051 次 |
| 最近记录: |