Javascript 在React Typescript中,是否可以将组件道具接口与另一道具一起使用?
基本上,我希望lineJavascript 在React Typescript中,是否可以将组件道具接口与另一道具一起使用?,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,基本上,我希望lineinjectComponentProps:object动态绑定到injectComponent的prop接口。在本例中,它将是injectComponentProps:InjectedComponentProps,但我希望它是动态的 也就是说,一旦在中设置了prop injectComponent,injectComponentProps就会被定义为injectComponent的components props 这可能吗 接口注入组件props{ 变体:字符串 尺码:号码
injectComponentProps:object
动态绑定到injectComponent的prop接口。在本例中,它将是injectComponentProps:InjectedComponentProps
,但我希望它是动态的
也就是说,一旦在中设置了prop injectComponent,injectComponentProps就会被定义为injectComponent的components props
这可能吗
接口注入组件props{
变体:字符串
尺码:号码
}
常量InjectedComponent:React.FC=(props)=>{
打招呼
}
接口组件{
injectComponent:React.ReactType
injectComponentProps:对象
}
常量组件:React.FC=(道具)=>{
const InjectedComponent=props.injectComponent
返回(
)
}
常量Main:React.FC=()=>{
返回(
)
}
接口注入组件props{
变体:字符串
尺码:号码
}
常量InjectedComponent:React.FC=(props)=>{
返回空
}
接口组件{
注入组件:React.FC
注射剂成分:T
}
常量组件=(props:ComponentProps):JSX.Element=>{
const InjectedComponent=props.injectComponent
返回(
)
}
常量Main:React.FC=()=>{
返回(
)
}
不要简单地将类型声明为对象
,您应该尝试将组件属性
修改为可以推断其类型参数属性的组件
genericGetProps
用于从组件推断props,即推断generic的类型参数
type GetProps<C extends React.ComponentType<any>> = C extends React.ComponentType<infer P> ? P : any
interface InjectedComponentProps {
variant: string
size: number
}
const InjectedComponent: React.FC<InjectedComponentProps> = (props) => {
return <Text {...props}>hello</Text>
}
// make this a generic type
interface ComponentProps<C extends React.ComponentType<any>> {
injectComponent: C
injectComponentProps: GetProps<C>
}
// and use it here
const Component: React.FC<ComponentProps<typeof InjectedComponent>> = (props) => {
const InjectedComponent = props.injectComponent
return (
<>
<InjectedComponent {...props.injectComponentProps}/>
</>
)
}
const Main: React.FC = () => {
return (
<Component
injectComponent={InjectedComponent}
injectComponentProps={{ variant: 'footnote', size: 14 }}
/>
)
}
type GetProps=C扩展React.ComponentType?P:有吗
接口注入组件props{
变体:字符串
尺码:号码
}
常量InjectedComponent:React.FC=(props)=>{
打招呼
}
//使其成为泛型类型
接口组件{
注射组分:C
injectComponentProps:GetProps
}
//在这里使用它
常量组件:React.FC=(道具)=>{
const InjectedComponent=props.injectComponent
返回(
)
}
常量Main:React.FC=()=>{
返回(
)
}
这不是关于泛型吗?(或者我不明白这个问题)。类似于interface ComponentProps
然后injectComponentProps:T
?看看这个