如果状态已禁用,则禁用按钮

Disabled button if status disabled

我需要一些帮助,因为我不知道如何使用功能性 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>
 )}

如果我的组件状态为禁用,你能给我一些指导并帮助我如何保持按钮禁用吗?

谢谢。

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

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>);
};