简体   繁体   中英

ReactJS: Empty input field after processing its value

I need to empty an input field in my react component after the content has been stored to the DB. This is what I did so far:

addPost (event) {
  const content = event.target.value

  methodInsert.call(
    { content },
    (error) => {
      if (!error) {
        event.target.value = ''
      }
    }
  )
}

render()

<Input
   onBlur={this.addPost.bind(this)}
/>

I am getting the error

Warning: This synthetic event is reused for performance reasons.
If you're seeing this, you're accessing the property `target` on a released/nullified synthetic event. This is set to null.
If you must keep the original synthetic event around, use event.persist().

You will need an onChange handler on your input that updates the state of the component when anything changes. You'll also need a onSubmit handler to handle your submit logic and then clear the input by using this.setState to set it's value to empty.

I recommend you read about Controlled Components in the React documentation.

Here is an example of how this can be accomplished:

class Example extends React.PureComponent {
    constructor( props ) {
        super( props );

        this.state = {
            inputValue = ""
        }

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

    handleChange( e ) {
        this.setState({
            inputValue: e.target.value
        });
    }

    handleSubmit( e ) {
        e.preventDefault();
        // .. do your stuff and then
        this.setState({
            inputValue: ""
        });
    }

    render() {
        <form onSubmit={ this.handleSubmit }>
            <input type="text"
                   placeholder="Controlled input"
                   onChange={ this.handleChange }
                   value={ this.state.inputValue } />
            <button>Submit</button>
        </form>
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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