React:根据状态设置禁用属性
React: setting the disabled attribute based on a state
我想根据组件的状态在 Button 上设置禁用属性,如下所示:
render() {
return (
<button type="button" {this.state.submitting ? 'disabled' : ''}
onClick={ this.handleSubmit }>Submit</button>
);
}
目前我在开始时收到意外令牌错误{,我错过了什么?
你可以通过布尔值设置disabled
属性,像这样
<button
type="button"
disabled={this.state.submitting}
onClick={this.handleSubmit}
>
Submit
</button>
你可以使用 null
<button type='button' disabled={this.state.submitting ? 'disabled' : null} onClick={this.handleSubmit}>Submit</button>
如果您希望根据某些条件添加禁用的属性,您可以这样做:
const disableBtnProps = {};
if (some condition) {
disableBtnProps.disabled = false;
} else {
disableBtnProps.disabled = true;
}
然后在你的组件中你可以这样做:
<Button {...disableBtnProps} className="btn"> my button </Button>
如果您使用的是打字稿,您可以在 Button 组件的 type/interface 中添加 optional property
disabled?: boolean
将 disabled 设为可选 属性 我们允许布尔值和 undefined
因此,如果将 disabled 的布尔值作为 prop 传递,它将使用传递的值将 disabled 属性添加到按钮。如果在这种情况下未传递 disabled 属性,则其值将被视为未定义,并且不会添加 disabled 属性。
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
这将避免任何必要的检查并使代码检查更严格
我想根据组件的状态在 Button 上设置禁用属性,如下所示:
render() {
return (
<button type="button" {this.state.submitting ? 'disabled' : ''}
onClick={ this.handleSubmit }>Submit</button>
);
}
目前我在开始时收到意外令牌错误{,我错过了什么?
你可以通过布尔值设置disabled
属性,像这样
<button
type="button"
disabled={this.state.submitting}
onClick={this.handleSubmit}
>
Submit
</button>
你可以使用 null
<button type='button' disabled={this.state.submitting ? 'disabled' : null} onClick={this.handleSubmit}>Submit</button>
如果您希望根据某些条件添加禁用的属性,您可以这样做:
const disableBtnProps = {};
if (some condition) {
disableBtnProps.disabled = false;
} else {
disableBtnProps.disabled = true;
}
然后在你的组件中你可以这样做:
<Button {...disableBtnProps} className="btn"> my button </Button>
如果您使用的是打字稿,您可以在 Button 组件的 type/interface 中添加 optional property
disabled?: boolean
将 disabled 设为可选 属性 我们允许布尔值和 undefined
因此,如果将 disabled 的布尔值作为 prop 传递,它将使用传递的值将 disabled 属性添加到按钮。如果在这种情况下未传递 disabled 属性,则其值将被视为未定义,并且不会添加 disabled 属性。
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
这将避免任何必要的检查并使代码检查更严格