所以我有这个功能,当输入为空时,我需要在我的模态中禁用该按钮。
canBeSubmitted() {
const { Department, Employee_Name, Address } = this.state;
return (
Department.length > 0 &&
Employee_Name.length > 0 &&
Address.length > 0
);
}
但是当单击模态时我将其指定为空,但是按钮再次启用,它应该被禁用
handleSubmit(name, address,department){
const laman = {
'Employee_Name': name,
'Address': address,
'Department': department
}
return fetch('http://localhost:5118/api/employeedetails/PostEmployeeDetail?', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(laman)
})
.then(function(response) {
console.log(response)
return response.json();
})
.then((result)=> {
var jsonReturnedValue = [...this.state.jsonReturnedValue];
jsonReturnedValue.push(result);
this.setState({jsonReturnedValue})
//this is where i call the function but it doesnt work
this.canBeSubmitted()
this.refs.Name.value="";
this.refs.Address.value="";
this.refs.Department.value="";
// this.setState({ value: '' });
})
.catch(function(error) {
console.log(error);
})
这是我的按钮
<input type="button" className="btn btn-info"disabled={!isEnabled}
onClick = { this.handleSubmit.bind(
this, this.state.Employee_Name,
this.state.Address,
this.state.Department)
}
value =" Add Employee"
data-dismiss="modal"/>
答案 0 :(得分:0)
按钮未禁用的原因是您没有切换html中使用的 isEnabled 变量。 我的建议如下: 在你班级的构造函数中
constructor(props){
super(props);
this.setState({
isEnabled: false
});
}
现在您已在构造函数中初始化了一个默认值。
现在,在您的承诺的成功条款中,使用以下代码:
.
.
.
this.canBeSubmitted()
this.refs.Name.value="";
this.refs.Address.value="";
this.refs.Department.value="";
this.setState({
isEnabled: true
});
并在错误子句中将状态设置为false
.catch(function(error) {
console.log(error);
this.setState({
isEnabled: false
});
})
现在将您的html更改为以下内容:
render(){
.
.
let {isEnabled} = this.state;
return (
<input type="button" className="btn btn-info" disabled={isEnabled}
onClick = { this.handleSubmit.bind(
this, this.state.Employee_Name,
this.state.Address,
this.state.Department)
}
value =" Add Employee"
data-dismiss="modal"/>
);
}
编写一个新方法,应该在关闭模态时调用,并将 isEnabled 的状态值设置回 false