样式控制 & classnames工具优化类名控制
样式控制
1. 行内样式控制
const style = {color: 'red',fontSize: '30px'
}function App() {return (<div className="App">{}<p style={style}>Hello BLU!</p></div>);
}
export default App;
2. 外部样式控制
import './index.css';function App() {const clickHandler = (name) => {alert("Hello " + name);}return (<div className="App">{}<button className='bluBtn' onClick={() => clickHandler('BLU')}>Click Me</button></div>);
}
export default App;
.bluBtn {color: red;font-size: 20px;font-weight: 600;
}
classnames工具优化类名控制
npm install classnames
import './index.css';
import classNames from 'classnames';
import { useState } from 'react';function Tab() {const [type, setType] = useState('');const handleTabClick = (name) => {setType(name);}return (<div><button className={classNames('bluBtn', {active: type === 'A'})} onClick={() => handleTabClick('A')}>Tab A</button><button className={classNames('bluBtn', {active: type === 'B'})} onClick={() => handleTabClick('B')}>Tab B</button></div>);}
export default Tab;
.bluBtn {color: red;font-size: 20px;font-weight: 600;
}
.bluBtn.active {background-color: bisque;
}
import Tab from "./Tab";function App() {return (<div className="App"><Tab></Tab> </div>);
}
export default App;