我有一个用于编辑包含多个文本输入字段的公司信息的表格。
该表单可以处于“编辑”模式或“查看”模式。在“查看”模式下,所有文本字段均被禁用,主按钮带有标签“编辑”。如果用户按下“编辑”,则将调度companyEdit(true)操作,并且表单的模式将更改为“编辑”。然后,主按钮将其标签更改为“保存”,并且应该重新渲染字段,这一次允许进行编辑。
当表单模式从“编辑”模式更改为“查看”模式时,我设法使主按钮更改了其标签,但是并没有重新渲染字段以将其从禁用状态更改为启用状态。在状态更改时应该自动调用此重新渲染吗?还是应该手动调用它?
以下是一些代码:
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { companyEdit } from '../actions/Company';
class CompanyScreen extends Component {
editButtonHandle = () => {
}
cancelButtonHandle = () => {
}
renderField = (field) => {
const { mode } = this.props.editor;
return (
<div>
<label>{field.label}</label>
<input
type="text"
{...field.input}
disabled = { mode != 'edit' }
/>
</div>
);
}
render() {
const { handleSubmit, pristine, initialValues } = this.props;
const { mode } = this.props.editor;
return (
<div>
<form onSubmit={handleSubmit(this.onSubmit)}>
<Field
label="Name"
name="name"
component={this.renderField}
/>
<Field
label="E-mail"
name="email"
component={this.renderField}
/>
<button
type="button"
onClick={this.editButtonHandle}
>
{ mode == 'view' ? 'Edit' : 'Save'}
</button>
</form>
</div>
);
}
}
const mapStateToProps = ({company}) => {
const {info, editor} = company;
return {
initialValues: info,
editor
}
}
export default connect(
mapStateToProps,
{ companyEdit }
)(
reduxForm({
form: 'CompanyForm',
enableReinitialize : true
})(CompanyScreen)
);
这是减速器:
import { COMPANY_EDIT } from '../constants/ActionTypes';
const INIT_STATE = {
info: {
id: "1",
name: "My company",
email: "mycompany@gmail.com",
},
editor: {
mode: "view"
}
}
export default (state = INIT_STATE, action) => {
switch (action.type) {
case COMPANY_EDIT:
const editor = {
...state.editor,
mode: action.payload ? 'edit' : 'view'
}
return { ...state, editor: editor}
default:
return state;
}
}
当mode
道具更改时,按钮会正确重新呈现,但是Field
却没有:-(