简体   繁体   中英

Disabled button if status disabled

I need some help because I can't figure out how to manage a disabled button using functional React.

First of all, isDisabled function holds a condition and according on that I set the button state, but I'm not sure where to call the function. The button contains a disabled prop that receives the disabled state declared at the beggining.

Below is the code I've tried so far:

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

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

Could you provide me some direction and help me on how to keep the button disabled if my component status is disabled?

Thank you.

There are multiple ways of doing this. This would be the most straightforward (but keep reading):

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

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

However, since createItem doesn't appear in your code, I assume that it is a function in the parent scope of your component. If that is the case, then the status should be tracked there and you should get rid of the useState in this component. You'd then just use the (reactive) prop to set the button state:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM