pho*_*nix 28 typescript reactjs typescript-typings
我有以下代码,它接收一个历史对象作为prop:
const ChildComponent = ({ history }) => (
<div className={styles.body}>
<div className={styles.cta}>
<FloatingActionButton onClick={() => history.push(routes[4].path)}>
<span>Click me</span>
</FloatingActionButton>
</div>
</div>
);
Run Code Online (Sandbox Code Playgroud)
如何为此历史道具添加类型检查,通过使用withRouter HOC包装它的父级来获得?我能想到的一种方法是写下这样的东西:
interface Props {
history: {
push(url: string): void;
};
}
Run Code Online (Sandbox Code Playgroud)
但我确定这不是正确的方法,因为历史对象的其他属性正在丢失.
你能建议正确的方法吗?
根据@ Oblosys的回答更新了代码
import { withRouter, RouteComponentProps } from "react-router-dom";
interface Props extends RouteComponentProps<any> {
/* Parent component's props*/
}
class Parent extends React.Component<Props, {}> {
render() {
return <ChildComponent history={this.props.history} />;
}
}
//Child component related stuff
interface ChildComponentProps extends RouteComponentProps<any> {}
const ChildComponent: React.SFC<ChildComponentProps> = (props) => (
<div className={styles.body}>
<div className={styles.cta}>
<FloatingActionButton onClick={() => history.push(routes[4].path)}>
<span>Click me</span>
</FloatingActionButton>
</div>
</div>
);
function mapStateToProps(state: types.AppState) {
/* related code */
}
function mapDispatchToProps(dispatch: Redux.Dispatch<types.AppState>{
/* related code */
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Parent));
Run Code Online (Sandbox Code Playgroud)
但是,现在我得到以下错误:
Type '{ history: History; }' is not assignable to type 'ChildComponentProps'.
Property 'match' is missing in type '{ history: History; }'
Run Code Online (Sandbox Code Playgroud)
Obl*_*sys 43
你可以使用RouteComponentProps界面,它声明所有传递的道具withRouter:
import { RouteComponentProps } from 'react-router-dom';
..
interface ChildComponentProps extends RouteComponentProps<any> {
/* other props for ChildComponent */
}
const ChildComponent : React.SFC<ChildComponentProps> = ({ history }) => (
..
);
Run Code Online (Sandbox Code Playgroud)
类型参数to RouteComponentProps是params属性的类型match,因此除非您匹配命名路径段,否则不需要它.
或者,如果history不是来自withRouter但作为道具自己传递,您可以从history以下位置导入类型:
import { History } from 'history';
..
interface ChildComponentProps {
history : History
/* other props for ChildComponent */
}
const ChildComponent : React.SFC<ChildComponentProps> = ({ history }) => (
..
);
Run Code Online (Sandbox Code Playgroud)
对于带有钩子的 React 16.8:
...
import {withRouter, RouteComponentProps} from 'react-router-dom';
...
const ChildComponent: React.FunctionComponent<RouteComponentProps> = ({history}) => {
...
}
Run Code Online (Sandbox Code Playgroud)
我找到的最简单的解决方案
import { RouteComponentProps } from 'react-router-dom';
....
interface Foo{
history: RouteComponentProps["history"];
location: RouteComponentProps['location'];
match: RouteComponentProps['match'];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17346 次 |
| 最近记录: |