为什么修剪后我的空字符串检查不能在HTMLInputElement
值属性上正常工作? storeOnEnter
函数中的问题代码。目标是仅在输入为空时设置新状态。
import React, { Component } from 'react';
class ItemEditor extends Component {
state = {
showInput: true,
itemDescription: ''
}
storeOnEnter = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key !== 'Enter') return;
const input = e.target as HTMLInputElement;
if (!input.value.trim) return;
this.setState({itemDescription: input.value, showInput: false})
}
switchToInput = (e: React.MouseEvent) => {
this.setState({showInput: true});
}
render() {
let input = <input type="text" onKeyPress={this.storeOnEnter} defaultValue={this.state.itemDescription}/>
let label = <label style={{userSelect: 'none'}} onDoubleClick={(e) => this.switchToInput(e)}>{this.state.itemDescription}</label>
return this.state.showInput ? input : label;
}
}
export default ItemEditor;
答案 0 :(得分:2)
trim
是一个函数。这就是!input.value.trim
总是真实的原因。请改用!input.value.trim()
。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim