【问题标题】:How to retrieve form values from a React.FormEvent<HTMLFormElement>?如何从 React.FormEvent<HTMLFormElement> 中检索表单值?
【发布时间】:2018-08-10 10:51:03
【问题描述】:

我想在用户提交表单时从&lt;form&gt; 元素中检索值。我不想使用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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    获取第一个字段:

    e.target[0].value
    

    【讨论】:

      猜你喜欢
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 1970-01-01
      • 1970-01-01
      • 2023-02-26
      相关资源
      最近更新 更多