在React中创建动态CSS类可以通过以下几种方式实现:
import React, { useState } from 'react';
const MyComponent = () => {
const [isActive, setIsActive] = useState(false);
const handleClick = () => {
setIsActive(!isActive);
};
const dynamicStyle = {
backgroundColor: isActive ? 'red' : 'blue',
color: isActive ? 'white' : 'black',
};
return (
<div>
<button onClick={handleClick}>Toggle</button>
<div style={dynamicStyle}>Dynamic CSS Class</div>
</div>
);
};
export default MyComponent;
// MyComponent.module.css
.active {
background-color: red;
color: white;
}
.inactive {
background-color: blue;
color: black;
}
// MyComponent.jsx
import React, { useState } from 'react';
import styles from './MyComponent.module.css';
const MyComponent = () => {
const [isActive, setIsActive] = useState(false);
const handleClick = () => {
setIsActive(!isActive);
};
const dynamicClassName = isActive ? styles.active : styles.inactive;
return (
<div>
<button onClick={handleClick}>Toggle</button>
<div className={dynamicClassName}>Dynamic CSS Class</div>
</div>
);
};
export default MyComponent;
import React, { useState } from 'react';
import classNames from 'classnames';
const MyComponent = () => {
const [isActive, setIsActive] = useState(false);
const handleClick = () => {
setIsActive(!isActive);
};
const dynamicClassName = classNames({
active: isActive,
inactive: !isActive,
});
return (
<div>
<button onClick={handleClick}>Toggle</button>
<div className={dynamicClassName}>Dynamic CSS Class</div>
</div>
);
};
export default MyComponent;
以上是在React中创建动态CSS类的几种常见方法。根据具体的需求和项目情况,选择适合的方法来实现动态CSS类的效果。
领取专属 10元无门槛券
手把手带您无忧上云