React中通用onChange处理程序的正确类型

时间:2019-11-30 15:45:51

标签: javascript reactjs typescript

使用有状态组件实现的HTML表单。我正在尝试为表单元素的更改处理程序编写一些通用属性,但未能成功输入正确的类型。 这是代码:

interface SignupState {
    username: string
    email: string
    password: string
    password_confirmation: string
}

class Signup extends React.Component<{}, SignupState> {
    ....
    onFieldUpdate: (k: keyof SignupState) => (e: React.ChangeEvent<HTMLInputElement>) => void = (k) => {
        return (e) => {
            this.setState({
                [k]: e.currentTarget.value
            });
        }
    };
}

我认为通过这种方式,我可以放置类似<input onChange={this.onFieldUpdate('username')} />的内容,但是在setState通话中出现以下错误:

Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'SignupState | ((prevState: Readonly<SignupState>, props: Readonly<{}>) => SignupState | Pick<SignupState, "username" | "email" | "password" | "password_confirmation"> | null) | Pick<...> | null'.
  Type '{ [x: string]: string; }' is missing the following properties from type 'Pick<SignupState, "username" | "email" | "password" | "password_confirmation">': username, email, password, password_confirmation  TS2345

1 个答案:

答案 0 :(得分:0)

好吧,我这样写,并且有效。

  handleStoreInput = (field: string) => (event: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({ [field]: event.target.value } as Pick<State, any>);
  }
...
onChange={this.handleStoreInput('tableFilterMethod')}

顺便说一句,是否有避免使用as any的适当方法?

加法 =>找到here类型的方法list[attr]