我正在Typescript环境中学习React,并试图创建一个连接到react-redux存储的高阶组件。
/**
* HoC that renders errors on the redux store raised for a component.
* @param BaseComponent The component to wrap should have uniqueId property
*/
export const withErrorListener = <BaseProps extends ExpectedProps>(
BaseComponent: React.ComponentType<BaseProps>
) => {
/**
* Type declarations
*/
type HocProps = BaseProps & ReduxProps & RouteComponentProps;
class ErrorListener extends React.Component<HocProps, {}> {
static displayName = `withErrorListener(${BaseComponent.name})`;
static readonly WrappedComponent = BaseComponent;
/**
* Render error if there is one to display, otherwise render the base component
* @returns Rendered error if error occurred. Rendered base component if no error occurred.
*/
render() {
const { ...restProps } = this.props;
console.log(`withErrorListener [error_count=${this.props.error.length}]`);
if (this.props.error.length > 0) {
return <ErrorInfo info={this.props.error[0]} {...restProps} />;
} else {
return <BaseComponent {...restProps as BaseProps} />;
}
}
}
// if I take out the any casts here get a compiler error against property mismatch
// how do I get this correctly typed?
const ConnectedHoc = connector(ErrorListener as any);
const RoutedHoc = withRouter(ConnectedHoc as any);
return RoutedHoc;
};
如果我删除了对react-redux和withRouter的任何强制类型转换,那么我会收到有关属性不匹配的编译错误。如何才能正确键入HoC以避免转换为任何?
答案 0 :(得分:0)
这是我与Material-UI
HOC一起使用的模板,用于与Typescript反应
希望能帮上忙
const styles = (theme: Theme) => createStyles({
});
interface Props extends WithStyles<typeof styles> {
classes: any,
}
interface State {
}
class RawComponent extends React.Component<Props, State>{
constructor(props: Props) {
super(props);
this.state = {
};
}
static defaultProps = {
classes: {},
};
async componentDidMount() {
}
render() {
return (
<div></div>
);
}
}
export const ComponentName = withTheme(withStyles(styles)(connect(
(store: Store) => ({
}),
(dispatch: any) => ({
})
)(RawComponent)));
export default ComponentName;
答案 1 :(得分:0)
设法从相关的question开始使用它。
包括codesandbox,以防其他人遇到类似问题。