我有一个Dictionary属性非常简单的组件:
interface DictionaryProps {
word: string;
}
在另一个组件的道具中,我请求了一个只需要一个字符串单词的通用组件:
dictionary: React.ComponentClass<{ word: string }>;
它的父母像这样使用它:
<UsesDictionary dictionary={Dictionary} />
现在我想尝试 JSS(MaterialUI 已经在整个项目中使用,所以不,整个库不仅仅用于单个组件)。我创建了一些样式并DictionaryProps相应地更新了:
const styles = createStyles({ root: { position: 'relative' } });
interface DictionaryProps extends WithStyles<typeof styles>{
word: string;
}
class Dictionary extends React.Component<DictionaryProps> {}
export default withStyles(styles)(Dictionary);
Dictionary将样式传递给React.ComponentClass-accepting时会产生以下编译错误UsesDictionary:
Types of property 'dictionary' are incompatible.
Type 'ComponentType<Overwrite<DictionaryProps, StyledComponentProps<"root">>>' is not assignable to type 'ComponentClass<{ word: string; }> & ComponentClass<{ word: string; }>'.
Type 'StatelessComponent<Overwrite<DictionaryProps, StyledComponentProps<"root">>>' is not assignable to type 'ComponentClass<{ word: string; }> & ComponentClass<{ word: string; }>'.
Type 'StatelessComponent<Overwrite<DictionaryProps, StyledComponentProps<"root">>>' is not assignable to type 'ComponentClass<{ word: string; }>'.
我通过直接使用它来确认Dictionary匹配:React.ComponentClass<{ word: string }>
<Dictionary word={dictionarySearch} />
这表明我没有弄乱Dictionary.
我可以使用
any而不是具体类型,但我已经为这个项目设置了一个规则,不要使用any. 无论如何,这是一种不好的做法,因为它失去了类型安全性。我尝试直接使用错误中的类型 -
StatelessComponent<Overwrite<DictionaryProps, StyledComponentProps<"root">>>。但是:- 它有一些
Overwrite我不知道的类型,也没有找到它所在的位置。我猜它来自 MaterialUI,我不想链接UsesDictionary到它。 - 它需要样式
DictionaryProps化的,而不仅仅是{word: string}部分,。而且我不想将 myUsesDictionary与任何具体的字典类型结合起来,所以我不希望它知道字典是否使用withStyles。
即使用错误中的类型不是一个可行的选择。
- 它有一些
其他有withStyles问题的人使用它作为装饰器,因此他们的错误。在这里,这不适用,因为我已经将withStyles其用作普通函数。
简而言之: