我有以下输入字段。在模糊时,该函数调用服务来更新服务器的输入值,完成后,它会更新输入字段。
我怎样才能让它发挥作用?我可以理解为什么它不让我更改字段,但我能做些什么才能使其正常工作?
我无法使用
defaultValue
因为我会将这些字段更改为其他字段
<input value={this.props.inputValue} onBlur={this.props.actions.updateInput} />
为了使输入值可编辑,您需要有一个
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)} />
这样做的方法:
不要将
value
属性分配给 input field
,每当 onblur
方法触发时,请像这样点击 api:
<input placeholder='abc' onBlur={(e)=>this.props.actions.updateInput(e.target.value)} />
将值更新到服务器:
updateInput(value){
/*update the value to server*/
}
如果您通过
value
将 input
属性分配给 this.props.inputValue
字段,则使用 onChange
方法,将值传回父组件,通过在父组件中使用 inputValue
更改 setState
,它将像这样工作:
<input value={this.props.inputValue} onChange={(e)=>this.props.onChange(e.target.value)} onBlur={()=>this.props.actions.updateInput} />
在父组件中:
onChange(value){
this.setState({inputvalue:value});
}
将值更新到服务器:
updateInput(value){
/*update the value to server*/
}
您将需要绑定一个 onChange 事件来更新您的状态。确保在构造函数中使用绑定方法,这样就不会丢失 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)}
/>
HTML 元素更改事件和 React 更改事件之间存在差异。
当发生更改且元素失去焦点时,会触发 HTML 更改事件。
每次按下键盘按键都会触发 React 更改事件。
如果您想要 HTML 的更改行为,一种方法是使用 ref 并添加更改事件侦听器。这是一个例子: