我有一个输入框,必须填写序列号。最大字符数为 32,因此当字符数达到 32 时,短信应该停止。我尝试了两种方法,但两种方法都不起作用。我尝试使用定义了某些模式的自定义函数来更新状态的第一种方法。第二种方式我尝试将 Textfield 组件中的模式作为 Prop 传递。该组件是react-mdl,当模式不匹配时它会显示错误。
我尝试更改默认情况下作为 Prop 在 Textfield 组件中传递的模式的第二种方法
<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
/>
第一种方法(使用第一个文本字段示例)
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 在文本区域中设置 maxLength 属性。我的意思是一些常量值this.props.customLength=32。
也不建议在状态中提供验证。
您所在的州应该拥有尽可能少的数据。
关于javascript - 限制reactjs中的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39694641/