首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在按insert item按钮时启用redux-form字段数组中禁用的字段?

在按下"insert item"按钮时,如果要启用redux-form字段数组中被禁用的字段,可以采取以下步骤:

  1. 在redux-form的表单组件中,将字段数组的状态存储在Redux store中。可以使用redux-form的FieldArray组件来处理字段数组。
  2. 在表单组件的state中,创建一个属性来存储每个字段是否被禁用的状态。初始时,所有字段都被禁用。
  3. 当点击"insert item"按钮时,触发一个Redux action,该action将更新字段数组的状态。通过修改对应字段的禁用状态为false,以启用该字段。
  4. 在Redux reducer中,更新字段数组的状态,根据action中的信息修改对应字段的禁用状态。
  5. 在表单组件中,使用redux-form的FieldArray组件来渲染字段数组,并根据每个字段的禁用状态来设置对应字段的禁用属性。

示例代码如下所示:

  1. 定义Redux action和reducer:
代码语言:txt
复制
// actions.js
export const enableField = (fieldIndex) => ({
  type: 'ENABLE_FIELD',
  payload: fieldIndex
});

// reducer.js
const initialState = {
  fields: [{ disabled: true }, { disabled: true }, { disabled: true }]
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'ENABLE_FIELD':
      return {
        ...state,
        fields: state.fields.map((field, index) => {
          if (index === action.payload) {
            return { ...field, disabled: false };
          }
          return field;
        })
      };
    default:
      return state;
  }
};

export default reducer;
  1. 在表单组件中使用redux-form的FieldArray组件:
代码语言:txt
复制
import React from 'react';
import { connect } from 'react-redux';
import { Field, FieldArray, reduxForm } from 'redux-form';

const renderFields = ({ fields }) => (
  <ul>
    {fields.map((field, index) => (
      <li key={index}>
        <Field
          name={field}
          component="input"
          type="text"
          disabled={fields[index].disabled} // 根据字段的禁用状态设置禁用属性
        />
      </li>
    ))}
  </ul>
);

const MyForm = ({ handleSubmit, enableField }) => (
  <form onSubmit={handleSubmit}>
    <FieldArray name="fields" component={renderFields} />
    <button type="button" onClick={() => enableField(1)}>Insert Item</button>
    <button type="submit">Submit</button>
  </form>
);

const mapStateToProps = (state) => ({
  initialValues: state.form
});

const mapDispatchToProps = (dispatch) => ({
  enableField: (fieldIndex) => dispatch(enableField(fieldIndex))
});

export default connect(mapStateToProps, mapDispatchToProps)(
  reduxForm({ form: 'myForm', enableReinitialize: true })(MyForm)
);

这样,在按下"insert item"按钮时,字段数组中被禁用的字段将被启用。你可以根据实际需求进行修改和调整。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券