我需要使用redux格式和React-JS来检查字段,具体取决于其他字段。 表单是从对象动态生成的。
例如,我的表单上有两个字段。 复选框pickup_allowed和zip文本。
只有在选中pickup_allowed时,zip文本才是必填项且可见。 如何根据其他字段检查字段并使用redux表单和React JS呈现或不显示?
代码:
const sellingFormFieldDescription = [
{key: 'pickup_allowed',
type: 'checkbox',
checkRules: {
mandatory: false
} },
{
key: 'zip_code',
type: 'integer',
checkRules: {
minValue: 1,
maxValue: 99999,
maxLength: 5,
mandatoryAndVisibleIf : { key:'pickup_allowed', checked: true}
}]
const minValue = min => value =>
value && value > min && `Must be greater than ${ min }` || undefined;
const maxValue = max => value =>
value && value > max && `Must be greater than ${ max }` || undefined;
const maxLength = max => value =>
value && value.length > max && `Must be longer than ${ max }` || undefined;
const mandatory = isMandatory => value =>
isMandatory && value && undefined || 'Mandatory';
const rules = { minValue, maxValue, maxLength, mandatory };
const applyRules = checkRules => {
let validations = [];
for(let ruleName in checkRules) {
let ruleFunc = rules[ruleName]
if(ruleFunc) {
validations.push(ruleFunc(checkRules[ruleName]))
}
}
return validations;
}
class SellingFormFast extends Component {
render() {
{ sellingFormFieldDescription.map((field,i) => {
const validate = applyRules(field.checkRules);
if(field.type === 'checkbox' ){
return <Field name={field.key} key={i} component={renderCheckbox} validate={validate} />
} else if (field.type === 'integer') {
return <Field name={field.key} key={i} component={renderField} validate={validate}/>
}});
}
}
}
export default reduxForm({form: 'sellling_form_fast'})(SellingFormFast)