React-Native Form验证错误(“this.validate不是函数”)

时间:2018-03-26 03:10:08

标签: reactjs validation react-native

当我使用下面的代码点击“this._onPressButton”时,我收到此错误。无法弄清楚为什么会发生这种情况或找到解决方案。提前谢谢。

App Service Token Store

import React, {Component}  from 'react';

import {View, Text, TextInput, TouchableHighlight} from 'react-native';

import ValidationComponent from 'react-native-form-validator';

export default class FormTest extends ValidationComponent {

  constructor(props) {
    super(props);
    this.state = {name : "My name", email: "tibtib@gmail.com", number:"56", date: "2017-03-01"};
  }

  _onPressButton() {
    // Call ValidationComponent validate method
    this.validate({
      name: {minlength:3, maxlength:7, required: true},
      email: {email: true},
      number: {numbers: true},
      date: {date: 'YYYY-MM-DD'}
    });
  }

  render() {
      return (
        <View>
          <TextInput ref="name" onChangeText={(name) => this.setState({name})} value={this.state.name} />
          <TextInput ref="email" onChangeText={(email) => this.setState({email})} value={this.state.email} />
          <TextInput ref="number" onChangeText={(number) => this.setState({number})} value={this.state.number} />
          <TextInput ref="date" onChangeText={(date) => this.setState({date})} value={this.state.date} />

          <TouchableHighlight onPress={this._onPressButton}>
            <Text>Submit</Text>
          </TouchableHighlight>

          <Text>
            {this.getErrorMessages()}
          </Text>
        </View>
      );
  }

}

2 个答案:

答案 0 :(得分:1)

尝试

constructor(props) {
    super(props);
    this.state = {name : "My name", email: "tibtib@gmail.com", number:"56", date: "2017-03-01"};
this._onPressButton = this._onPressButton.bind(this)

  }

更新: 我想你需要使用这个propthis.isFormValid()

如果有效,您可以提交表格......等等。

答案 1 :(得分:0)

问题出在onPress分配上。 这样做:

<TouchableHighlight onPress={() => {this._onPressButton}}}>
    <Text>Submit</Text>
</TouchableHighlight>

如果你执行onPress={this._onPressButton} this._onPressButton将被自动调用而不被按下。您必须将onPress函数放在箭头函数中,如onPress = {()=> {//HERE YOUR FUNCTION}}