简体   繁体   English

通过句柄更改通过状态传递值

[英]React passing value through state on handle change

I am attempting to use two methods, handleChange and handleSubmit for a login page in react. 我正在尝试对React登录页面使用两种方法handleChange和handleSubmit。 I have tried to set two values for username and password within state, update the values in state whenever the input are of the form is modified, then submit using the values stored in state. 我尝试为状态内的用户名和密码设置两个值,只要输入的形式被修改,就更新状态下的值,然后使用状态中存储的值提交。 However, my values return undefined when printed to console. 但是,当打印到控制台时,我的值返回未定义。 (ps I am aware I still yet need to encrypt password for all you security gurus). (ps,我知道我仍然需要为所有安全专家加密密码)。

I'm new to react so there may be an issue with my logic: 我是新来的人,所以我的逻辑可能有问题:

Login.js Login.js

export default class Login extends React.Component {

constructor(props) {
    super(props);
    this.state = {uname: '', password: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange(event) {
    this.setState({uname: event.target.uname, password: event.target.password});
}

handleSubmit(event) {
    alert('A username and password  was submitted: ' + this.state.uname + this.state.password);
    event.preventDefault();

    fetch('https://localhost:8080/login', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            uname: this.state.uname,
            password: this.state.password,
        })
    });
}

render() {

    return (
        <div>
            <Header titleName={"Login"}>
                <div className="container">
                    <div className="card"/>
                    <div className="card">
                        <h1 className="title">Login</h1>
                        <form onSubmit={this.handleSubmit}>
                            <div className="input-container">
                                <input name="uname" type="text" value={this.state.uname} id="#uname" required="required"
                                        onChange={this.handleChange}/>
                                <label form="#unamelabel">Username</label>
                                <div className="bar"/>
                            </div>
                            <div className="input-container">
                                <input name="password" type="password" value={this.state.password} id="#pass" required="required"
                                       onChange={this.handleChange}/>
                                <label form="#passlabel">Password</label>
                                <div className="bar"/>
                            </div>
                            <div className="button-container">
                                <button type="submit" value="Submit"><span>Go</span></button>
                            </div>
                            <div className="footer"><a href="#">Forgot your password?</a></div>
                        </form>
                    </div>
                </div>
            </Header>
            <Footer/>
        </div>
    );
}
}

Replace handle change with this 以此替换手柄更改

handleInputChange(event) {
    const target = event.target;
    const value = target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

You need to set value of the inputs to the state, not the name of the inputs 您需要将输入的值设置为状态,而不是输入的名称

If you want to get the value of an input inside a react statefull component, you should set the ref property of this input like this: 如果要在react statefull组件中获取输入的值,则应按以下方式设置此输入的ref属性:

<input name="username" ref={node => this.username = node} />

then calling this.username will return you the actual value of username input. 然后调用this.username将返回用户名输入的实际值。

You don't want to set the state in a submit action since this makes your component rerender each times a letter push your input value. 您不希望在Submit操作中设置状态,因为这会使您的组件在每次按下字母输入值时都重新呈现。

More in the react doc 反应文档中更多

The problem lies with handleChange function. 问题在于handleChange函数。 In the code posted above, there are two distinct 'event' objects associated with the two form inputs. 在上面发布的代码中,有两个不同的“事件”对象与两个表单输入相关联。 Each one of them have their own set of properties. 它们每个都有自己的一组属性。 For example: 'event.target.name' stores the 'name' attribute specified by 'input' tag while 'event.target.value' stores the data entered by the user. 例如:'event.target.name'存储由'input'标签指定的'name'属性,而'event.target.value'存储用户输入的数据。 So, change the implementation of handleChange to either 因此,将handleChange的实现更改为

(A) Verbose (A)详细

handleChange(event) {
     if (event.target.name == "uname") {
              this.setState({
                uname: event.target.value
              });
            }
      if (event.target.name == "password") {
              this.setState({
                password: event.target.value
              });
            }
    }

where you can match the 'name' attribute to either uname or password and set state accordingly. 您可以在其中将'name'属性与uname或password匹配,并相应地设置状态。

(B) Succinct (B)简洁

  handleChange(event) {
    this.setState({
        [event.target.name]: event.target.value
    });
}

I think the handleChange should setState should have event.tagert.name = event.target.value: 我认为handleChange应该setState应该具有event.tagert.name = event.target.value:

 handleChange(evt) {
    this.setState({
      [evt.target.name]: evt.target.value,
    });
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM