-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
118 lines (110 loc) · 3.13 KB
/
index.ts
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import React from "react";
interface NodeJson {
type: string | Function;
key?: string | number | null;
ref?: any;
props: {
className: string;
style?: any;
children: Array<NodeJson | string>;
};
}
export function CreateJSON(obj: NodeJson | Array<NodeJson>): NodeJson {
let newNode: NodeJson = {
type: '',
props: {
className: '',
style: {},
children: []
}
}
function recurse(obj: NodeJson | Array<NodeJson>, newNode: NodeJson) {
if (Array.isArray(obj)) {
obj.forEach(item => recurse(item, newNode))
} else {
if (obj.hasOwnProperty("type")) {
newNode.type = obj.type;
}
if (obj.hasOwnProperty("key")) {
newNode.key = obj.key;
}
if (obj.hasOwnProperty("ref")) {
newNode.ref = obj.ref;
}
if (obj.hasOwnProperty("props")) {
if (obj.props.hasOwnProperty("className")) {
newNode.props.className = obj.props.className;
}
if (obj.props.hasOwnProperty("style")) {
newNode.props.style = obj.props.style;
}
if (obj.props.hasOwnProperty("children")) {
if (Array.isArray(obj.props.children)) {
obj.props.children.forEach((child: NodeJson | string) => {
if (typeof child === 'string') {
newNode.props.children.push(child);
} else {
let newChild = {
type: '',
key: '',
ref: '',
props: {
className: '',
style: {},
children: []
}
}
recurse(child, newChild);
newNode.props.children.push(newChild);
}
});
} else if (typeof obj.props.children === 'string') {
newNode.props.children.push(obj.props.children);
} else {
let newChild = {
type: '',
key: '',
ref: '',
props: {
className: '',
style: {},
children: []
}
}
recurse(obj.props.children, newChild);
newNode.props.children.push(newChild);
}
}
}
}
}
recurse(obj, newNode);
return newNode;
}
export function CreateJsx(el:any){
type JsonType = {
type?: string;
key: any;
ref: any;
props: {
children?: JsonType[] | string[];
};
};
function createReactElementFromJson(json: JsonType): React.ReactNode {
const { type, props, key, ref, } = json;
const { children, ...rest } = props;
const childElements = (children || []).map(child => {
if (typeof child === "string") {
return child;
} else {
return createReactElementFromJson(child);
}
});
return React.createElement(
type!,
{ key, ref, ...rest },
...childElements
);
}
return createReactElementFromJson(el);
}