如何在使用TypeScript验证的React中创建HOC组件

时间:2019-05-21 20:28:17

标签: reactjs typescript

所以我有一个仅通过子代传递的HOC组件:

import * as React from "react";

interface Props {
    children?: any
}

function BaseWidget(props: Props) {
    const { children } = props;

    return (
        <div>
        {children}
        </div>
    );
}

export default BaseWidget;

然后,我想将另一个组件与上述组件包装在一起,例如HOC。

所以我尝试了这个:

function MockWidget(props: Props) {
    const classes = useStyles(props);

    return (
        <List className={classes.root}>
        {mockPosts.map( (post: Post) => 
            <ListItem alignItems="flex-start">
                <ListItemAvatar>
                    <Avatar alt="Remy Sharp" src={post.img} />
                </ListItemAvatar>
                <ListItemText
                primary={post.channel}
                secondary={
                    <React.Fragment>
                    <Typography component="span" className={classes.inline} color="textPrimary">
                        {post.name}
                    </Typography>
                    {` — ${post.message}`}
                    </React.Fragment>
                }
                />
            </ListItem>  
        )}
      </List>
    );
}

const useStyles = makeStyles((theme: Theme) => ({
    root: {
        width: '100%',
        maxWidth: 360,
        backgroundColor: theme.palette.background.paper,
      },
      inline: {
        display: 'inline',
      },
}));

export default withBaseWidget(MockWidget);

但是我在withBaseWidget()定义中出错:

function MockWidget(props: Props): JSX.Element
Type '(props: Props) => Element' has no properties in common with type 'Props'.

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

您需要定义适当的HOC包装器,就像在JS中一样。

给出i=1BaseWidget

MockWidget