在按下"insert item"按钮时,如果要启用redux-form字段数组中被禁用的字段,可以采取以下步骤:
示例代码如下所示:
// 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;
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"按钮时,字段数组中被禁用的字段将被启用。你可以根据实际需求进行修改和调整。
领取专属 10元无门槛券
手把手带您无忧上云