与 TypeScript 反应 - 在无状态函数中定义 defaultProps
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37262047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React with TypeScript - define defaultProps in stateless function
提问by Mateusz Jagie??o
I'm using React with TypeScript and I've created stateless function. I've removed useless code from the example for readability.
我正在将 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>;
};
Everything is great and this code is working correctly. But there's my question: how can I define defaultProps
for CenterBox
component?
一切都很好,这段代码工作正常。但有我的问题:我怎么可以定义defaultProps
为CenterBox
组件?
As it is mentioned in react docs:
正如反应文档中提到的那样:
(...) They are pure functional transforms of their input, with zero boilerplate. However, you may still specify .propTypes and .defaultPropsby setting them as properties on the function, just as you would set them on an ES6 class. (...)
(...) 它们是输入的纯函数转换,零样板。但是,您仍然可以通过将.propTypes 和.defaultProps设置为函数的属性来指定 它们,就像在 ES6 类上设置它们一样。(...)
it should be easy as:
它应该很容易,因为:
CenterBox.defaultProps = {
minHeight: 250
}
But this code generates TSLint error: error TS2339: Property 'defaultProps' does not exist on type '(props: CenterBoxProps) => Element'.
但是这段代码会产生 TSLint 错误: error TS2339: Property 'defaultProps' does not exist on type '(props: CenterBoxProps) => Element'.
So again: how can I correctly define defaultProps
in my above stack (React + TypeScript)?
再说一遍:如何defaultProps
在上面的堆栈(React + TypeScript)中正确定义?
回答by Mateusz Jagie??o
After 2 hours of looking for solution... it's working.
经过 2 个小时的寻找解决方案......它正在工作。
If you want to define defaultProps
, your arrow function should look like:
如果你想定义defaultProps
,你的箭头函数应该是这样的:
export const CenterBox: React.SFC<CenterBoxProps> = props => {
(...)
};
Then you can define props like:
然后你可以定义道具,如:
CenterBox.defaultProps = { someProp: true }
Note that React.SFC
is alias for React.StatelessComponent
.
请注意,这React.SFC
是 的别名React.StatelessComponent
。
I hope that this question (and answer) help somebody. Make sure that you have installed newest React typings.
我希望这个问题(和答案)对某人有所帮助。确保你已经安装了最新的 React 类型。
回答by Mark Peterson
And here's how it works for stateful functions in case others stumble on this. The key is declaring defaultPropsas a static variable.
这是它如何用于有状态函数,以防其他人偶然发现。关键是将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;
};
回答by pete otaqui
I believe a better way than described in the React docs is simply to use Javascript / Typescript default arguments.
我相信比 React 文档中描述的更好的方法是简单地使用 Javascript / Typescript 默认参数。
There's an answer here: https://stackoverflow.com/a/54569933/484190but for convenience, here's an example:
这里有一个答案: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;
This will allow Typescript to know that you don't have to provide the prop, and also that it will never be "undefined" inside your component
这将使 Typescript 知道您不必提供道具,并且它永远不会在您的组件中“未定义”
回答by robstarbuck
For Functional Componentsas of React 16.7.0the 'React.SFC' type is being deprecated in favour of 'React.FC
'.
对于React 16.7.0 起的功能组件,'React.SFC' 类型被弃用,取而代之的是 ' '。React.FC
Example
例子
type TFuncComp = React.FC<{ text: string }>
const FuncComp: TFuncComp = props => <strong>{props.text}</strong>
FuncComp.defaultProps = { text: 'Empty Text' }
回答by apollo
Typing default props in function component with React.FC can result in false type error:
使用 React.FC 在函数组件中输入默认 props 可能会导致错误类型错误:
type Props = {
required: string,
} & typeof defaultProps;
const defaultProps = {
optDefault: 'optDefault'
};
const MyComponent: React.FC<Props> = (props: Props) => (
<ul>
<li>required: {props.required}</li>
<li>optDefault: {props.optDefault}</li>
</ul>
)
MyComponent.defaultProps = defaultProps;
ReactDOM.render(
<div>
<MyComponent
required='required'
optDefault='over written'
/>
<MyComponent /* type error <---- false type error */
required='required'
/>
</div>,
document.getElementById('app')
);
error:
错误:
[tsserver 2741] Property 'optDefault' is missing in type '{ required: string; }' but required in type '{ optDefault: string; }'. [E]
Another solution proposed is to use Javascript's own default function parameters:
提出的另一个解决方案是使用 Javascript 自己的默认函数参数:
type Props = {
required: string,
optDefault?: string
}
const MyComponent: React.FC<Props> = ({
required,
optDefault='default'
}: Props) => (
<ul>
<li>required: {required}</li>
<li>optDefault: {optDefault}</li>
</ul>
)
ReactDOM.render(
<div>
<MyComponent
required='required'
optDefault='over written'
/>
<MyComponent
required='required'
/>
</div>,
document.getElementById('app')
);
But the problem with this solution is that if you forgot to provide default, a run time bug will result:
但是这个解决方案的问题是,如果你忘记提供默认值,就会导致一个运行时错误:
const MyComponent: React.FC<Props> = ({
required,
optDefault //='optDefault' //<--- if you forgot to provide default
}: Props) => (
<ul>
<li>required: {required}</li>
<li>optDefault: {optDefault}</li> {/* <-- result in bug */}
</ul>
)
A better solution is not using React.FC at all, simply rely on Typescript type inference:
更好的解决方案是根本不使用 React.FC,只需依靠 Typescript 类型推断:
type Props = {
required: string,
} & typeof defaultProps;
const defaultProps = {
optDefault: 'optDefault'
};
const MyComponent = (props: Props) => (
<ul>
<li>required: {props.required}</li>
<li>optDefault: {props.optDefault}</li>
</ul>
)
MyComponent.defaultProps = defaultProps
ReactDOM.render(
<div>
<MyComponent
required='required'
optDefault='over written'
/>
<MyComponent
required='required'
/>
</div>,
document.getElementById('app')
);
回答by Arnd Brugman
Simplest for me is to define (partial) defaults in the defaultProps directly:
对我来说最简单的是直接在 defaultProps 中定义(部分)默认值:
export default class TSError extends React.Component<ITSErrorProps, {}> {
private static defaultProps: Partial<ITSErrorProps> = {
fullPage: true,
controlClick: true,
doubleClick: true
};
...
}
回答by Israel kusayev
You can put this inside your component
你可以把它放在你的组件中
static defaultProps: any;