问题
I have the following input field as below. On blur, the function calls a service to update the input value to the server, and once that's complete, it updates the input field.
How can I make it work? I can understand why it's not letting me change the fields but what can I do to make it work?
I can't use the defaultValue
because I will be changing these fields to some other ones
<input value={this.props.inputValue} onBlur={this.props.actions.updateInput} />
回答1:
In order to have the input value editable you need to have an onChange
handler for it that updates the value. and since you want to call a function onBlur, you have to bind that like onBlur={() => this.props.actions.updateInput()}
componentDidMount() {
this.setState({inputValue: this.props.inputValue});
}
handleChange = (e) => {
this.setState({inputValue: e.target.value});
}
<input value={this.state.inputValue} onChange={this.handlechange} onBlur={() => this.props.actions.updateInput(this.state.inputValue)} />
回答2:
Ways of doing this:
Do not assign
value
property toinput field
, wheneveronblur
method gets trigger, hit the api like this:<input placeholder='abc' onBlur={(e)=>this.props.actions.updateInput(e.target.value)} />
Update value to server:
updateInput(value){
/*update the value to server*/
}
If you are assigning the
value
property toinput
field bythis.props.inputValue
, then useonChange
method, pass the value back to parent component, change theinputValue
by usingsetState
in parent, it will work like this:<input value={this.props.inputValue} onChange={(e)=>this.props.onChange(e.target.value)} onBlur={()=>this.props.actions.updateInput} />
In Parent Component:
onChange(value){
this.setState({inputvalue:value});
}
Update value to server:
updateInput(value){
/*update the value to server*/
}
回答3:
You will want to bind a onChange event to update your state. Make sure to use the bind method in your constructor so that you do not lose the 'this' context within your onChange event handler method. You will then want to pass the value back to your update input method onBlur. Something like this:
constructor(props) {
super(props);
this.state = {
inputValue: props.inputValue
};
this.handleChange = this.handleChange.bind(this);
};
handleChange = (e) => {
this.setState({inputValue: e.target.value});
}
<input
value={this.state.inputValue}
onChange={this.handleChange}
onBlur={() => this.props.actions.updateInput(this.state.inputValue)}
/>
来源:https://stackoverflow.com/questions/41832389/updating-a-react-input-text-field-with-the-value-on-onblur-event