我想给我的React组件道具一个泛型类型,但是当我将它包装在一个更高阶的组件(material-ui)中时,如何传递所需的信息会丢失它?
type Props<T> = {
data: Array<T>;
}
class MyComponent<T> extends React.Component<Props<T>> {
const StyledComponent = withStyles(styles)(MyComponent)
使用<StyledComponent<myType
会产生错误,因为它不了解通用。
答案 0 :(得分:1)
我的赌注是这样注释新组件:
const MenuItem = ({title,indicatorColor,index,onPressItem}) => {
const onMenuItemPress = (index) => {
console.log('menu selected:'.index);
}
return (
<TouchableOpacity onPress={()=>onPressItem(index)} >
<View
style={{
paddingLeft: 20,
paddingBottom: 15,
paddingTop: 15,
flexDirection: 'row',
width: 150,
borderRightWidth: 2,
borderRightColor: 'Colors.GREY_TWO',
backgroundColor: indicatorColor,
alignItems: 'center',
}}>
<View
style={{
backgroundColor: 'black',
height: 5,
width: 5,
borderRadius: 3,
alignSelf: 'center',
}}
/>
<Text style={{fontSize: 15, left: 5,alignItems: 'center',}}>{title}
</Text>
</View>
</TouchableOpacity>
)
};
<MenuItem title='Sort' indicatorColor='red' index='0' onPress={onMenuItemPress} />
请注意,您可能需要区分const StyledComponent: <T>(props: OuterProps<T>) => JSX.Element = withStyles(styles)(MyComponent) ;
和OuterProps
,请参见下面的示例供我参考:
https://stackblitz.com/edit/hoc-generics
希望有帮助!