如何从React.FormEvent <htmlformelement>检索表单值?

时间:2018-08-10 10:51:04

标签: javascript reactjs forms typescript

我想在用户提交表单时从<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>
        );
    }
}

2 个答案:

答案 0 :(得分:0)

然后通过id'input_username'和'input_password'或使用React.createRef()的ref获取它

答案 1 :(得分:0)

获取第一个字段:

e.target[0].value