前一段时间写页面,有一个下拉框功能需要封装一个组件, 封装的组件给大哥气不行, 封装的稀碎.大哥忍无可忍.
新组件代码:
// 下拉框组件
interface DropdownMenuProps{
className?: string;
height?: string;
value?: string;
options: Array<{value:string;label:string}>;
onChange?:(value: string)
children: React.ReactNode;
}
export default function DropdownMenu(fvalue,options,onChange,children,className}:DropdownMenuProps){
return (
<div class="pos-r"> //pos-r:定位
{children}
<div class="pos-a">
{options.map(item=>(
<div onClick={()=>onChange(item.value)}>{item.label}</div>
))}
</div>
</div>
)
}
// 使用组件
let [selectIpt, setSelectIpt] = useState('');
let list = [
{value:'11',label:'11'},
{value:'22',label:'22'},
]
<div>
<DropdownMenu options={list} onChange={(e)=>setSelectIpt(e)}>
<div>{selectIpt}</div>
</DropdownMenu>
</div>
旧版代码:
// 父组件
<div className="flex-1 pos-r d-flex-r ai-center" onClick={() => setTimeSelectDialogShow(!timeSelectDialogShow)}>
<div className="flex-1 text-center">{timeSelect}</div>
<img className="icon-24" src="/pic/icon_select_down.png" alt="" />
{timeSelectDialogShow && (
<SelectDialog activeItem={timeSelect} list={timerList} onCancel={(v) => setTimeSelect(v)} />
)}
</div>
// 子组件
interface props {
list: string[];
activeItem?: string;
onCancel: (v: string) => void;
}
export default function SelectDialogPage({ list, activeItem, onCancel }: props) {
return (
<div className="select-dialog bw-100 pos-a d-shadow pt-10 pl-10 pr-20 border- radius-4">
{list.map((item, idx) => (
<div key={idx} className="mb-10 d-flex-r ai-center" onClick={() => onCancel(item)}>
<img className={`icon-20 ${activeItem !== item && 'view-opacity-0'}`} src="/pic/icon_ok.png" alt="" />
<span className={`ml-5 ${activeItem === item && 'text-color-p'}`}>{item}</span>
</div>
))}
</div>
);
}
明白一个道理,如果要封装组件的话,就尽量都弄进组件中,否则将会代码显的特别乱,到后期可能会不好维护.