我无法在React文本字段中输入

时间:2019-09-18 05:16:45

标签: html reactjs

我只是不能在文本字段中输入。我在构造函数上设置状态。绑定功能。我找不到错在哪里。

这是我的构造函数...

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

这是我处理onChange的方式...

handleChange=(e)=>{
    this.setState ({ [e.target.name]: e.target.value });
  }

这是我的...

<form>
                    <div class="form-group">
                      <label for="exampleInputEmail1">Email address</label>
                      <input
                        type="email"
                        class="form-control"
                        id="exampleInputEmail1"
                        aria-describedby="emailHelp"
                        placeholder="Enter email"
                        value={this.state.email}
                        onChange={this.handleChange}
                      ></input>
                      <small id="emailHelp" class="form-text text-muted">
                        We'll never share your email with anyone else.
                      </small>
                    </div>
                    <div class="form-group">
                      <label for="exampleInputPassword1">Password</label>
                      <input
                        onChange={this.handleChange}
                        value={this.state.password}
                        type="password"
                        class="form-control"
                        id="exampleInputPassword1"
                        placeholder="Password"
                      ></input>

2 个答案:

答案 0 :(得分:2)

要在更改时正确设置状态,您需要在输入上具有name属性,否则将无法定义e.target.name并且不会正确设置状态

<div class="form-group">
  <label for="exampleInputEmail1">Email address</label>
  <input
    type="email"
    name="email"
    class="form-control"
    id="exampleInputEmail1"
    aria-describedby="emailHelp"
    placeholder="Enter email"
    value={this.state.email}
    onChange={this.handleChange}
  ></input>
  <small id="emailHelp" class="form-text text-muted">
    We'll never share your email with anyone else.
  </small>
</div>
<div class="form-group">
  <label for="exampleInputPassword1">Password</label>
  <input
    onChange={this.handleChange}
    value={this.state.password}
    type="password"
    name="password"
    class="form-control"
    id="exampleInputPassword1"
    placeholder="Password"
  ></input>
</div>

答案 1 :(得分:1)

在输入字段中添加名称属性