reactjs - 如何修复 Typescript 中的“对象”类型上不存在“属性“字符串”错误
问题描述
我正在尝试使用带有以下代码的 Typescript 在 React Router 中实现Scroll Restoration 。
import { Component } from 'react';
import { withRouter } from "react-router-dom";
export interface IProps {
prevProps?: any;
location: object;
pathname?: any;
}
class ScrollToTop extends Component<IProps, object> {
componentDidUpdate(prevProps?: any) {
if (this.props.location.pathname !== prevProps.location.pathname) {
window.scrollTo(0, 0);
}
}
render() {
return this.props.children;
}
}
export default withRouter(ScrollToTop);
但是,当我添加位置和路径名的类型时,我继续收到以下 TS 错误。
(14,29): Property 'pathname' does not exist on type 'object'.
为什么我的代码不正确?
解决方案
如另一个答案中所述,withRouter
必须从react-router
.
但是要回答您关于 Typescript 错误的问题,这是因为location
已将其定义为object
for typescript 而没有在其上指定属性。这就是为什么当您尝试访问pathname
它时出现错误的原因。
幸运的是,您不必在 location 属性上写出所有属性。相反,您可以安装 react-router 类型:
npm install --save @types/react-router @types/react-router-dom
创建继承这些道具(匹配、位置、历史)的组件时,只需扩展RouteComponentProps
:
import { RouteComponentProps } from "react-router";
interface IProps extends RouteComponentProps {
// other props
}
推荐阅读
- angular - “ng”命令只能通过管理员 cmd 执行
- constraints - 如何添加约束以使只有一个非整数值?
- java - GlassFish 5.1.0 错误,因为 dcs 为空
- python - Pyspark:获取列名的子字符串
- laravel - 如何使用带有多个图像的 Ajax Call 在 laravel 8 中存储数据
- node.js - In node on Windows 10, how can I get a list of all the voices installed?
- c++ - 在 Visual Studio 2019 中将对象序列化调试为 xml 代码时出现链接错误
- kotlin - View does not move correctly in x and y axis after it's been rotated
- php - 如何在查询中为表列的值动态调用 PHP/Laravel 函数?
- typescript - 'T' 仅指一种类型,但在此处用作值