当前位置: 代码迷 >> JavaScript >> 在禁用的道具上反应组件函数从未调用过
  详细解决方案

在禁用的道具上反应组件函数从未调用过

热度:90   发布时间:2023-06-05 09:21:41.0

我有以下问题。 我需要禁用按钮,对于disabled道具,我通过函数来??控制这种行为。 出于某种原因,它从未被调用。 我的代码是这样的:

isValid = () => { 
  //conditions 
}

createNextButton = () => {
  return(
    <button disabled={!this.isValid})>next</button>
  )
}

createBackButton = () => {
  //similar as next button
}

generateButtons = () => (
  <div>
    {this.createBackButton()}
    {this.createNextButton()}
  </div>
)

render() {
  return(
    //something
    <div>
      {this.generateButtons()}
    </div>
)}

这大致是我代码的相关部分的样子。 除了isValid函数之外,所有东西都被调用了,我不知道为什么。 我错过了什么吗?

只有几个小的语法错误可以解决这个问题 - 首先,将括号()添加到this.isValid ,如下所示,以将isValid作为函数执行(而不是作为变量访问它)。 另外,删除}和>之间的额外括号) :

createNextButton = () => {
  return(
    <button disabled={!this.isValid()}>next</button>
  )
}

disabled 应设置为 true 或 false。 调用您的函数并从中返回 true 或 false。

isValid = () => { 
  //conditions 
// return true or false
}


<button disabled={!this.isValid()}>next</button>
  相关解决方案