reactjs - 无法访问道具中的“历史”
问题描述
我有一些 React 组件。
import * as React from 'react';
import { Component } from 'react';
import { FormControl, Button } from 'react-bootstrap';
type Props = {
history: any[];
};
// How to define Props only once, in base component
class BaseComponent extends Component<Props, State> {
}
class HomeComponent extends BaseComponent {
constructor(props: any) {
super(props);
this.state = {
name: ""
};
}
onSubmit = (event: any) => {
event.preventDefault();
this.props.history.push('/messenger'); // TYPE ERROR !!!
}
render() {
<FormControl autoFocus value={this.state.name} /> // TYPE ERROR !!!
<Button type="submit">Enter</Button>
}
}
当带有组件的文件具有扩展名 .js 时,它可以正常工作,但是如果我将其重命名为 .tsx ,则会出现以下错误。
Property 'history' doesn't exist
on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'
同样的错误表明状态中不存在“名称”。如何告诉 React 这不是错误?
TS 配置。
{
"compilerOptions": {
"baseUrl": ".",
"outDir": "output",
"module": "esnext",
"target": "es5",
"lib": ["es6", "dom"],
"sourceMap": true,
"allowJs": true,
"jsx": "react",
"moduleResolution": "node",
"rootDir": "src"
},
"exclude": [
"node_modules",
"build",
"scripts",
"acceptance-tests",
"webpack",
"server"
]
}
然后我以这种方式运行项目。
react-scripts-ts start
更新#1
当我从 React.Component 继承它时让它工作,不知道如何创建 CustomBaseComponent,但这可能是另一个问题。
interface IProps {
history: any[];
}
class HomeComponent extends React.Component<IProps> {
public state: any = {};
constructor(props: IProps) {
super(props);
this.state = {
name: ""
};
this.props.history.push('/demo'); // now history works as expected
}
}
更新#2
看起来 React 更喜欢 HTML 组件级别的继承,而不是标准的 JS 类继承。
解决方案
您需要为组件的 props 和 state 定义类型,并将它们指定为类型参数Component
:
type HomeProps = {
history: /* insert type here */;
};
type HomeState = {
name: string;
};
class HomeComponent extends Component<HomeProps, HomeState> {
// ...
}
推荐阅读
- c# - 如何在 C#“枚举键 - 属性”关系中提供类型安全,如 TypeScript 高级类型
- perl - Perl 将 cpan 安装到特定存储库中
- dictionary - PhpStorm:我可以在全球词典中添加一个新词吗?
- flutter - How to check length of value in onchange method in flutter
- html - 如何修复我的活动列表项下没有边框?
- sql - 使用外键管理其他表中新传入数据的引用表
- java - 如何下载 REST API 响应文件?
- typescript - 未使用的属性 OnPrepare
- php - Laravel Eloquent 过滤记录与查询
- android - android - Dagger 2 注入多个接口和实现类