2017-07-20 2 views

Antwort

1

Dies ist, wie ich bin die Validierung in der react-toolbox durchführen.

class MyComponent extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     username: '', 
     active: false, // for Dialog open/close 
     errors: {} 
    }; 
    this.updateState = this.updateState.bind(this); 
    this.validateFormField = this.validateFormField.bind(this); 
    } 

    updateState(value, e) { 
    this.setState({ 
     [e.target.name]: value 
    }); 
    } 

    validateFormField(e) { 
    const propName = e.target.name; 
    const value = e.target.value; 
    const errors = { ...this.state.errors }; 

    errors[propName] = ''; 
    switch (propName) { 
     case 'username': 
     if (value === '') { 
      errors[propName] = 'Username required'; 
     } 
     // add other checks for username 
     break; 
     // add more for fields 
     default: 
    } 

    this.setState({ 
     errors 
    }); 
    } 

    render() { 
    const actions = [ 
     { label: 'Cancel', onClick: this.cancelAction }, 
     { label: 'Submit', onClick: this.submitForm } 
    ]; 
    return (
     <Dialog 
     actions={actions} 
     active={this.state.active} 
     > 
     <Input 
      type="text" 
      name="username" 
      label="Username" 
      onChange={this.updateState} 
      value={this.state.username} 
      onBlur={this.validateFormField} 
      error={this.state.errors.username} 
     /> 
     </Dialog> 
    ); 
    } 
} 

Hoffe, das hilft.