1

我在 Typescript 中有以下代码。为什么编译器会抛出错误?

import { connect } from 'react-redux';
import React from "react";
import { Link, Redirect } from "react-router-dom";

class HeaderComponent extends React.Component {
    render() {
        return (
            <header>
                <div><Link to="">Sign up</Link></div>
                <div>{this.props.handleLoginDisplay}</div>
            </header>
        )
    }
}

const mapStateToProps = (state: { showLoginModal: any; }) => {
    return {
        showLoginModal: state.showLoginModal
    }
}

const mapDispatchToProps = (dispatch: (arg0: { type: string; }) => void) => {
    return {
        handleLoginDisplay: () => dispatch({ type: 'HANDLE_LOGIN_DISPLAY' })
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(HeaderComponent);

属性 'handleLoginDisplay' 不存在于类型'Readonly<{}> & Readonly<{ children?: ReactNode; }>'.ts(2339)

4

1 回答 1

1

因为你需要通过这样的接口告诉 ts 组件将收到什么样的 props:

interface Props {
    showLoginModal: boolean;
    handleLoginDisplay: () => void;
}

class HeaderComponent extends React.Component<Props> {
    render() {
        return (
            <header>
                 <div><Link to="">Sign up</Link></div>
                 <div>{this.props.handleLoginDisplay}</div>
             </header>
     )}
 }

这会让 ts 知道 HeaderComponent 接受这些道具。您还应该从 mapStateToProps 中删除 any。

于 2019-08-02T14:38:18.160 回答