2016-09-26 76 views
0

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

,我试图更改在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 
/> 

第一方式的图案(与第一个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); 
    } 
+0

为什么你不检查函数内部的长度,如果它大于32那么不要再给输入添加字符。 – Kafo

+0

如果组件使用常规的HTML输入字段,那么为什么不在输入字段上设置maxLength,而不是每次更改输入时都调用函数来检查其中文本的长度? – pll33

+0

我正在使用react-mdl Textfield组件。 – milan

回答

0

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

+0

我正在使用react-mdl Textfield组件而不是textarea。你可以放置你写的道具,根据我的代码? – milan

+0

可能你必须自定义你的textField库根据你的逻辑:https://github.com/tleunen/react-mdl/blob/master/src/Textfieldimp.js,你可以看到隐式地使用了textarea,所以你可以在里面应用逻辑。也许你可以更新“inputProps”来实现你的行为。希望能工作 –