![](/img/trans.png)
[英]React / Javascript - Remove white spaces from both ends of a string and extra spaces between words, from a input field (search bar)
[英]Remove white spaces from both ends of a string inside a form - React
我有一個接收名字和姓氏的簡單表單,我需要刪除字符串開頭和結尾的空格。 我可以用.trim()
方法做到這一點,但因為是一個表單,它不會讓我寫一個有兩個單詞的名字,比如Ana Maria,因為它不允許我按空格鍵一句話的結尾。 如何從字符串的兩邊刪除空格,但仍然讓我按空格並寫一個以上的單詞?
這是組件:
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
回調中執行此操作:
<input onBlur={this.props.formatInput} {...} />
在哪里可能看起來像這樣:
formatInput = (event) => {
const attribute = event.target.getAttribute('name')
this.setState({ [attribute]: event.target.value.trim() })
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.