使用方式
tagRef.current.value 拿到select数据,maxInputSize输入最大tag数量文章来源:https://www.toymoban.com/news/detail-532298.html
<TagSelect ref={tagRef} maxInputSize={10} />
组件文章来源地址https://www.toymoban.com/news/detail-532298.html
import React, {
useImperativeHandle,
useMemo,
useState,
forwardRef,
ForwardRefRenderFunction,
useEffect,
} from 'react';
import { Select, message } from 'antd';
import { PropsType } from './interface';
const TagSelect: React.FC = (props: PropsType) => {
const {
/**
* 输入个数限制
*/
maxInputSize = 0,
/**
* 透传ref
*/
TagSelectRef,
/**
* antd Select component props
*/
...ohterProps
} = props;
const { defaultValue } = ohterProps;
const [value, setValue] = useState<any[]>([]);
useImperativeHandle(
TagSelectRef,
() => ({
value,
}),
[value],
);
useEffect(() => {
if (defaultValue?.length) {
let limit = defaultValue;
if (defaultValue?.length > maxInputSize) {
limit = defaultValue.slice(0, maxInputSize);
}
setValue(limit);
}
}, [defaultValue]);
/**
* 展示-输入tags个数
*/
const showMaxInputSize = useMemo(() => {
return (
<div>
{value?.length ?? 0}/{maxInputSize}
</div>
);
}, [value, maxInputSize]);
const selectProps: any = {
style: {
width: '100%',
},
mode: 'tags',
placeholder: '请输入',
allowClear: true,
maxTagCount: 5, // 展示5个标签,大于5个展示省略标签
open: false, // 是否展开下拉菜单
showArrow: true,
suffixIcon: showMaxInputSize,
tokenSeparators: [',', ','],
value,
options: [],
/* ------------------ event ----------------------- */
onChange: (value: any[]) => {
console.log(value, 'value');
let limit = value;
if (value.length > maxInputSize) {
limit = value.slice(0, maxInputSize);
message.info(`超出输入上限,最多可输入${maxInputSize}个值!`);
}
setValue(limit);
},
};
return <Select {...selectProps} {...ohterProps} />;
};
TagSelect.defaultProps = {
maxInputSize: 100,
};
const _TagSelect: ForwardRefRenderFunction<unknown, any> = (props, ref) => {
return <TagSelect {...props} TagSelectRef={ref} />;
};
export default forwardRef(_TagSelect);
到了这里,关于封装Select组件自定义输入个数的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!