首页 文章

渲染使用typescript反应组件而不传入强类型道具

提问于
浏览
0

我有一个问题,试图严格键入反应组件的道具,只传递1个属性到该组件 .

所以以此为例:

我有这个类App,它有一个SideMenu类的子组件 . SideMenu有强类型道具,如下所示:

class SideMenu extends Component<ISideMenu> {
    render() {
        return (
            <div>
                Test
            </div>
        );
    }
}

const mapStateToProps = (state: IFileExplorerState) => {
    return {
        fileExplorerInfo: state.fileExplorer
    };
};

export default connect<{}, {}, ISideMenu, IFileExplorerState>(mapStateToProps, {})(SideMenu);

这是我用来强烈输入道具的ISideMenu界面:

export interface ISideMenu {
    fileExplorerInfo: IFileExplorerState;
}

所以现在在我的App类中我试图渲染SideMenu组件,但typescript显示一个错误,说我没有将prop fileExplorerInfo传递给该组件 . 我宁愿不必这样做,因为redux填充了我在商店的状态下使用的道具 . 有人建议如何更好地处理这个问题吗?

class App extends Component {
    render() {
        return (
            <div>
                <SideMenu />
            </div>
        );
    }
}

1 回答

  • 1

    您错过了connect函数中类型的顺序

    connect<TStateProps = {}, TDispatchProps = {}, TOwnProps = {}, State = {}>
    
    • TStateProps来自mapStateToProps中的状态

    • TOwnProps来自外部

    你应该像这样使用connect:

    export default connect<ISideMenu, {}, {}, IFileExplorerState>(mapStateToProps, {})(SideMenu);
    

    或者你可以留空“通用部分”

    export default connect(mapStateToProps, {})(SideMenu);
    

相关问题