我在尝试严格键入 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);
这是我用来强类型 Prop 的 ISideMenu 界面:
export interface ISideMenu {
fileExplorerInfo: IFileExplorerState;
}
所以现在在我的 App 类中,我试图渲染 SideMenu 组件,但是 typescript 显示一个错误,指出我没有将 prop fileExplorerInfo 传递到该组件。我宁愿不必这样做,因为 redux 会填充该 Prop 供我从商店的状态使用。有人对我如何更好地处理这个问题有什么建议吗?
class App extends Component {
render() {
return (
<div>
<SideMenu />
</div>
);
}
}
最佳答案
你错过了连接函数中类型的顺序
connect<TStateProps = {}, TDispatchProps = {}, TOwnProps = {}, State = {}>
- TStateProps 来自 mapStateToProps 中的状态
- TOwnProps 来自外部
你应该像这样使用连接:
export default connect<ISideMenu, {}, {}, IFileExplorerState>(mapStateToProps, {})(SideMenu);
或者您可以将“通用部分”留空
export default connect(mapStateToProps, {})(SideMenu);
关于javascript - 使用 typescript 渲染 react 组件而不传递强类型 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48293889/