为“字段” redux组件构建一个更高阶的组件

时间:2018-08-13 22:33:58

标签: reactjs redux redux-form

我有一个Field组件,我想构建一个新的CurrencyField

旧的Field组件

<Field
    component={FormField}
    id="amount"
    label="Amount"
    type="text"
    name="amount"
    {...currencyMask}
    maxLength={16}
    valid={}
    validate={[
        required(),
        length({ max: 13 }),
        numericality({ '>': 0, msg: 'Must be greater than 0!' }),
        numericality({ '<=': loan.AccountBalance, msg: `Must be less than or equal to customer's account balance of $${loan.AccountBalance}` }),
    ]}
/>

新的CurrencyField相当于上面的Field,我想看起来像这样:

<CurrencyField
    id="amount"
    label="Amount"
    type="text"
    name="amount"
/>

<Field
    component={CurrencyField}
    id="amount"
    label="Amount"
    type="text"
    name="amount"
/>

尝试执行此操作时出现错误:

export const CurrencyField = (props) => {

  return (
    <Field
      name={props.input.name}
      type={props.type || "text"}
      maxLength={16}
      {...props}
      validate={[
        required(),
        length({ max: 11 }),
        numericality({ '>': 0, msg: 'Must be greater than 0!' })
      ]}
    />
  );
}

2 个答案:

答案 0 :(得分:2)

您遇到什么错误?

此外,您还应将验证功能移至渲染https://github.com/erikras/redux-form/issues/4017之外

const validateCurrency = [
    required(),
    length({ max: 11 }),
    numericality({ '>': 0, msg: 'Must be greater than 0!' })
 ]
export const CurrencyField = (props) => {
    return (
      <Field
         name={props.input.name}
         type={props.type || "text"}
         maxLength={16}
         {...props}
         validate={validateCurrency}
      />
    );
}

答案 1 :(得分:1)

您在CurrencyField无状态函数的新 Field 组件中缺少了 组件 属性