Reactjs 使用来自某个数据库的类型正确发布
在使用HOC时,我在正确输入类型方面遇到了一些问题。我有这个Reactjs 使用来自某个数据库的类型正确发布,reactjs,typescript,Reactjs,Typescript,在使用HOC时,我在正确输入类型方面遇到了一些问题。我有这个 导出接口IWithLangProps{ 朗:宜兰; } 常量withLang=(组件:React.ComponentType): React.ComponentClass | React.FunctionComponent=> 类包装器组件扩展组件{ render():JSX.Element{ 返回( {(值:IWithLangProps):JSX.Element=> } ); } }; 现在我有了一个使用HOC的组件 导出接口IG
导出接口IWithLangProps{
朗:宜兰;
}
常量withLang=(组件:React.ComponentType):
React.ComponentClass | React.FunctionComponent=>
类包装器组件扩展组件{
render():JSX.Element{
返回(
{(值:IWithLangProps):JSX.Element=>
}
);
}
};
现在我有了一个使用HOC的组件
导出接口IGridSearchProps{
searchDelay?:数字;
onChange:(值:string)=>void;
}
/**
*GridSearch用于在数据网格上显示搜索字段
*/
const GridSearch=(props:IGridSearchProps):JSX.Element=>{
常数{
一旦改变,
搜索延迟=300,
lang,//此处的Typescript错误,因为它找不到HOC提供的lang
}=道具;
返回(
);
};
GridSearch.displayName='GridSearch';
使用lang导出默认值(GridSearch);
这是我的问题。如何让
GridSearch
正确了解lang?我尝试用IWithLangProps
扩展IGridSearchProps
,但是如果我这样做,任何使用GridSearch
的组件都希望lang
在props中。因为GridSearch
需要lang
它应该在GridSearch
的props中<代码>withLang然后可以使用省略从生成组件的道具中删除lang
:
export interface IWithLangProps {
lang: ILang;
}
type Omit<T, K extends PropertyKey> = Pick<T, Exclude<keyof T, K>> // Included in 3.5
const withLang = <T extends object>(Comp: React.ComponentType<T>): React.ComponentType<Omit<T, keyof IWithLangProps>> =>
class WrapperComponent extends Component<Omit<T, keyof IWithLangProps>> {
render(): JSX.Element {
return (
<LangConsumer>
{(value: IWithLangProps): JSX.Element =>
<Comp {...this.props as T} lang={value.lang} />
}
</LangConsumer>
);
}
};
export interface IGridSearchProps extends IWithLangProps{
searchDelay?: number;
onChange: (value: string) => void;
}
/**
* GridSearch for displaying search field on data grids
*/
const GridSearch = (props: IGridSearchProps): JSX.Element => {
const {
onChange,
searchDelay = 300,
lang, // Typescript errors here since it cant find lang provided by the HOC
} = props;
return (
<Search
placeholder={lang.trans('s.search_the_table')}
onChange={onChange}
searchDelay={searchDelay}
/>
);
};
GridSearch.displayName = 'GridSearch';
export default withLang(GridSearch);
导出接口IWithLangProps{
朗:宜兰;
}
类型省略=拾取//包含在3.5中
常量withLang=(Comp:React.ComponentType):React.ComponentType=>
类包装器组件扩展组件{
render():JSX.Element{
返回(
{(值:IWithLangProps):JSX.Element=>
}
);
}
};
导出接口IGridSearchProps扩展了IWithLangProps{
searchDelay?:数字;
onChange:(值:string)=>void;
}
/**
*GridSearch用于在数据网格上显示搜索字段
*/
const GridSearch=(props:IGridSearchProps):JSX.Element=>{
常数{
一旦改变,
搜索延迟=300,
lang,//此处的Typescript错误,因为它找不到HOC提供的lang
}=道具;
返回(
);
};
GridSearch.displayName='GridSearch';
使用lang导出默认值(GridSearch);
我有个问题。IGridSearchProps
或GridSearch
是否可以了解lang
w/o在接口定义中扩展它?由于这个HOC在很多地方都有使用,所以如果这个部分可以自动化就好了。@topched您需要以某种方式将它添加到每个组件中,另一种方法是使用交叉点(props:IGridSearchProps&IWithLangProps)…
是的,我有点想。我希望有一些神奇的东西,我不需要在任何地方抓取使用Lang的界面。不管怎样,谢谢你,这很管用。