fix: 优化按钮排序传参

This commit is contained in:
苑宏博 2024-04-22 12:12:17 +08:00
parent a3aefaf499
commit e4a73f5ec1
2 changed files with 12 additions and 15 deletions

View File

@ -10,7 +10,7 @@ export interface IButtonItem {
onClick: () => void; onClick: () => void;
children?: Array<Omit<IButtonItem, 'weight'>>; children?: Array<Omit<IButtonItem, 'weight'>>;
// 用于排序 // 用于排序
weight: number; weight?: number;
icon?: ReactNode icon?: ReactNode
className?: string; className?: string;
isCenter?: boolean; isCenter?: boolean;
@ -30,12 +30,16 @@ const ButtonList: React.FC<ButtonListProps> = (Props) => {
const [buttonListWrapMarginLeft, setButtonListWrapMarginLeft] = useState(0) const [buttonListWrapMarginLeft, setButtonListWrapMarginLeft] = useState(0)
const centerButtonRef = useRef<HTMLDivElement>(null); const centerButtonRef = useRef<HTMLDivElement>(null);
const sortedButtons = useMemo(() => { const sortedButtons = useMemo(() => {
let buttonList = [...buttons] let buttonList = buttons.map((btn, index) => {
if (btn.weight === undefined) {
return { ...btn, weight: index }
return buttonList?.sort((a, b) => a.weight - b.weight); } else {
return { ...btn, weight: btn.weight }
}
})
const newButtonList = buttonList?.sort((a, b) => a.weight - b.weight)
return newButtonList;
}, [buttons]); }, [buttons]);
const handleButtonClick = (key: string, item: IButtonItem) => { const handleButtonClick = (key: string, item: IButtonItem) => {

View File

@ -19,34 +19,28 @@ export default () => {
{ key: 'subButton1-1', text: '二级按钮1-1', onClick: () => console.log('二级按钮1-1被点击'), icon: <DownloadOutlined /> }, { key: 'subButton1-1', text: '二级按钮1-1', onClick: () => console.log('二级按钮1-1被点击'), icon: <DownloadOutlined /> },
{ key: 'subButton1-2', text: '二级按钮1-2', onClick: () => console.log('二级按钮1-2被点击') }, { key: 'subButton1-2', text: '二级按钮1-2', onClick: () => console.log('二级按钮1-2被点击') },
], ],
weight: 1,
// icon:<DownloadOutlined />, // icon:<DownloadOutlined />,
}, },
{ {
key: 'button2', key: 'button2',
text: '一级按钮2', text: '一级按钮2',
onClick: () => console.log('一级按钮2被点击'), onClick: () => console.log('一级按钮2被点击'),
weight: 2,
}, },
{ {
key: '播放', key: '播放',
text: isPlay ? '播放按钮' : '图片按钮', text: isPlay ? '播放按钮' : '图片按钮',
onClick: () => { setIsPlay(!isPlay) }, onClick: () => { setIsPlay(!isPlay) },
weight: 3, // isCenter: true
isCenter: true
}, },
{ {
key: 'button3', key: 'button3',
text: '一级按钮3', text: '一级按钮3',
onClick: () => console.log('一级按钮3被点击'), onClick: () => console.log('一级按钮3被点击'),
weight: 3,
}, },
{ {
key: 'button4', key: 'button4',
text: '一级按钮4', text: '一级按钮4',
onClick: () => console.log('一级按钮4被点击'), onClick: () => console.log('一级按钮4被点击'),
weight: 4,
// isCenter: true
}, },
{ {
@ -56,7 +50,6 @@ export default () => {
children: [ children: [
{ key: 'subButton5-1', text: '二级按钮5-1', onClick: () => console.log('二级按钮5-1被点击') }, { key: 'subButton5-1', text: '二级按钮5-1', onClick: () => console.log('二级按钮5-1被点击') },
], ],
weight: 5,
}, },
], ],
} }