【问题标题】:Rendering react component using typescript without passing in strongly typed props使用打字稿渲染反应组件而不传递强类型道具
【发布时间】:2018-06-25 21:47:22
【问题描述】:

我在尝试 stronly 键入 react 组件的 props 并仅将 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>
        );
    }
}

【问题讨论】:

    标签: javascript reactjs typescript react-redux


    【解决方案1】:

    你错过了连接函数中类型的顺序

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

    你应该像这样使用连接:

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 1970-01-01
      • 2020-04-08
      • 2018-10-26
      • 2022-01-06
      • 2020-05-13
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多