因此,我很困惑,一旦在名为Add
的特定输入中键入了文本,我试图在Material UI dialog
中启用company_name
按钮。我有一个addEnable
布尔状态值。我最初将状态从addEnable
设置为false。然后,我为handleInputChanges
输入字段的onChange
事件使用了company_name
。在那个handleInputChanges
中,我使用prevState
的addEnable
将其设置为true。但是该按钮未启用。
interface CompanyFinancialModalState {
addEnabled: boolean;
[key: string]: any;
values: IValues[];
}
export interface IValues {
company_name: string;
critical_technology: string[];
}
interface CompanyFinancialModalProps {
open: boolean;
onClose: () => void;
}
export class CompanyFinancialModal extends React.Component<
CompanyFinancialModalProps,
CompanyFinancialModalState
> {
constructor(props: CompanyFinancialModalProps) {
super(props);
this.state = {
addEnabled: false,
company_name: '',
critical_technology: [],
values: []
};
}
public render() {
const { open, onClose } = this.props;
const { addEnabled } = this.state;
return (
<>
<Dialog
open={open}
onClose={onClose}
className="company-financial-modal"
>
<DialogTitle id="company-financial-modal-title">
{'Company and Financial Data'}
</DialogTitle>
<DialogContent>
<div>
<Form
onSubmit={this.processFormSubmission}
// validate={this.validateForm}
// tslint:disable-next-line jsx-no-lambda
render={({
handleSubmit,
/* reset, submitting, pristine, */ values
}) => (
<form onSubmit={handleSubmit}>
<Paper style={{ padding: 16 }}>
<Grid container={true} alignItems="flex-start" spacing={2}>
<Grid item={true} xs={12}>
<Field
fullWidth={true}
required={true}
name="company_name"
component={TextField}
type="text"
label="Company Name"
onChange={this.handleInputChanges}
/>
</Grid>
</Grid>
</Paper>
</form>
)}
/>
</div>
</DialogContent>
<DialogActions>
<Button
id="company-financial-modal-add"
disabled={!addEnabled}
onClick={onClose}
color="primary"
>
Add
</Button>
<Button
id="company-financial-modal-cancel"
onClick={onClose}
color="secondary"
autoFocus={true}
>
Cancel
</Button>
</DialogActions>
</Dialog>
</>
);
}
private handleInputChanges = (e: React.FormEvent<HTMLInputElement>) => {
e.preventDefault();
this.setState({ [e.currentTarget.name]: e.currentTarget.value });
this.setState((prevState) => {
return { addEnabled: prevState.addEnabled }
})
}
}
export default CompanyFinancialModal;
如果在第二次触发handleInputChanges时使用prevState,则一旦company_name字段中有一些输入,您将希望始终启用该按钮,则将再次禁用该按钮。
return { addEnabled: true }
然后该函数看起来像这样
private handleInputChanges = (e: React.FormEvent<HTMLInputElement>) => {
e.preventDefault();
this.setState({ [e.currentTarget.name]: e.currentTarget.value });
this.setState((prevState) => {
return { addEnabled: true }
})
}