2017-05-25 49 views
0

所以我有这个功能,当输入为空时,我需要禁用模式中的按钮。是否可以在函数内部放置一个函数?

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 
}); 

,并设置状态恢复到虚假的错误子句中

.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的状态值回

+0

它的工作原理,但从未启用按钮 –

+0

你写了一个关闭模式调用的方法吗? –

相关问题