使用onBlur事件的值更新React Input文本字段

Sut*_*ala 18 javascript onblur reactjs

我有以下输入字段如下.在模糊时,该函数调用服务来更新服务器的输入值,一旦完成,它就会更新输入字段.

我怎样才能使它工作?我能理解为什么它不会让我改变字段,但我能做些什么来使它工作?

我不能使用,defaultValue因为我会将这些字段更改为其他字段

<input value={this.props.inputValue} onBlur={this.props.actions.updateInput} />

Shu*_*tri 30

为了使输入值可编辑,您需要有一个onChange更新值的处理程序.并且因为你想调用函数onBlur,你必须绑定它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)} />
Run Code Online (Sandbox Code Playgroud)

  • 如果您想使用 onBlur 将更新后的值分派到状态,而不必在每次击键时使用 onChange 重新渲染组件,该怎么办? (2认同)

May*_*kla 10

这样做的方法:

  1. 不要将value属性赋值给input field,只要onblur方法触发,就像这样命中api:

    <input placeholder='abc' onBlur={(e)=>this.props.actions.updateInput(e.target.value)} />
    
    Run Code Online (Sandbox Code Playgroud)

更新服务器的值:

updateInput(value){
    /*update the value to server*/
}
Run Code Online (Sandbox Code Playgroud)
  1. 如果要将value属性分配给inputfield by this.props.inputValue,则使用onChangemethod,将值传递回父组件,inputValue通过setState在parent中使用更改,它将如下工作:

    <input value={this.props.inputValue} onChange={(e)=>this.props.onChange(e.target.value)} onBlur={()=>this.props.actions.updateInput} />
    
    Run Code Online (Sandbox Code Playgroud)

在父组件中:

onChange(value){
    this.setState({inputvalue:value});
}
Run Code Online (Sandbox Code Playgroud)

更新服务器的值:

updateInput(value){
    /*update the value to server*/
}
Run Code Online (Sandbox Code Playgroud)


MDi*_*sel 5

您需要绑定onChange事件以更新您的状态.确保在构造函数中使用bind方法,这样就不会在onChange事件处理程序方法中丢失'this'上下文.然后,您需要将值传递回更新输入方法onBlur.像这样的东西:

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)} 
/>
Run Code Online (Sandbox Code Playgroud)

  • 首先将道具设置为初始状态是反模式,如果你使用箭头函数你没有函数需要在构造函数中绑定 (4认同)