Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - hidden attribute ignored on Button component

I'm trying to hide a Material-UI Button component by adding the hidden attribute, but it appears the attribute is ignored. I've used the hidden attribute on other Material-UI components such as Typography, Grid and Box and there it works fine. Below is a simplified snippet of my code. Click here to try it out on CodeSandbox.

<Typography hidden={loading}>
  Works. This text is not displayed when `loading` is truthy.
</Typography>
<Button hidden={loading}>
  Doesn't work. This Button is still there!
</Button >

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

TLDR: Don't use the hidden attribute. Use conditional rendering like {loading && <Component/>} or a style like <Component style={{ display: loading ? 'none' : undefined }} />

First, the hidden attribute has nothing to do with Material UI or React, but is a default HTML attribute from the web standard. Second, the hidden attribute is overridden if a display: ... style is applied to the same element. It doesn't matter if these styles are inline or coming from CSS. As a result, the hidden attribute is "ignored" by any Material-UI component that happens to set the display attribute.

You can try this on any of the examples from the official docs. For example, playing around with CodeSandbox you can see hidden work on Card, CardContent and Typography, but ignored on CardActionArea, CardMedia, CardActions and Button.

Considering the above it's best to avoid the hidden attribute as its behavior is different on a per-component basis. Moreover, if in any next version of Material UI a component is updated to use display internally, it'll change the semantics of hidden for that component and break stuff in your code base.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...