javascript 从表单内的字符串两端删除空格 - React
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52284334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove white spaces from both ends of a string inside a form - React
提问by Liz Parody
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?
我有一个接收名字和姓氏的简单表单,我需要删除字符串开头和结尾的空格。我可以用这个.trim()方法来做到这一点,但是因为是一种形式,它不允许我写一个有两个词的名字,比如 Ana Maria,因为它不允许我在一个词的末尾按下空格键. 如何从字符串的两侧删除空格,但仍然让我按空格并写多个单词?
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>
);
}
回答by coreyward
Instead of trimming onChange, do that in an onBlurcallback:
而不是 trimming onChange,在onBlur回调中做到这一点:
<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() })
}


