reactjs - 如何提取作为道具传递给React函数组件的属性的嵌套类型
问题描述
如果我为功能组件定义了一个接口,比如说
MyFuncComp.tsx
import React from 'react'
interface MyFuncCompProps {
x: string
y: number
z: Array<ComplexType>
}
export function MyFuncComp(props: MyFuncCompProps) {
return <>...</>
}
我在另一个组件中使用该组件
MyPage.tsx
import React from 'react'
import {MyFuncComp} from 'MyFuncComp.tsx'
export function MyPage(){
const [x, setX] = React.useState()
const [y, setY] = React.useState()
const [z, setZ] = React.useState()
return <><MyFuncComp x={x} y={y} z={z} /></>
}
如何提取函数组件中定义的属性的类型,以便我也可以使用相同的类型MyPage.tsx
?
我知道我可以完全导出/导入接口,但我想避免这种情况。
解决方案
MyFuncComp
我可以从以下中的功能组件推断类型MyPage.tsx
:
import {MyFuncComp} from 'MyFuncComp.tsx'
const InferredTypes = React.ComponentProps<typeof MyFuncComp>
export function MyPage(){
const [x, setX] = React.useState<InferredTypes['x']>()
const [y, setY] = React.useState<InferredTypes['y']>()
const [z, setZ] = React.useState<InferredTypes['z']>()
return <><MyFuncComp x={x} y={y} z={z} /></>
}
推荐阅读
- r - R闪亮中更新的奇怪行为
- email - 在 MODX 片段中更改 mail_smtp_user
- python - 在运行 return 语句时,我得到了一些不好的输出,不知道为什么?
- python - Python中按位左移的最大限制
- python-3.x - 如何返回列表列表中元素的索引?
- php - Typo3:将 USER_INT 与 HMENU 的 special.value 一起使用
- snowflake-cloud-data-platform - 如何在 Snowflake 中使用 Javascript 存储过程执行 SQL UDF 的输出?
- google-sheets - 如何从另一个 Google 表格文档中导入前 7 天数据的平均值?
- firebase - 跳过使用 firebase init 托管创建拉取请求操作:github
- c# - 在 C3 powershell 中使用 ScriptBlock 和 WSManConnectionInfo