Javascript 如何从React.FormEvent中检索表单值<;HTMLFormElement>;?
我想在用户提交表单时从Javascript 如何从React.FormEvent中检索表单值<;HTMLFormElement>;?,javascript,reactjs,forms,typescript,Javascript,Reactjs,Forms,Typescript,我想在用户提交表单时从元素中检索值。我不想使用onChangelistener并在状态中设置值。我怎样才能做到这一点 login.tsx ... interface LoginProps { authService: Auth } export default class Login extends React.Component<LoginProps, {}> { constructor(props: LoginProps, context: any) {
元素中检索值。我不想使用onChange
listener并在状态中设置值。我怎样才能做到这一点
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>
);
}
}
。。。
接口登录操作{
authService:Auth
}
导出默认类登录扩展React.Component{
构造函数(props:LoginProps,context:any){
超级(道具、背景);
this.onSubmit=this.onSubmit.bind(this);
}
私有onSubmit(e:React.FormEvent){
e、 预防默认值();
//如何从FormEvent中检索用户名和密码值
this.props.authService.authenticate(用户名、密码)
}
render():React.ReactNode{
返回(
格布鲁伊克斯纳姆酒店
密码
安梅尔登
);
}
}
然后通过id“输入用户名”和“输入密码”或使用React.createRef()通过ref获取第一个字段:
e.target[0].value
为什么不想使用onChange?@jsw324只是在试验;感觉它增加了不必要的复杂性,而且看起来更干净。我认为您可以使用onChange并根据输入的名称设置本地状态,因此它只是两个输入值的一个处理程序。类似于
this.setState({[inputName]:[inputValue]})
@jsw324我试图避免使用整个推/拉机制进行值检索