-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.tsx
47 lines (44 loc) · 1.27 KB
/
index.tsx
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import * as React from "react"
export default
class FindElement<TProps, TState> extends React.Component<TProps, TState> {
element: Element|undefined
mapElement(elem: React.ReactChild): React.ReactChild {
if (typeof elem == "object") {
if (typeof elem.type == "string") {
const origRef = (elem as any).ref
return React.cloneElement(elem, {
ref: (elem: Element) => {
if (origRef) {
origRef(elem)
}
this.element = elem
}
})
} else {
const {children} = elem.props
const childCount = React.Children.count(children)
if (childCount == 0) {
return elem
}
if (childCount == 1) {
const child = React.Children.toArray(children)[0]
return React.cloneElement(elem, {
children: this.mapElement(child)
})
}
return React.cloneElement(elem, {
children: React.Children.map(children, this.mapElement.bind(this))
})
}
}
return elem
}
render() {
const child = this.mapElement(React.Children.only(this.props.children))
if (typeof child == "object") {
return child
} else {
throw new Error("Child must not be string nor number")
}
}
}