1 |
|
2 | import * as React from 'react';
|
3 | export default function useControlled({
|
4 | controlled,
|
5 | default: defaultProp,
|
6 | name,
|
7 | state = 'value'
|
8 | }) {
|
9 | const {
|
10 | current: isControlled
|
11 | } = React.useRef(controlled !== undefined);
|
12 | const [valueState, setValue] = React.useState(defaultProp);
|
13 | const value = isControlled ? controlled : valueState;
|
14 |
|
15 | if (process.env.NODE_ENV !== 'production') {
|
16 | React.useEffect(() => {
|
17 | if (isControlled !== (controlled !== undefined)) {
|
18 | console.error([`Material-UI: A component is changing the ${isControlled ? '' : 'un'}controlled ${state} state of ${name} to be ${isControlled ? 'un' : ''}controlled.`, 'Elements should not switch from uncontrolled to controlled (or vice versa).', `Decide between using a controlled or uncontrolled ${name} ` + 'element for the lifetime of the component.', "The nature of the state is determined during the first render, it's considered controlled if the value is not `undefined`.", 'More info: https://fb.me/react-controlled-components'].join('\n'));
|
19 | }
|
20 | }, [controlled]);
|
21 | const {
|
22 | current: defaultValue
|
23 | } = React.useRef(defaultProp);
|
24 | React.useEffect(() => {
|
25 | if (!isControlled && defaultValue !== defaultProp) {
|
26 | console.error([`Material-UI: A component is changing the default ${state} state of an uncontrolled ${name} after being initialized. ` + `To suppress this warning opt to use a controlled ${name}.`].join('\n'));
|
27 | }
|
28 | }, [JSON.stringify(defaultProp)]);
|
29 | }
|
30 |
|
31 | const setValueIfUncontrolled = React.useCallback(newValue => {
|
32 | if (!isControlled) {
|
33 | setValue(newValue);
|
34 | }
|
35 | }, []);
|
36 | return [value, setValueIfUncontrolled];
|
37 | } |
\ | No newline at end of file |