【发布时间】: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<{}, SignInState>
标签: javascript reactjs typescript