react hooks 如何写一个 颜色和尺码同时选择同时高亮状态
时间: 2024-03-22 19:37:56 浏览: 192
可以使用 useState 来存储当前选择的颜色和尺码,然后在渲染时根据当前选择状态来添加高亮样式。
具体代码如下:
```javascript
import React, { useState } from 'react';
function ColorAndSizeSelector() {
const [selectedColor, setSelectedColor] = useState(null);
const [selectedSize, setSelectedSize] = useState(null);
const handleColorSelect = (color) => {
setSelectedColor(color);
}
const handleSizeSelect = (size) => {
setSelectedSize(size);
}
return (
<div>
<h2>Select Color:</h2>
<button onClick={() => handleColorSelect('red')} className={selectedColor === 'red' ? 'selected' : ''}>Red</button>
<button onClick={() => handleColorSelect('green')} className={selectedColor === 'green' ? 'selected' : ''}>Green</button>
<button onClick={() => handleColorSelect('blue')} className={selectedColor === 'blue' ? 'selected' : ''}>Blue</button>
<h2>Select Size:</h2>
<button onClick={() => handleSizeSelect('small')} className={selectedSize === 'small' ? 'selected' : ''}>Small</button>
<button onClick={() => handleSizeSelect('medium')} className={selectedSize === 'medium' ? 'selected' : ''}>Medium</button>
<button onClick={() => handleSizeSelect('large')} className={selectedSize === 'large' ? 'selected' : ''}>Large</button>
</div>
);
}
export default ColorAndSizeSelector;
```
在上述代码中,我们使用了 useState 来分别存储当前选择的颜色和尺码状态。handleColorSelect 和 handleSizeSelect 两个函数分别用来更新对应的状态。
在渲染时,我们通过判断当前选择状态来添加 selected 类名,从而实现高亮效果。
阅读全文