在React中动态更改组件的className可以通过以下几种方式实现:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isActive: false
};
}
handleClick = () => {
this.setState(prevState => ({
isActive: !prevState.isActive
}));
}
render() {
const { isActive } = this.state;
const className = isActive ? 'active' : 'inactive';
return (
<div className={className}>
<button onClick={this.handleClick}>Toggle</button>
</div>
);
}
}
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isActive: false
};
}
handleClick = () => {
this.setState(prevState => ({
isActive: !prevState.isActive
}));
}
render() {
const { isActive } = this.state;
return (
<div className={isActive ? 'active' : 'inactive'}>
<button onClick={this.handleClick}>Toggle</button>
</div>
);
}
}
import classNames from 'classnames';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isActive: false
};
}
handleClick = () => {
this.setState(prevState => ({
isActive: !prevState.isActive
}));
}
render() {
const { isActive } = this.state;
const className = classNames({
active: isActive,
inactive: !isActive
});
return (
<div className={className}>
<button onClick={this.handleClick}>Toggle</button>
</div>
);
}
}
以上是在React中动态更改组件的className的几种常见方法。根据具体的需求和项目情况,选择适合的方式来实现动态className的变化。
领取专属 10元无门槛券
手把手带您无忧上云