How do I reset the defaultValue for a React input

前端 未结 2 1285
野的像风
野的像风 2021-01-19 19:54

I have a set of React input elements that have a defaultValue set. The values are updated with an onBlur event.

I also have another action on the page that updates

2条回答
  •  [愿得一人]
    2021-01-19 20:51

    As mentioned in https://stackoverflow.com/a/21750576/275501, you can assign a key to the outer element of your rendered component, controlled by state. This means you have a "switch" to completely reset the component because React considers a new key to indicate an entirely new element.

    e.g.

    class MyComponent extends React.Component {
      
      constructor() {
      
        super();
        this.state = { 
        
          key: Date.now(),
          counter: 0
          
        };
        
      }
      
      updateCounter() {
      
        this.setState( { counter: this.state.counter + 1 } );
        
      }
      
      updateCounterAndReset() {
      
        this.updateCounter();
        this.setState( { key: Date.now() } );
        
      }
      
      render() { return ( 
      
        

    Input with default value:

    Counter: {this.state.counter}

    ); } } ReactDOM.render( , document.querySelector( "#container" ) );
    
    
    

提交回复
热议问题