mobx-react-forms的问题

时间:2018-03-21 18:31:40

标签: javascript reactjs ecmascript-6 mobx mobx-react-form

我正在尝试使用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;

2 个答案:

答案 0 :(得分:0)

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

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

这些属性可以是value

答案 1 :(得分: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"
}

现在有些事情正在发挥作用。