选择的Antd自定义选项组件



是否可以在antd-select中呈现自定义选项?

以下是我的想法。我希望复选框与选项一起呈现。

但是,我得到了默认选项。

以下是我的"CustomSelect"one_answers"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>
);
};

你可以看看这个沙箱,看看这个代码的实时工作示例。

最新更新