【问题标题】:React component throwing TypeScript error for function passed in as propReact 组件为作为 prop 传入的函数引发 TypeScript 错误
【发布时间】:2020-11-07 13:57:50
【问题描述】:

我有一个基于类的 React 组件,它接受一个函数作为道具。

该组件最初是一个无状态的功能组件,它接受相同的功能而没有任何 TypeScript 错误。

现在我已将其转换为类组件,但在调用函数时出现错误:Property 'onRouteChange' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'

以及当我在道具中对其进行解构时出现错误:Property 'onRouteChange' is missing in type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' but required in type '{ onRouteChange: any; }'.

我最初尝试在文件顶部的类型声明中定义它,但这也不起作用。

Component

type SignInState = {
  signInEmail: string,
  signInPassword: string
}

class SignIn extends Component<{}, SignInState> {
  constructor(props: {}){
    super(props);
    this.state = {
      signInEmail: '',
      signInPassword: ''
    }
  }

  onEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      this.setState({ signInEmail: e.target.value })
  }

  onPasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({ signInPassword: e.target.value })
  }

  onSubmitSignIn = () => {
    // fetch()
    console.log(this.state);
// TS Error: Property 'onRouteChange' does not exist
    this.props.onRouteChange('home');
  }
  
  render() {
// TS Error: Property 'onRouteChange' is missing in type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' 
    const { onRouteChange } : { onRouteChange: any} = this.props

    return (
      <Container>
        <Main>
          <Form>
            <Fieldset>
              <SignInTitle>Sign In</SignInTitle>
              <EmailAddressSection>
                <Label>Email</Label>
                <EmailInput />
              </EmailAddressSection>
              <PasswordSection>
                <Label>Password</Label>
                <PasswordInput />
              </PasswordSection>
            </Fieldset>
            <div>
              <SignInButton
                onClick={this.onSubmitSignIn}
                type="submit"
                value="Sign in"
              />
            </div>
            <AccountOptionsSection>
              <AccountOption onClick={() => onRouteChange("register")}>
                Register
              </AccountOption>
            </AccountOptionsSection>
          </Form>
        </Main>
      </Container>
    );
  }
};

export default SignIn;

【问题讨论】:

  • 你的道具被输入到一个空对象Component&lt;{}, SignInState&gt;

标签: javascript reactjs typescript


【解决方案1】:
class SignIn extends Component<{}, SignInState> 

Component 类型的第一个参数是 props 类型,你还没有定义它,所以报错。

定义一个接口,

interface ISignInProp {

onRouteChange:any
}

并将其传递给您的组件

class SignIn extends Component<ISignInProp , SignInState> 

【讨论】:

  • 做到了!谢谢!
【解决方案2】:

为你的道具​​创建一个typeinterface,就像你对你的状态所做的那样。

道具接口

// interface over type literal
interface IProps { 
 onRouteChange: (param: string) => void
}

避免输入any

尽量避免向any 输入内容。您基本上是在告诉 typescript 这没有类型。这违背了 TS 的目的。如果实在不知道,请输入unknown

但是,您传递的是 string 主页,因此您有一些关于它的信息,您可以使用它来更好地输入它。

在这里,我猜onRouteChange 是一个函数,它接受一个字符串类型的参数并且什么都不返回(有副作用)。您可以相应地更新它。

输入组件道具

你完全按照你对你的状态类型所做的事情(更喜欢接口而不是类型)。

class SignIn extends Component<IProps, IState>

现在您在解构它时不必键入onRouteChange

const { onRouteChange } : { onRouteChange: any} = this.props

变成

const { onRouteChange } = this.props

【讨论】:

    猜你喜欢
    • 2022-10-04
    • 2021-05-11
    • 1970-01-01
    • 2021-12-12
    • 2021-11-25
    • 1970-01-01
    • 2019-05-11
    • 2020-05-27
    • 2021-12-28
    相关资源
    最近更新 更多