0

我正在尝试开始使用 mobx-react-forms,但遇到了错误:

Unhandled Rejection (Error): Validation Error: Invalid Field Instance    
-> const form = new Form();

这是我的代码:

import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import { Form as BaseForm } from 'mobx-react-form';
import validatorjs from 'validatorjs';

class Form extends BaseForm{
    plugins() {
        return { dvr: validatorjs };
    }

    setup(){
        return {
            fields: [{
                name: 'amount',
                label: 'Amount',
            }]
        }
    }

    hooks(){
        return {
            onSuccess(form) {
                alert('Form is valid! Send the request here.');
                // get field values
                console.log('Form Values!', form.values());
            },
            onError(form) {
                alert('Form has errors!');
                // get all form errors
                console.log('All form errors', form.errors());
            }
        };
    }
}

@observer
class PaymentForm extends Component {
    render() {    
        const form = new Form();

        return (
            <div>
                <h2>Payment Form</h2>

                <form onSubmit={form.onSubmit}>
                    <label>
                        {form.$('amount').label}
                        <input {...form.$('amount').bind()} />
                        <p>{form.$('amount').error}</p>
                    </label>
                </form>
            </div>
        )
    }
}

export default PaymentForm;
4

2 回答 2

0

好吧,您的标签定义错误,正确的设置应如下所示:

setup() {
  return {
    fields: {
      <fieldName>: { <properties> },
    }
  }
}

例如,这些属性可以是value

于 2018-03-22T10:08:52.487 回答
0

这原来是我正在运行的版本控制错误:

"dependencies": {
  "axios": "^0.18.0",
  "custom-react-scripts": "^0.2.2",
  "expect": "^23.0.0-alpha.0",
  "mobx": "^4.1.0",
  "mobx-react": "^5.0.0",
  "mobx-react-form": "^1.32.3",
  "react": "^16.2.0",
  "react-dom": "^16.2.0",
  "react-redux": "^5.0.7",
  "react-router-dom": "^4.2.2",
  "validatorjs": "^3.14.2"
},

我降级为:

"dependencies": {
  "axios": "^0.18.0",
  "custom-react-scripts": "^0.2.2",
  "expect": "^23.0.0-alpha.0",
  "mobx": "^3.3.1",
  "mobx-react": "^4.3.3",
  "mobx-react-form": "^1.32.3",
  "react": "^16.2.0",
  "react-dom": "^16.2.0",
  "react-redux": "^5.0.7",
  "react-router-dom": "^4.2.2",
  "validatorjs": "^3.13.5"
}

现在一切正常。

于 2018-03-22T17:17:08.913 回答