React:根据状态设置禁用属性

问题描述 投票:0回答:4

我想根据组件的状态在按钮上设置禁用属性,如下所示:

render() {
  return (
    <button type="button" {this.state.submitting ? 'disabled' : ''} 
      onClick={ this.handleSubmit }>Submit</button>
    );
}

目前我在打开 { 时收到意外的令牌错误,我错过了什么?

javascript reactjs
4个回答
75
投票

你可以通过布尔值设置

disabled
属性,就像这样

<button
  type="button"
  disabled={this.state.submitting}
  onClick={this.handleSubmit}
>
  Submit
</button>

Example


6
投票

你可以使用 null

<button type='button' disabled={this.state.submitting ? 'disabled' : null} onClick={this.handleSubmit}>Submit</button>

4
投票

如果您希望根据某些条件添加禁用的属性,您可以执行以下操作:

const btnProps = {};
if (some condition) {
  btnProps.disabled = true;
} else {
  delete btnProps['disabled']
}

然后在你的组件中你可以这样做:

 <Button { ...btnProps } className="btn"> my button </Button>





                    

2
投票

如果您使用打字稿,您可以在 Button 组件的类型/界面中添加 可选属性

disabled?: boolean

使禁用成为可选属性,我们允许布尔值和未定义

因此,如果将禁用的布尔值作为属性传递,它将使用传递的值将禁用属性添加到按钮。如果在这种情况下未传递禁用属性,则其值将被视为未定义,并且将不会添加禁用属性。

import { ReactNode } from 'react'

type Props = {
  disabled?: boolean
  type: 'button' | 'reset' | 'submit'
  btnClass: string
  children: ReactNode
  onClick?: () => void
}

function Button({
  type,
  disabled,
  btnClass,
  children,
  onClick,
}: Props): JSX.Element {
  return (
    <button
      onClick={onClick}
      type={type}
      disabled={disabled}
      className={btnClass}
    >
      {children}
    </button>
  )
}

export default Button

这将避免任何必要的检查,并使代码检查更严格

© www.soinside.com 2019 - 2024. All rights reserved.