样式控制 & classnames工具优化类名控制
样式控制
1. 行内样式控制
js
复制代码
//定义样式
const style = {
color: 'red',
fontSize: '30px'
}
function App() {
return (
<div className="App">
{/* 行内样式控制 */}
<p style={style}>Hello BLU!</p>
</div>
);
}
export default App;
2. 外部样式控制
js
复制代码
//导入外部样式
import './index.css';
function App() {
const clickHandler = (name) => {
alert("Hello " + name);
}
return (
<div className="App">
{/* class类名样式控制 */}
<button className='bluBtn' onClick={() => clickHandler('BLU')}>Click Me</button>
</div>
);
}
export default App;
css
复制代码
.bluBtn {
color: red;
font-size: 20px;
font-weight: 600;
}
classnames工具优化类名控制
bash
复制代码
npm install classnames
js
复制代码
//导入外部样式
import './index.css';
//引入依赖
import classNames from 'classnames';
//引入useState
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;
css
复制代码
.bluBtn {
color: red;
font-size: 20px;
font-weight: 600;
}
.bluBtn.active {
background-color: bisque;
}
js
复制代码
import Tab from "./Tab";
function App() {
return (
<div className="App">
<Tab></Tab>
</div>
);
}
export default App;