小编典典

打字稿:如何在React中为历史对象添加类型检查?

reactjs

我有以下代码,它接收一个历史对象作为道具:

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>
);

我该如何为这个历史道具添加typecheck, 通过使用withRouter HOC包装它的父项来获得它 ?我能想到的一种方法是写这样的东西:

interface Props {
    history: {
        push(url: string): void;
    };
}

但是我确定这不是正确的方法,因为历史对象的其余属性都将丢失。

您能建议正确的方法吗?

根据@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));

但是,现在我收到以下错误:

Type '{ history: History; }' is not assignable to type 'ChildComponentProps'.
    Property 'match' is missing in type '{ history: History; }'

阅读 277

收藏
2020-07-22

共1个答案

小编典典

您可以使用RouteComponentProps接口,该接口声明所有通过的道具withRouter

import { RouteComponentProps } from 'react-router-dom';
..
interface ChildComponentProps extends RouteComponentProps<any> {
  /* other props for ChildComponent */
}
const ChildComponent : React.SFC<ChildComponentProps> = ({ history }) => (
  ..
);

的type参数RouteComponentProps是中的params属性的类型match,因此除非匹配命名路径段,否则将不需要它。

或者,如果history不是来自withRouter但作为道具本身传递,则可以从中导入类型history

import { History } from 'history';
..
interface ChildComponentProps {
  history : History
  /* other props for ChildComponent */
}
const ChildComponent : React.SFC<ChildComponentProps> = ({ history }) => (
  ..
);
2020-07-22