空字符串检查输入元素值

时间:2019-02-24 20:10:01

标签: javascript reactjs typescript

为什么修剪后我的空字符串检查不能在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;

1 个答案:

答案 0 :(得分:2)

trim是一个函数。这就是!input.value.trim总是真实的原因。请改用!input.value.trim()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim