【问题标题】:Disable button if input value is whitespace? React如果输入值为空格,则禁用按钮?反应
【发布时间】:2020-05-24 11:53:02
【问题描述】:

如果输入中的值是空格,我想禁用按钮。在 React 中真的找不到任何东西。

<Button onClick={handleClick} disabled={username === " "} /> //here's my button

现在它只在我输入 1 个空格时禁用,但我总是希望它在有空格时禁用。谢谢!

【问题讨论】:

    标签: javascript reactjs validation


    【解决方案1】:

    可以使用Regexp.Testhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

    如果用户名包含 any 空格,

    /\s/.test(username) 将返回 true,否则返回 false。

    【讨论】:

      【解决方案2】:
      • 您可以includes 来检查是否有空格。 &lt;Button onClick={handleClick} disabled={username.includes(" ")} /&gt;

      【讨论】:

        【解决方案3】:
        <Button onClick={handleClick} disabled={username.includes(" ")} />
        

        或者

        <Button onClick={handleClick} disabled={(/\s/g).test(username)} />
        

        【讨论】:

          【解决方案4】:

          几种方法:

          1. 查看索引:username.indexOf(' ') &gt;= 0

          2. 检查是否包含:username.includes(' ')

          3. 使用正则表达式:/\s/g.test(username)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-01-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多