我无法弄清楚如何使用我的打字原稿设置组件的默认属性值。
这是源代码:
class PageState
{
}
export class PageProps
{
foo: string = "bar";
}
export class PageComponent extends React.Component<PageProps, PageState>
{
public render(): JSX.Element
{
return (
<span>Hello, world</span>
);
}
}
当我尝试使用该组件是这样的:
ReactDOM.render(<PageComponent />, document.getElementById("page"));
我得到一个错误说属性foo
缺失。 我想使用默认值。 我也试图用static defaultProps = ...
在组件内部,但它没有任何效果,因为我怀疑。
src/typescript/main.tsx(8,17): error TS2324: Property 'foo' is missing in type 'IntrinsicAttributes & IntrinsicClassAttributes<PageComponent> & PageProps & { children?: ReactEle...'.
如何使用默认属性值? 很多JS组件公司使用依赖于他们,而不是使用它们不是一种选择。
Default props with class component
Using static defaultProps
is correct. You should also be using interfaces, not classes, for the props and state.
Update 2018/12/1: TypeScript has improved the type-checking related to defaultProps
over time. Read on for latest and greatest usage down to older usages and issues.
For TypeScript 3.0 and up
TypeScript specifically added support for defaultProps
to make type-checking work how you'd expect. Example:
interface PageProps {
foo: string;
bar: string;
}
export class PageComponent extends React.Component<PageProps, {}> {
public static defaultProps = {
foo: "default"
};
public render(): JSX.Element {
return (
<span>Hello, { this.props.foo.toUpperCase() }</span>
);
}
}
Which can be rendered and compile without passing a foo
attribute:
<PageComponent bar={ "hello" } />
Note that:
foo
is not marked optional (ie foo?: string
) even though it's not required as a JSX attribute. Marking as optional would mean that it could be undefined
, but in fact it never will be undefined
because defaultProps
provides a default value. Think of it similar to how you can mark a function parameter optional, or with a default value, but not both, yet both mean the call doesn't need to specify a value. TypeScript 3.0+ treats defaultProps
in a similar way, which is really cool for React users!
- The
defaultProps
has no explicit type annotation. Its type is inferred and used by the compiler to determine which JSX attributes are required. You could use defaultProps: Pick<PageProps, "foo">
to ensure defaultProps
matches a sub-set of PageProps
. More on this caveat is explained here.
- This requires
@types/react
version 16.4.11
to work properly.
For TypeScript 2.1 until 3.0
Before TypeScript 3.0 implemented compiler support for defaultProps
you could still make use of it, and it worked 100% with React at runtime, but since TypeScript only considered props when checking for JSX attributes you'd have to mark props that have defaults as optional with ?
. Example:
interface PageProps {
foo?: string;
bar: number;
}
export class PageComponent extends React.Component<PageProps, {}> {
public static defaultProps: Partial<PageProps> = {
foo: "default"
};
public render(): JSX.Element {
return (
<span>Hello, world</span>
);
}
}
Note that:
- It's a good idea to annotate
defaultProps
with Partial<>
so that it type-checks against your props, but you don't have to supply every required property with a default value, which makes no sense since required properties should never need a default.
- When using
strictNullChecks
the value of this.props.foo
will be possibly undefined
and require a non-null assertion (ie this.props.foo!
) or type-guard (ie if (this.props.foo) ...
) to remove undefined
. This is annoying since the default prop value means it actually will never be undefined, but TS didn't understand this flow. That's one of the main reasons TS 3.0 added explicit support for defaultProps
.
Before TypeScript 2.1
This works the same but you don't have Partial
types, so just omit Partial<>
and either supply default values for all required props (even though those defaults will never be used) or omit the explicit type annotation completely.
Default props with Functional Components
You can use defaultProps
on function components as well, but you have to type your function to the StatelessComponent
(FunctionComponent
in @types/react
version 16.7.2
+) interface so that TypeScript knows about defaultProps
on the function:
interface PageProps {
foo?: string;
bar: number;
}
const PageComponent: StatelessComponent<PageProps> = (props) => {
return (
<span>Hello, {props.foo}, {props.bar}</span>
);
};
PageComponent.defaultProps = {
foo: "default"
};
Note that you don't have to use Partial<PageProps>
anywhere because StatelessComponent.defaultProps
is already specified as a partial in TS 2.1+.
Another nice alternative (this is what I use) is to destructure your props
parameters and assign default values directly:
const PageComponent: StatelessComponent<PageProps> = ({foo = "default", bar}) => {
return (
<span>Hello, {foo}, {bar}</span>
);
};
Then you don't need the defaultProps
at all! Be aware that if you do provide defaultProps
on a function component it will take precedence over default parameter values, because React will always explicitly pass the defaultProps
values (so the parameters are never undefined, thus the default parameter is never used.) So you'd use one or the other, not both.
与打字稿2.1+,使用偏<T>而不是使你的界面特性是可选的。
export interface Props {
obj: Model,
a: boolean
b: boolean
}
public static defaultProps: Partial<Props> = {
a: true
};
随着打字稿3.0有一个新的解决方案这个问题:
export interface Props {
name: string;
}
export class Greet extends React.Component<Props> {
render() {
const { name } = this.props;
return <div>Hello ${name.toUpperCase()}!</div>;
}
static defaultProps = { name: "world"};
}
// Type-checks! No type assertions needed!
let el = <Greet />
需要注意的是这个工作,你需要一个新版本@types/react
比16.4.6
。 它的工作原理与16.4.11
。
从上公认的答案@pamelus评论:
要么你必须让所有的接口特性可选的(坏的)或指定默认值也为所有必填字段(不必要的样板)或避免defaultProps指定类型。
其实你可以使用打字稿的接口继承 。 生成的代码只有一点点更详细。
interface OptionalGoogleAdsProps {
format?: string;
className?: string;
style?: any;
scriptSrc?: string
}
interface GoogleAdsProps extends OptionalGoogleAdsProps {
client: string;
slot: string;
}
/**
* Inspired by https://github.com/wonism/react-google-ads/blob/master/src/google-ads.js
*/
export default class GoogleAds extends React.Component<GoogleAdsProps, void> {
public static defaultProps: OptionalGoogleAdsProps = {
format: "auto",
style: { display: 'block' },
scriptSrc: "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
};
对于需要默认值是具有可选的道具。 信用在这里:)
interface Props {
firstName: string;
lastName?: string;
}
interface DefaultProps {
lastName: string;
}
type PropsWithDefaults = Props & DefaultProps;
export class User extends React.Component<Props> {
public static defaultProps: DefaultProps = {
lastName: 'None',
}
public render () {
const { firstName, lastName } = this.props as PropsWithDefaults;
return (
<div>{firstName} {lastName}</div>
)
}
}