2017-03-07 28 views
0

我想在用戶從vazco/uniforms組件中單擊AutoForm內的提交按鈕時調用一個函數。我還使用參數schema = {schema}來驗證表單數據是否正確。如果表單不正確,會發生什麼情況,我沒有找到觸發該功能的方法。我怎樣才能在AutoForm上設置它?如何在嘗試使用vazco/uniforms提交表單時觸發某個功能?

細節:我需要當用戶點擊表單的按鈕提交。

我:

<AutoForm 
    showInlineError 
    schema={schema} 
    model={model} 
    label={false} 
    onSubmit={this.submitForm.bind(this)} 
> 
... 
</AutoForm> 

我知道我可以寫:

onValidate={(modelTmp, error, callback) => {..}}

modelTransform={(mode, model) => {..}}

但這個功能我不知道用戶只需點擊提交b utton,或者如果他在表格上鍵入內容並且正在改變模型。

任何想法如何解決它?

回答

0

我跟vazco /制服,拉多斯拉夫·Miernik的創造者,他說,有解決它的方法有兩種:

1)添加的形式,當它被點擊了一個按鈕,觸發功能。

2)創建一個自定義表單。

由於我正在尋找一個解決方案只使用AutoForm,我注意到這是不可能的。然後,我的解決方案是創建一個我需要的自定義表單。所以解決方案是自定義表格(基於AutoForm):

import cloneDeep from 'lodash.clonedeep'; 
import isEqual from 'lodash.isequal'; 
import set from 'lodash.set'; 
import {PropTypes} from 'react'; 


import ValidatedQuickForm from 'uniforms-bootstrap3/ValidatedQuickForm'; 

const Auto = parent => class Custom extends parent { 
    static Auto = Auto; 
    static displayName = `Auto${parent.displayName}`; 

    static propTypes = { 
     ...parent.propTypes, 
     onChangeModel: PropTypes.func 
    }; 

    constructor() { 
     super(...arguments);// eslint-disable-line 

     this.state = { 
      ...this.state, 
      model: this.props.model, 
      modelSync: this.props.model 
     }; 
    } 

    componentWillReceiveProps({model}) { 
     super.componentWillReceiveProps(...arguments);// eslint-disable-line 

     if (!isEqual(this.props.model, model)) { 
      this.setState({model, modelSync: model}); 
     } 
    } 


    func() { 
     // makes whatever i need 
    } 

    getNativeFormProps() { 
     const { 
      onChangeModel, // eslint-disable-line no-unused-vars 
      ...props 
     } = super.getNativeFormProps(); 

     return props; 
    } 

    getModel(mode) { 
     return mode === 'form' ? this.state.modelSync : this.state.model; 
    } 

    onChange(key, value) { 
     this.setState(state => ({modelSync: set(cloneDeep(state.modelSync), key, value)}),() => { 
      super.onChange(...arguments);// eslint-disable-line 
      this.setState({model: this.state.modelSync},() => { 
       if (this.props.onChangeModel) { 
        this.props.onChangeModel(this.state.model); 
       } 
      }); 
     }); 
    } 

    onReset() { 
     this.setState(() => { 
      super.onReset(); 

      return { 
       model: this.props.model, 
       modelSync: this.props.model 
      }; 
     }); 
    } 

    onSubmit(event) { 
     if (event) { 
      event.preventDefault(); 
      event.stopPropagation(); 
     } 

     this.func(); // func that i wanted to call 

     return new Promise(resolve => 
      this.setState({validate: true},() => 
       resolve(this.onValidate().then(
        () => super.onSubmit())) 
      ) 
     ); 
    } 

    onValidate() { 
     return this.onValidateModel(this.getChildContextModel()); 
    } 
}; 

export default Auto(ValidatedQuickForm); 
相關問題