Clear an input field with Reactjs?

后端 未结 7 2005
囚心锁ツ
囚心锁ツ 2020-12-08 04:33

I am using a variable below.

var newInput = {
   title: this.inputTitle.value,
   entry: this.inputEntry.value    
};

This is used by my i

相关标签:
7条回答
  • 2020-12-08 05:00

    The way I cleared my form input values was to add an id to my form tag. Then when I handleSubmit I call this.clearForm()

    In the clearForm function I then use document.getElementById("myForm").reset();

    import React, {Component } from 'react';
    import './App.css';
    import Button from './components/Button';
    import Input from './components/Input';
    
    class App extends Component {  
      state = {
        item: "", 
        list: []
    }
    
    componentDidMount() {
        this.clearForm();
      }
    
    handleFormSubmit = event => {
       this.clearForm()
       event.preventDefault()
       const item = this.state.item
    
        this.setState ({
            list: [...this.state.list, item],
                })
    
    }
    
    handleInputChange = event => {
      this.setState ({
        item: event.target.value 
      })
    }
    
    clearForm = () => {
      document.getElementById("myForm").reset(); 
      this.setState({
        item: ""
      })
    }
    
    
    
      render() {
        return (
          <form id="myForm">
          <Input
    
               name="textinfo"
               onChange={this.handleInputChange}
               value={this.state.item}
          />
          <Button
            onClick={this.handleFormSubmit}
          >  </Button>
          </form>
        );
      }
    }
    
    export default App;
    
    0 讨论(0)
提交回复
热议问题