【问题标题】:Disabled button if status disabled如果状态禁用,则禁用按钮
【发布时间】:2021-01-28 14:45:29
【问题描述】:

我需要一些帮助,因为我不知道如何使用功能性 React 管理禁用的按钮。

首先,isDisabled 函数持有一个条件,并据此设置按钮状态,但我不确定在哪里调用该函数。该按钮包含一个 disabled 属性,它接收在开始时声明的 disabled 状态。

以下是我目前尝试过的代码:

const MainComponent = ({component}) => {
 const [disabled, setDisabled] = useState('');

const isDisabled = () => {
 if (component.status === 'disabled') {
   setDisabled();
  };
}
 
 return (
  <div>
 <Button> 
 onClick={createItem}
 disabled={disabled}
 Button
 <Button/>
 </div>
 )}

如果我的组件状态为禁用,您能否为我提供一些指导并帮助我了解如何使按钮保持禁用状态?

谢谢。

【问题讨论】:

  • props值&lt;Button&gt; onClick={createItem} disabled={component.status === 'disabled'}Button &lt;Button/&gt;可以直接用相等运算符的结果@
  • 我同意@anonymous 的评论,如果您仍有疑问,可以参考codesandbox.io/s/react-functional-component-forked-e4265 进行实施..

标签: javascript reactjs button react-hooks react-functional-component


【解决方案1】:

有多种方法可以做到这一点。这将是最直接的(但请继续阅读):

const MainComponent = ({component}) => {
  const [disabled, setDisabled] = useState(false);

  return (<div>
  <Button
    onClick={() => {createItem(); setDisabled(true);}}
    disabled={disabled}
  >
    Button
    <Button/>
  </div>);
};

但是,由于createItem 没有出现在您的代码中,我假设它是您组件的父范围内的一个函数。如果是这种情况,则应在此处跟踪状态,并且您应该摆脱此组件中的useState。然后,您只需使用 (reactive) 属性来设置按钮状态:

const MainComponent = ({component, createItem}) => {
  return (<div>
    <Button
      onClick={createItem}
      disabled={component.status === 'disabled'}
    >
      Button
    <Button/>
  </div>);
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-04
    • 1970-01-01
    • 2019-10-24
    相关资源
    最近更新 更多