乐闻世界logo
搜索文章和话题

How to add a class with ReactJS ?

1个答案

1

In React, you can add CSS classes to elements using the className attribute. This attribute accepts a string in JSX, which contains one or more class names separated by spaces. Here is a basic example using the className attribute:

jsx
function MyComponent() { return ( <div> <h1 className="title">Welcome to my website</h1> <p className="description">This is a great place.</p> </div> ); }

In the above code, the <h1> element is assigned the title class, and the <p> element is assigned the description class.

If you need to dynamically add or remove classes based on component state or props, you can construct the className value using template literals or logical operators. For example:

jsx
function MyComponent({ isActive }) { const activeClass = isActive ? 'active' : 'inactive'; return ( <div className={`my-component ${activeClass}`}> This component is now {isActive ? 'active' : 'inactive'}. </div> ); }

In this example, the component's className dynamically includes the active or inactive class based on the value of the isActive prop. If isActive is true, className will be "my-component active", otherwise it will be "my-component inactive".

Ensure that you have defined these classes in your component's CSS file so that they can be applied correctly.

2024年6月29日 12:07 回复

你的答案