问题
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?
回答1:
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.
回答2:
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.
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/28519023/does-the-classname-attribute-take-on-the-role-of-the-id-attribute-in-reactjs