简体   繁体   中英

js, react: cannot reenable a button that is rendered as disabled

i have a simple buttoN.

            <Button id='button1' disabled onClick={() => buttonClick(false)}variant="contained">Text</Button>

This button is rendered as a grayed out version of itself, which is good.

Now, I want to enable the button. It should be:

document.getElementById("button1").disabled = false; 

But nothing is enabled again.

What is the issue here?

Generally, you should avoid using document.getElementById and similar in React whenever possible.
To make your button enable, do the following:

const [isDisabled, setIsDisabled] = useState(true);

return (
    <>
        <Button id='button1' disabled={isDisabled} onClick={() => buttonClick(false)}variant="contained">Text</Button>
        <div onClick={() => setIsDisabled(value => !value)}>toggle disabled</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