单击按钮后如何重置输入状态值?

时间:2021-04-11 11:46:45

标签: reactjs

我希望能够在单击按钮时摆脱该值。我知道我需要将代码添加到函数 dataPush。我试过这个:

(this.name.value=''; this.pw.value='';)

在函数 dataPush 中。但它不会工作。我应该添加什么代码?

import React, { Component } from "react";
import "../Product/Product.scss";

export class Product extends Component {
  constructor() {
    super();
    this.state = {
      name: "",
      pw: "",
      users: [],
    };
    this.fillInput = this.fillInput.bind(this);
    this.dataPush = this.dataPush.bind(this);
  }
  fillInput = (e) => {
    this.setState({ [e.target.id]: e.target.value });
    console.log(this.state.name);
    console.log(this.state.pw);
  };
  dataPush = () => {
    let obj = {
      name: this.state.name,
      pw: this.state.pw,
    };
    let arr = this.state.users;
    arr.push(obj);

    this.setState({
      users: arr,
    });
  };

  render() {
    return (
      <div className="product">
        <div class="inputWrap">
          <input
            id="name"
            type="text"
            placeholder="id"
            onChange={this.fillInput}
          />
          <input
            id="pw"
            type="text"
            placeholder="pw"
            onChange={this.fillInput}
          />
        </div>

        <button type="reset" onClick={this.dataPush}>
          submit
        </button>
        <div>
          {this.state.users.map((ele) => {
            return (
              <div>
                {ele.name} : {ele.pw}
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}

export default Product;

1 个答案:

答案 0 :(得分:0)

将您的 dataPush 函数更改为:

dataPush = ()=>{
    let obj = {
        name : this.state.name,
        pw :  this.state.pw
    }
    let arr= this.state.users;
    arr.push(obj);

    this.setState({
        users:arr
        pw:"", 
        name:""
    })
}

并将您的输入字段更改为:

<input value={this.state.name} id='name' type='text' placeholder="id" onChange={this.fillInput} />
<input value={this.state.pw} id='pw' type='text' placeholder="pw" onChange={this.fillInput} />