可重用组件的redux-form验证

时间:2016-04-02 07:26:41

标签: reactjs redux redux-form

嘿我尝试使用reduxform验证并对可在表单中重用并且多次​​调用的组件应用验证。

但我最终得到了彼此绑定的所有组合。不在他们自己的背景下。

comp:

export const fields = ['myField'];

const validate = values => {
    const errors = {};

    // just to see the error:
    errors.myField = 'error!! ';

    return errors;
};

class myField extends React.Component {

    render() {

        const {
            fields: { myField }
        } = this.props;


        return (
            <div className="myField">

                <input type="text" {...myField}  />
                {myField.touched && myField.error && <span>{myField.error}</span>}
            </div>
        );
    }
}

myField.propTypes = {
    fields: React.PropTypes.object.isRequired
}

myField = reduxForm({
        form: 'myform',
        fields: fields,
        destroyOnUnmount: false,
        validate
    }
)(myField);

我尝试在名称中使用'[]'但最终得到了X组件的X组件。所以'[]'似乎应该用于列表,而不是同一组件的新实例。

export const fields = ['myField'];

谢谢!

1 个答案:

答案 0 :(得分:0)

reduxForm()装饰器应该装饰整个表单,而不是单个输入。你需要更像这样的东西(组件类应该大写):

// validate.js
const validate = values => {
    const errors = {};

    // just to see the error:
    errors.firstField = 'error!!';
    errors.secondField = 'error!!';

    return errors;
};

// ----------------

// MyField.js
class MyField extends React.Component {
  render() {
    const { field } = this.props;
    return (
      <div className="myField">
        <input type="text" {...myField}  />
        {myField.touched && myField.error && <span>{myField.error}</span>}
      </div>
    );
  }
}
MyField.propTypes = {
  field: React.PropTypes.object.isRequired
};

// ----------------

// MyForm.js
import MyField from './MyField';
import validate from './validate';

class MyForm extends React.Component {
  render() {
    const {
      fields: { firstField, secondField }
    } = this.props;

    return (
      <div className="myForm">
        <MyField field={firstField}/>
        <MyField field={secondField}/>
      </div>
    );
  }
}

MyForm.propTypes = {
  fields: React.PropTypes.object.isRequired
}

MyForm = reduxForm({
  form: 'myform',
  fields: ['firstField', 'secondField'],
  destroyOnUnmount: false,
  validate
})(MyForm);