Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

javascript - React中通用onChange处理程序的正确类型(Proper types for generic onChange handler in react)

HTML form implemented with react stateful component.(使用有状态组件实现的HTML表单。)

I am trying to write some generic on change handler for form elements but don't succeed to get it typed properly.(我正在尝试为表单元素的更改处理程序编写一些通用属性,但未能成功输入正确的类型。) Here is the code:(这是代码:) 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 }); } }; } I thought that this way I will be able to put something like <input onChange={this.onFieldUpdate('username')} /> but have following error on setState call:(我认为通过这种方式,我可以放置类似<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   ask by Boffin translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, I wrote like this and it works.(好吧,我这样写,而且行得通。)

handleStoreInput = (field: string) => (event: React.ChangeEvent<HTMLInputElement>) => { this.setState({ [field]: event.target.value } as Pick<State, any>); } ... onChange={this.handleStoreInput('tableFilterMethod')} By the way, any proper way to avoid using as any ?(顺便说一句,任何适当的方式,以避免使用as any ?)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...