我在打字稿中有一个较长的形式,我们需要根据状态的价值隐藏/显示或启用/禁用。
export interface IState {
Status: string;
DisableBasicForm: boolean;
DisableFeedbackCtrl: boolean;
DisableTypeofReqCtrl: boolean;
DisablePurposeCtrl: boolean;
DisableDutyStation: boolean;
DisableContractManager: boolean;
DisableSection: boolean;
DisableStartDate: boolean;
DisableEndDate: boolean;
DisableEstimateDate: boolean;
DisableTotalBudget: boolean;
DisableDeliveryDate: boolean;
DisableWBS: boolean;
DisableGrant: boolean;
DisableGrantExpiry: boolean;
DisableCaseSubmitter: boolean;
DisablePreparedBy: boolean;
DisablePreparedDate: boolean;
ShowSupplyManagerPanel: boolean;
ShowBudgetOwnerPanel: boolean;
DisableSupplyManagerPanel: boolean;
DisableBudgetOwnerPanel: boolean;
}
在课堂上,我需要在构造函数中启动状态,什么是最好的方法,我不需要在ISTATE中启动非常可变的?
public constructor(props: IGoodsProps) {
super(props);
//What should be written here, minimal code required.
}
如果您对某些具有undefined
默认值的属性可以,则可以使用?
在IState
中将其标记为可选。例如(由于我不知道您的要求,我会随机选择一些属性):
export interface IState {
Status: string; // this one is required
DisableBasicForm?: boolean; // this one is optional
DisableFeedbackCtrl?: boolean;
// ...
}
然后,您可以在构造函数中初始化状态时省略可选属性。
默认情况下,如果您希望任何布尔值为false,在许多情况下,undefined
会起作用,因为undefined
在JavaScript中是" falsey",则可以使用哪些属性?。(如果这没有意义,可以详细介绍)
如果陈述ISTATE,则需要启动ISTATE的每个属性(基于您的逻辑),因为ISTATE中的属性未标记为可选的。
伪代码示例:
public constructor(props: IGoodsProps) {
const {status} = this.props
super(props);
this.state ={
Status: status,
DisableBasicForm: status.Status === 'yourValue',
... // initialize here
}
}
如果您的状态传递给您的状态有一些默认值,则可以使用对象解析器:
public constructor(props: IGoodsProps) {
const {status} = this.props
super(props);
this.state ={
...status,
DisableBasicForm: status.Status === 'yourValue', // just overwrite this property with your logic
}
}
您也可以在codstructor之外初始化状态:
class Component extends React.Component<Props, State> {
state: State = {
Status: 'value',
... // initialize here
}
constructor(props: Props) {
...
}
如果您有一些共享的逻辑来设置状态,并且不想重复自己,则可以使用React.useState
进行评估,但是组件需要是功能。