预期的 Checkbox 使用方法
1 | import Checkbox from '@/components' |
两种实现方式
通过 React.cloneElement
1 | React.cloneElement( |

Checkbox
1 | // Checkbox |
CheckboxItem
1 | // CheckboxItem |
使用 Checkbox
1 | import * as React from "react"; |
通过 React.createContext
1 | const MyContext = React.createContext(defaultValue); |

CheckBox
1 | import React, { createContext } from "react"; |
CheckboxItem
1 | import React, { useContext } from "react"; |
总结
使用 React.createContext
的实现方式, 可以支持嵌套的组件结构, 非常灵活。
通过 React.cloneElement
的实现方式不支持组件嵌套的结构, 可以考虑使用 children
的方式, 使组件更灵活;1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32// CheckboxItem
import React from "react";
import { uid } from "../../utils";
export interface CheckboxItemProps {
onChange?: (checked: boolean, val: unknown) => void;
block?: boolean;
label?: string;
children? React.ReactNode
}
const CheckboxItem = (props: CheckboxItemProps) => {
const { onChange, block = false, label, children, ...rest } = props;
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (onChange) {
onChange(e.currentTarget.checked, label);
}
};
const uuid = uid();
const item = (
<>
<input {...rest} type="checkbox" onChange={handleChange} id={`${uuid}`} />
{label && <label htmlFor={`${uuid}`}>{children || label}</label>}
</>
);
if (block) {
return <div>{item}</div>;
}
return item;
};
export default CheckboxItem;
一个人活在世上就是为了忍受一切摧残,想通了这点,任何事情都能泰然处之。 ——王小波