Remove white spaces from both ends of a string inside a form - React

寵の児 提交于 2020-03-21 22:22:07

问题


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?

This is the component:

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>
  );
}

回答1:


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() })
}


来源:https://stackoverflow.com/questions/52284334/remove-white-spaces-from-both-ends-of-a-string-inside-a-form-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!