简体   繁体   中英

And with an Or conditional statement in react / javascript

I am trying to disable a button depending on a couple of conditions.

<Button disabled={((myobject && myobject.name === "bob") || user.registered) ? true : false} >my button</Button>

Essentially, I want to disable the button if myobject.name is "bob" or if the user is registered (eg. user.registered is not nil). As it stands now, the button seems to get disabled if myobject.name is "bob" but it seems to ignore user.registered . What am I doing wrong?

many thanks!

您可以通过可选链接和省略三元来简化您的代码,因为它在这里是多余的:

<Button disabled={myobject?.name === "bob" || user.registered}>my button</Button>

Inside the button tag you could try to use just the two constraints you want to impose (I didn't understand why the myobject at the beginning though). It could be something like the following:

(myobject.name === "bob" || user.registered) ? true : false

It looks like you're probably pretty close, the code you have should work fine. I would make sure to check two things. Make sure that user.registered has a "truthy" value.

If it's a string or a number it could be evaluating to false where you don't expect it. In Javascript 0 undefined null "" (empty string) and NaN are all evaluated as false

You should also make sure that myobject is defined somewhere. You'll still get a reference error if myobject never gets declared. if myobject is any of those values that evaluate to false though and user.registered == true then your code should do what I think you're trying to accomplish. If not you might need to give a little more detail as to what you expect to happen and some sample values to look at.

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