【问题标题】:Disable delete button until a new card is created in react.js禁用删除按钮,直到在 react.js 中创建新卡
【发布时间】:2020-12-01 17:40:56
【问题描述】:

我有这个组件,它可以添加具有不同输入值的多张卡片。我有一个删除按钮,可以删除创建的最新卡。我希望在单击和 onkeypress 时禁用删除按钮,直到有不止一张卡。删除按钮似乎是一个有效的工作按钮,但如果只有一张卡,它实际上什么都不做。任何帮助都非常感谢。

这是删除按钮的代码:

 <Button
              onClick={props.deleteCard.bind(null, props.i)}
              aria-label='Remove Card' disabled={props.isLoading}><Icon name='trash' aria/>
            </Button>

添加新卡按钮的代码:

<Button className='btn-confirm'
                                onClick={this.addCard} disabled={!!this.state.loading}>Add Card
                              </Button>

两者的功能:

addCard = () => {
    this.setState((prevState) => {
      const {particles, errors} = prevState
      particles.push({type: 'constant', distributionType: 'uniform', fields: ['', '']})
      errors.particles.push([null, null, null])

      return {particles, errors}
    })
  }

  deleteCard = (index) => {
    if (this.state.particles.length <= 1) {
      return this.setState((prevState) => {
        const {particles, errors} = prevState
        particles[0] = {type: 'constant', distributionType: 'uniform', fields: ['', '']}
        errors.particles[0] = [null, null, null]

        return {particles, errors}
      })
    }

谢谢!

【问题讨论】:

标签: reactjs


【解决方案1】:

disabled 条件添加到您的删除按钮,如下所示:

            <Button
                onClick={props.deleteCard.bind(null, props.i)}
                aria-label='Remove Card' 
                disabled={props.isLoading || props.particles.length > 1}>
              <Icon name='trash' aria/>
            </Button>

【讨论】:

  • 当我的删除按钮位于与我所在状态不同的文件中时,我该如何完成此操作?我将道具中的 deleteCard 函数传递给我的删除按钮。我收到错误:无法读取未定义的属性“状态”
  • 明白了,感谢您的评论。一种方法是将particlesparticles.length 的道具发送到Button,类似于您将isLoading 作为道具发送的方式。我将编辑我的答案以适应用例。
  • 你太棒了!谢谢!
猜你喜欢
  • 2017-05-20
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-30
  • 1970-01-01
  • 2022-01-22
  • 2019-12-21
相关资源
最近更新 更多