Mar*_*zer 3 typescript reactjs react-router-dom
我有一个想法来定义location.state某个无状态组件可以是什么类型。我找到了一些基于该RouteComponentProps类型的文章,但我无法弄清楚细节。
假设在这个例子中,我希望location.state属性的类型是
type StateType = {
id: number,
type: number
}
Run Code Online (Sandbox Code Playgroud)
或者让 type` 甚至是一个枚举。这能实现吗?
import React from 'react';
import { withRouter, RouteComponentProps } from 'react-router-dom';
const Index = ({ location, history }) => {
return (
<div>Test</div>
)
}
export default withRouter(Index)
Run Code Online (Sandbox Code Playgroud)
型RouteComponentProps的react-router是一个通用型。这是您如何使用自定义类型定义位置状态(我修改了您的示例):
import React from 'react';
import { withRouter, RouteComponentProps } from 'react-router-dom';
type StateType = {
id: number,
type: number
}
type IndexProps = RouteComponentProps<{}, {}, StateType>;
const Index: React.FC<IndexProps> = ({ location, history }) => {
return (
<div>{location.state && (
<ul>
<li>{location.state.id}</li>
<li>{location.state.type}</li>
</ul>
)}</div>
);
}
export default withRouter(Index);
Run Code Online (Sandbox Code Playgroud)
一些要点:
location.state已定义,可能会发生由于某种原因未通过状态React.FC泛型类型为组件本身添加正确的类型(不过,还有其他方法可以做到这一点......)RouteComponentProps 实际上可以正确定义三种类型:
{}在我的示例中为空) -的参数类型<Route />{}在我的例子中为空) -的上下文类型<StaticRouter />StateType在我的例子中) - 位置状态的类型location目的也可以发现history.location,但它没有类型的,应该不会被使用,如在文档中指出:
...历史对象是可变的。因此,建议从 的渲染道具访问位置
<Route>,而不是从history.location. ...
| 归档时间: |
|
| 查看次数: |
2324 次 |
| 最近记录: |