[英]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.