//checkbox格式
//数据
const options = [
{ label: 'Apple', value: 'Apple' },
{ label: 'Pear', value: 'Pear' },
{ label: 'Orange', value: 'Orange' },
];
// 事件
const onChange = (checkedValues: CheckboxValueType[]) => {
console.log('checked = ', checkedValues);
};
<div>
<Checkbox.Group
options={options}
defaultValue={['Apple']}
onChange={onChange}
/>
</div>
按钮形式
const options2 = ['Apple', 'Banana', 'Orange']; // 选项数组
const [checkedList, setCheckedList] = useState(['Apple']); // 默认选中项
const onChange2 = (checkedValues) => {
console.log('checked2 = ', checkedValues);
setCheckedList(checkedValues);
};
// 生成按钮组件
const renderButton = (option) => {
const isChecked = checkedList.includes(option);
return (
<Button
key={option}
type={isChecked ? 'primary' : 'default'}
onClick={() => onChange2(
isChecked
? checkedList.filter((item) => item !== option)
: [...checkedList, option]
)}
>
{option}
</Button>
);
};
<div>
{/* 遍历选项数组,展示按钮 */}
{options2.map((option) => renderButton(option))}
{/* 显示选中的项 */}
<div>Checked options2: {checkedList.join(', ')}</div>
</div>
按钮格式也改成数组对象形式
//初始化数据
//所有数据
const options3 = [
{ label: 'Apple', value: 'Apple' },
{ label: 'Pear', value: 'Pear' },
{ label: 'Orange', value: 'Orange' },
];
const [checkedList, setCheckedList] = useState([{ label: 'Apple', value: 'Apple' },]); // 默认选中项
//函数
const onChange3 = (checkedValues) => {
console.log('checked3 = ', checkedValues);
setCheckedList(checkedValues);
};
// 生成按钮组件
const renderButton = (option) => {
const isChecked = checkedList.some(item => item.value === option.value);
return (
<Button
key={option.value}
type={isChecked ? 'primary' : 'default'}
onClick={() => onChange3(
isChecked
? checkedList.filter((item) => item.value !== option.value)
: [...checkedList, option]
)}
>
{option.label}
</Button>
);
};
//页面渲染
<div>
{options3.map((option) => renderButton(option))}
</div>
按钮。如果是传递key格式的修改
const options4 = [
{ val: 'ceshi1', key: '1' },
{ val: 'ceshi2', key: '2' },
{ val: 'ceshi3', key: '3' },
];
const [checkedList, setCheckedList] = useState(['1','2']); // 默认选中项
const onChange4 = (checkedValues) => {
console.log('checked2 = ', checkedValues);
setCheckedList(checkedValues);
};
// 生成按钮组件
const renderButton = (option) => {
const isChecked = checkedList.some((item) => item === option.key);
return (
<Button
key={option.key}
type={isChecked ? 'primary' : 'default'}
onClick={() => onChange4(
isChecked
? checkedList.filter((item) => item !== option.key)
: [...checkedList, option.key]
)}
>
{option.val}
</Button>
);
};
{options4.map((option) => renderButton(option))}