作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有这个组件类:
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/
我是一名优秀的程序员,十分优秀!