[英]Antd Custom Option Component for Select
是否可以在 antd select 中呈現自定義選項?
這就是我想出的。 我希望復選框與選項一起呈現。
但是,我得到默認選項。
這是我的“CustomSelect”和“CustomOption”組件。
// CustomSelect.tsx
import React from "react";
import { Select as AntSelect } from "antd";
import { CustomSelectStyle, Wrapper } from "./styles";
import { ReactComponent as ChevronDown } from "@assets/images/chevron-down.svg";
import { NewSelectProps } from "./types";
import { SelectValue } from "antd/lib/select";
import CustomOption from "./CustomOption";
function CustomSelect<T extends SelectValue>({
width = "normal",
mode,
error = false,
children,
...props
}: NewSelectProps<T>) {
return (
<Wrapper width={width}>
<CustomSelectStyle onError={error} />
<AntSelect optionLabelProp="label" mode={mode} {...props}>
{children}
</AntSelect>
<ChevronDown className="dropdown-icon" />
</Wrapper>
);
}
CustomSelect.Option = CustomOption;
export default CustomSelect;
// CustomOption.tsx
import { Select as AntdSelect, Checkbox } from "antd";
import { OptionProps } from "antd/lib/select";
const { Option } = AntdSelect;
interface CustomOptionProps extends OptionProps {
type: "checkbox" | "default";
}
function CustomOption({ type, children, ...props }: CustomOptionProps) {
return (
<Option {...props}>
{type === "checkbox" && <Checkbox />}
{children}
</Option>
);
}
export default CustomOption;
我知道我可以做到這一點...
<CustomSelect
onChange={value => console.log(value)}
error={false}
mode="multiple"
>
<CustomSelect.Option value={"korea"}>
<TextWithCheckbox checked={false}>
korea
</TextWithCheckbox>
</CustomSelect.Option>
<CustomSelect.Option value={"china"}>
<TextWithCheckbox checked={false}>
china
</TextWithCheckbox>
</CustomSelect.Option>
</CustomSelect>
但我想要的是制作一個新的選項組件。
您不需要自定義CustomOption
組件。 您可以在TextWithCheckbox
組件中處理自定義選項渲染器,例如:
const TextWithCheckbox = (props) => {
return (
<div>
<Checkbox checked={props.checked} />
{props.children}
</div>
);
};
您可以查看此沙箱以獲取此代碼的實時工作示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.