reactjs - 使用 TypeScript 3 扩展道具的 React 组件中的默认属性值
问题描述
我在 jsx 中使用对 defaultprops 的支持,如https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#support-for-defaultprops-in-jsx中所述
一切正常,除非我用另一个接口扩展道具。在这种情况下,我在子组件中扩展我的道具,例如
interface Props extends WithNamespaces {
className: string;
}
并声明默认道具:
const defaultProps = {
className: ''
};
*WithNamespaces是 react-i18next 的一个接口
在我的父组件中,我收到子组件缺少属性 className 的编译错误,即使它应该是可选的,对吗?
是否应该采取不同的措施来保持这些默认道具不是强制性的?
解决方案
Props
需要className
道具。如果它是可选的,则取决于接口的使用方式,应在接口本身中将其标记为:
interface Props extends WithNamespaces {
className?: string;
}
或者使用它的地方:
class Comp extends Component<Partial<Props>> {
static defaultProps: Props = {
className: ''
};
...
}
推荐阅读
- javascript - 我们可以直接在反应js渲染函数中使用boostrap类吗
- html - 如何设置div元素的css覆盖顶部
- rabbitmq - 为什么 ConfirmCallback#confirm#CorrelationData 只有一个属性 id 而不是整个消息,以便我可以立即重新发送消息
- java - 如何在 NetBeans 上放大/缩小视图设计
- java - 我尝试使用 Web 套接字将一些对象从 Java 服务器传输到有角度的网页
- windows - 在 Inno Setup 中重新安装和卸载时停止 Windows 服务
- java - maven 依赖项 - 哪个依赖项正在使用不需要的 jar?
- wcf - 为什么我无法访问托管在 Windows 服务中的 wcf?
- rasa - rasa init --no-prompt 抛出导入错误
- java - 如何管理 Firebase Firestore 中的可选值并避免数据库中的空字段?