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?
相关问题
- How to toggle on Order in ReactJS
- Refreshing page gives Cannot GET /page_url in reac
- Adding a timeout to a render function in ReactJS
- React Native Inline style for multiple Text in sin
- Issue with React.PropTypes.func.isRequired
相关文章
- Why would we use useEffect without a dependency ar
- Is it possible to get ref of props.children?
- Stateless function components cannot be given refs
- React testing library: Test attribute / prop
- React/JestJS/Enzyme: How to test for ref function?
- Material-UI [v0.x] RaisedButton on hover styles
- Remove expo from react native
- ReactJS toLowerCase is not a function
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.
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.
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 anid
, sure, but that doesn't really imply anything else for otherclassName
usage, which can never really be a direct equivalent toid
becauseclassName
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 aref
name and usegetDOMNode()
on it.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.