1 | import { useObserver } from "./useObserver"
|
2 |
|
3 |
|
4 |
|
5 | interface IObserverProps {
|
6 | children?(): React.ReactElement | null
|
7 | render?(): React.ReactElement | null
|
8 | }
|
9 |
|
10 | function ObserverComponent({ children, render }: IObserverProps) {
|
11 | if (children && render) {
|
12 | console.error(
|
13 | "MobX Observer: Do not use children and render in the same time in `Observer`"
|
14 | )
|
15 | }
|
16 | const component = children || render
|
17 | if (typeof component !== "function") {
|
18 | return null
|
19 | }
|
20 | return useObserver(component)
|
21 | }
|
22 | if ("production" !== process.env.NODE_ENV) {
|
23 | ObserverComponent.propTypes = {
|
24 | children: ObserverPropsCheck,
|
25 | render: ObserverPropsCheck
|
26 | }
|
27 | }
|
28 | ObserverComponent.displayName = "Observer"
|
29 |
|
30 | export { ObserverComponent as Observer }
|
31 |
|
32 | function ObserverPropsCheck(
|
33 | props: { [k: string]: any },
|
34 | key: string,
|
35 | componentName: string,
|
36 | location: any,
|
37 | propFullName: string
|
38 | ) {
|
39 | const extraKey = key === "children" ? "render" : "children"
|
40 | const hasProp = typeof props[key] === "function"
|
41 | const hasExtraProp = typeof props[extraKey] === "function"
|
42 | if (hasProp && hasExtraProp) {
|
43 | return new Error(
|
44 | "MobX Observer: Do not use children and render in the same time in`" + componentName
|
45 | )
|
46 | }
|
47 |
|
48 | if (hasProp || hasExtraProp) {
|
49 | return null
|
50 | }
|
51 | return new Error(
|
52 | "Invalid prop `" +
|
53 | propFullName +
|
54 | "` of type `" +
|
55 | typeof props[key] +
|
56 | "` supplied to" +
|
57 | " `" +
|
58 | componentName +
|
59 | "`, expected `function`."
|
60 | )
|
61 | }
|