我处于一个基于React类的组件中,并且处于这样的状态状态:
<xsd:simpleType name="AbsoluteOrRelativeTimeType">
<xsd:union memberTypes="xsd:dateTime xsd:duration" />
</xsd:simpleType>
我有一个从输入组件触发的inputChangedHandler
state = {
controls: {
email: {
validation: {
required: true,
isEmail: true
},
invalid: false,
},
password: {
validation: {
required: true,
minLength: 6
},
invalid: true,
},
disabledSubmit: true,
}
};
还有一个应该从我的inputChangedHandler内调用的disabledSubmitHandler:
inputChangedHandler = (event, controlName) => {
console.log("[STATE]", this.state.controls);
const updatedControls = {
...this.state.controls,
[controlName]: {
...this.state.controls[controlName],
value: event.target.value,
invalid: !this.checkValidity(
event.target.value,
this.state.controls[controlName].validation
)
},
touched: true
};
console.log("[UPDATEDCONTROLS]", updatedControls);
this.setState({ controls: updatedControls }, () => {
this.disabledSubmitHandler();
});
};
该道具像这样设置在我的JSX中的按钮组件上:
disabledSubmitHandler() {
if (
!this.state.controls["email"].invalid &&
!this.state.controls["password"].invalid
) {
this.setState(
{ disabledSubmit: true },
console.log("[DISABLEDHANDLER] TRUE")
);
}
}
这不起作用,但是我不确定发生了什么事
答案 0 :(得分:1)
我认为这似乎需要解决:
disabledSubmitHandler() {
if (
!this.state.controls["email"].invalid && //if email is not invalid
!this.state.controls["password"].invalid //if password is not invalid
) {
this.setState(
{ disabledSubmit: true },
console.log("[DISABLEDHANDLER] TRUE")
);
}
}
该代码说明,如果电子邮件和密码有效,请禁用输入。我认为应该是:
disabledSubmitHandler() {
if (
!this.state.controls["email"].invalid &&
!this.state.controls["password"].invalid
) {
this.setState(
{ disabledSubmit: false },
console.log("[DISABLEDHANDLER] FALSE")
);
}
}
就像@ an0nym0us所说的,disabledSubmit
嵌套在controls
内。
另外,从侧面讲,您会调用一个设置状态的函数,而仅调用另一个在该函数内部设置状态的函数作为设置状态的回调(inputChangedHandler
, disabledSubmitHandler'). It seems you could call that disabled check from within
inputChangedHandler passing it your
updatedControls , and return true/false for
disabledSubmit , resulting in a single call to
setState`