Does the className attribute take on the role of t

2020-07-13 09:18发布

Since id attributes are rarely used in Reactjs components due to the fact that id attributes imply that the component will not be reused, then are className attributes used instead of id's? If this is the case, then what is the Reactjs equivalent of the class attribute in HTML?

4条回答
放荡不羁爱自由
2楼-- · 2020-07-13 09:42

To add to insin's answer, ids do have practical uses, but styling is not one of them.

The two cases are fragment identifiers, and input/label pairing. In that case, you usually want to generate ids that are guaranteed to be globally unique (but consistent across renders). For that, use a mixin like unique-id-mixin.

查看更多
可以哭但决不认输i
3楼-- · 2020-07-13 09:44

ID's are for single use (in React and in general) or one-time instances.

classNames are for multiple usage (in React and in general) or for many-time instances - the same way that classes are used in traditional CSS.

查看更多
够拽才男人
4楼-- · 2020-07-13 09:48

className is used for class names for CSS styling, just as elsewhere.

You can give something a unique className for styling purposes the same way you might give otherwise give it an id, sure, but that doesn't really imply anything else for other className usage, which can never really be a direct equivalent to id because className can contain multiple class names, none of which have to be unique. (There are also pretty good reasons not to use id for styling, regardless of React).

A more usual reason not to give something an id with React is that you rarely need to add hooks to go and look up an element from the real DOM, as you can use state or props to control rendering changes which do whatever dynamic stuff you need to do, and if you do need to go grab an element, you can give it a ref name and use getDOMNode() on it.

查看更多
We Are One
5楼-- · 2020-07-13 09:51

First of all, ids are used with React, and they don't necessarily prevent re-use. For instance, if you'd want to use a element then you'd have to give it an ID (so it can be referenced from the "list" attribute of its tag). In that case, I usually auto-generate an ID using a counter variable. Hence, IDs and re-use don't have to rule each other out.

To answer your question, the className attribute is used instead and works just like the class attribute. The "react/addons" module provides a utility for easily creating className values.

查看更多
登录 后发表回答