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)
May*_*kla 10
这样做的方法:
不要将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)
如果要将value
属性分配给input
field by this.props.inputValue
,则使用onChange
method,将值传递回父组件,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)
您需要绑定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)
归档时间: |
|
查看次数: |
52584 次 |
最近记录: |