【发布时间】:2018-08-10 10:51:03
【问题描述】:
我想在用户提交表单时从<form> 元素中检索值。我不想使用onChange 侦听器并在状态中设置值。我怎样才能做到这一点?
login.tsx
...
interface LoginProps {
authService: Auth
}
export default class Login extends React.Component<LoginProps, {}> {
constructor(props: LoginProps, context: any) {
super(props, context);
this.onSubmit = this.onSubmit.bind(this);
}
private onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
// how can I retrieve the username and password value from the FormEvent
this.props.authService.authenticate(username, password)
}
render(): React.ReactNode {
return (
<div className="container">
<div className="col align-self-center">
<form className="form-signin" onSubmit={this.onSubmit}>
<img className="mb-4" src={Logo} height={72}/>
<label htmlFor="input_username">Gebruikersnaam</label>
<input type="text" id="input_username" className="form-control" required={true}
autoFocus={true} tabIndex={1}/>
<label htmlFor="input_password">Password</label>
<input type="password" id="input_password" className="form-control" required={true}
tabIndex={2}/>
<button className="btn btn-lg btn-primary btn-block" type="submit" tabIndex={3}>Aanmelden
</button>
</form>
</div>
</div>
);
}
}
【问题讨论】:
-
为什么不想使用onChange?
-
@jsw324 只是在做实验;感觉它增加了不必要的复杂性,而且我认为看起来更干净
-
您可以使用 onChange 并根据输入的名称设置本地状态,因此它只是两个输入值的一个处理程序。类似
this.setState({ [inputName]: [inputValue] }) -
@jsw324 我试图避免使用整个推/拉机制进行价值检索
标签: javascript reactjs forms typescript