[英]Limit number of characters in reactjs
我有一個輸入框,其中必須填寫序列號。最大字符為32,因此當字符數達到32時,短信應該停止。我嘗試以兩種方式進行,但兩種方式都不起作用。 我嘗試使用自定義函數更新狀態的第一種方法,其中定義了一些模式。 第二種方式我試圖將Textfield組件中的模式作為道具傳遞。 該組件是react-mdl,它在模式不匹配時顯示錯誤。
第二種方法,我試圖默認情況下將Textfield組件中傳遞的模式更改為prop
<Textfield
onChange={(event)=> {this.handleInputChange(event)}}
pattern="-?[0-9]*(\.[0-9]+)?"
error="Input is not a number!"
label="Device Serial Number"
floatingLabel
/>
至
<Textfield
onChange={(event)=> {this.handleInputChange(event)}}
pattern="-?[0-9]*(\.[0-9]{6,32})?"
error="Input is not a number!"
label="Device Serial Number"
floatingLabel
/>
第一種方式(第一個Textfield示例)
const extract = (str, pattern) => (str.match(pattern) || []).pop() || '';
const extractPattern = (str) => extract(str, "-?[0-9]*(\.[0-9]+)?");
const limitLength = (str, length) => str.substring(0, length);
export default class App extends Component {
constructor(props){
super(props);
this.state = {max_char:32, limit:{}};
this.handleChange = this.handleChange.bind(this);
}
handleChange(charLength){
console.log('charLength',charLength);
this.setState({
max_char:32 - charLength.length,
limit:limitLength(extractPattern(charLength), 32),
});
console.log('charLength', charLength);
// console.log('limitLength', this.state.limit);
}
使用props在textArea中設置maxLength屬性。 我的意思是一些常量值this.props.customLength=32.
還不建議在狀態下提供驗證。 您的州應該盡可能地擁有最少的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.