限制reactjs中的字符数

时间:2016-09-26 04:14:30

标签: javascript regex reactjs react-jsx

我有一个输入框,其中必须填写序列号。最大字符为32,因此当字符数达到32时,短信应该停止。我尝试以两种方式进行,但两种方式都不起作用。我尝试使用自定义函数更新状态的第一种方法,其中定义了一些模式。第二种方式我试图将Textfield组件中的模式作为道具传递。该组件是react-mdl,它在模式不匹配时显示错误。

第二种方法,我尝试将默认情况下在Textfield组件中传递的模式更改为道具

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

第一种方式(使用第一个Textfield示例)

ArrayList

1 个答案:

答案 0 :(得分:0)

使用道具在textArea中设置 maxLength 属性。我的意思是一些常数值this.props.customLength=32. 还不建议在状态下提供验证。 你的州应该尽可能地拥有最少的数据。

相关问题