从表单内字符串两端删除空格-React [英] Remove white spaces from both ends of a string inside a form - React

查看:32
本文介绍了从表单内字符串两端删除空格-React的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的形式,可以接收名字和姓氏,并且需要删除字符串开头和结尾的空格.我可以使用 .trim()方法执行此操作,但是由于它是一种形式,因此它不允许我写一个包含两个单词的名称,例如Ana Maria,因为它不允许我按一个单词结尾的空格键.如何在字符串的两边删除空格,但仍然让我按空格并写多个单词?

I have a simple form that receives the first name and last name, and I need to remove the whitespaces in the beginning and end of the string. I can do this with the .trim() method, but because is a form, it doesn't let me write a name that has two words, such as Ana Maria, because it doesn't let me press the space key at the end of a word. How can I remove white spaces from both sides of a string but still let me press space and write more than one word?

这是组件:

export default function ScheduleInput(
  { label, required, onChange, value, ...extraProps },
) {
  return (
    <div className="item_container">
      {label}:
      {required &&
        <span style={{ color: 'red' }}> *</span>
      }
      <br />
      <input
        type="text"
        onChange={onChange}
        value={value.trim()}
        {...extraProps}
      />
    </div>
  );
}

推荐答案

而不是修剪 onChange ,而是在 onBlur 回调中进行此操作:

Instead of trimming onChange, do that in an onBlur callback:

<input onBlur={this.props.formatInput} {...} />

可能看起来像这样的地方:

Where that might look something like this:

formatInput = (event) => {
  const attribute = event.target.getAttribute('name')
  this.setState({ [attribute]: event.target.value.trim() })
}

这篇关于从表单内字符串两端删除空格-React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆