gpt4 book ai didi

reactjs - React-Typescript : How do I type a default prop?

转载 作者:行者123 更新时间:2023-12-02 16:36:14 25 4
gpt4 key购买 nike

假设我有这个组件类:

interface SomeComponentProps {
someOptionalProperty?: string;
}
interface SomeComponentState { /* ... */ }

class SomeComponent extends React.Component<SomeComponentProps, SomeComponentState> {
static defaultProps = {
someOptionalProp = 'some default value',
}

method() {
const shouldNotBeOptional = this.props.someOptionalProp;
}
}

如何断言 this.props.someOptionalProp 在类中不是未定义的,而且在尝试使用组件时也是可选的?

我一直在做的只是通过创建 getter 来完全忽略 defaultProps

return `this.props.someOptionalProp || 'the default value'`;

但我想使用 defaultProps 因为我的团队使用它。

最佳答案

此问题已在 here 中讨论并解决。 。现在您只需这样做:

interface Props {
thing: string; // note: not optional within class, but is optional when writing due to the default
}

class Thing extends React.Component<Props> {
static defaultProps = {
thing: 'hello'
}

render() {
console.log(this.props.thing) // strict type from `Props`
// ...
}
}
// ..
<Thing /> // works, thanks to `defaultProps`

它适用于 Typescript 3.1.6 和 React 16.5.0

关于reactjs - React-Typescript : How do I type a default prop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50272065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com