我在 React 应用程序中使用自定义 Select 组件,其中包括 SelectValue 和 SelectItem 组件。我想在选择 SelectItem 时将 SelectValue 组件的字体粗细更改为粗体。
例如,用户点击下拉列表中的“TO:”选项,则SelectValue组件的占位符从“Select”变为“TO:”;在这种情况下,我需要将占位符的字体从正常更改为粗体。
这是我的代码的简化版本:
import { useState, useEffect } from 'react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "src/components/ui/select";
export const LinkCard: React.FC = () => {
const [isSelected, setIsSelected] = useState(false);
useEffect(() => {
console.log('isSelected:', isSelected);
}, [isSelected]);
return (
<Select>
<SelectTrigger>
<SelectValue key={isSelected.toString()} placeholder="Select" style={{ fontWeight: isSelected ? 'bold' : 'normal' }}/>
</SelectTrigger>
<SelectContent position="popper">
<SelectItem value="filterTo" style={{ fontWeight: 'bold' }} onClick={() => { console.log('SelectItem clicked'); setIsSelected(true); }}>TO:</SelectItem>
{/* other SelectItem components */}
</SelectContent>
</Select>
);
};
我正在使用 useState 挂钩来跟踪是否已选择 SelectItem,并且我正在尝试使用此状态来更改 SelectValue 组件的字体粗细。但是,SelectItem 组件上的 onClick 处理程序不会被触发,因此 isSelected 状态不会被更新。
我尝试将 onClick 和 onChange 处理程序添加到 Select 组件,但收到 TypeScript 错误,指出 Select 组件上不存在这些属性。
这个问题不完整。我们需要知道您使用什么来进行造型,以便为您提供更多指导。
如果你使用CSS,你可以看看焦点伪类。当用户单击或点击某个元素或使用键盘的 Tab 键选择它时,通常会触发它。 :聚焦
label {
display: block;
margin-top: 1em;
}
input:focus {
background-color: lightblue;
}
select:focus {
background-color: ivory;
}
<form>
<p>Which flavor would you like to order?</p>
<label>Full Name: <input name="firstName" type="text" /></label>
<label
>Flavor:
<select name="flavor">
<option>Cherry</option>
<option>Green Tea</option>
<option>Moose Tracks</option>
<option>Mint Chip</option>
</select>
</label>
</form>