使用 DOM 属性作为状态的条件类名 | simeonGriggs.dev

Adam Wathan recently tweeted a tip. After using it in a project, the author is convinced and decided to write a complete guide. The guide uses code examples to explain conditional class names when using JSX templates and can be adapted for other languages.

It starts with a basic list of "products" rendered in a flex column. The simplest way to conditionally style them is with a template literal, but for three possibilities, it looks ugly. Then, clsx is introduced, which makes the dynamic creation of a list of class names more readable. However, the resulting output in the DOM is not easily debuggable.

The solution is to store the component's "state" in data attributes and conditionally apply styles based on the element. Another useful tip is to style children based on the data attributes of a parent.

More DOM-as-state patterns are also discussed, such as styling based on ARIA attributes and styling form elements based on state. For styling based on ARIA attributes, using aria-hidden can avoid layout shift and make animations smoother. For styling form elements based on state, there are built-in pseudo selectors in the docs.

阅读 14
0 条评论