reactjs - 如何使用打字稿渲染条件道具并做出反应?
问题描述
我似乎无法访问道具形状
https://cdn.discordapp.com/attachments/508357248330760249/831773180162998292/Untitled.png
解决方案
TypeScript 引发了该错误,因为该属性仅为 定义shape: 'circle'
,因此您必须通过匹配标记来缩小其类型,在本例中为shape
属性。
例子:
type ButtonProps = { fullName: string } & (
| { shape: 'circle'; radius: number }
| { shape: 'square'; width: number }
)
declare const props: ButtonProps
props.radius // Property 'radius' does not exist on type 'ButtonProps'
if (props.shape === 'circle') {
props.radius // number
}
请参阅https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions。
推荐阅读
- android - Android Studio:允许用户将图像添加到可绘制文件夹?
- javascript - 在 Laravel 中,如何将下拉列表的多个值添加为单个数据库单元格中的对象
- javascript - 将数组中的值设置为对象中的键减少/返回对象内的值
- javascript - 如何在js中给定数字之间随机选择一个数字?
- random - 如何创建一个随机数序列
- python - 如何从矩阵中选择行或列?
- javascript - 定义在模块中发生事件时调用的方法
- php - Magento 我的第一个自定义模块给出 404 not found
- firebase - 当我在 React Native App 中不使用“Debug JS Remotly”模式时,Firebase 身份验证失败
- spring-boot - java.lang.ExceptionInInitializerError 在 Spring-boot 应用程序中使用 lombok 时产生