Исходный код вики Динамический рендер компонентов
Редактировал(а) Alexandr Fokin 2023/12/29 14:48
Последние авторы
author | version | line-number | content |
---|---|---|---|
1 | |(% style="width:84px" %) |(% style="width:1353px" %)React + [[TypeScript>>doc:Разработка.Frontend.Промежуточные языки.TypeScript.WebHome]] | ||
2 | |(% style="width:84px" %) |(% style="width:1353px" %){{code language="html"}}import { useState, createElement, ElementType } from 'react' | ||
3 | |||
4 | interface componentProp { | ||
5 | selectedComponent: string, | ||
6 | prop1: number, | ||
7 | onClick: (state: componentProp) => void | ||
8 | }; | ||
9 | |||
10 | function Component1(prop: componentProp) { | ||
11 | return ( | ||
12 | <div> | ||
13 | <p>component1 {prop.prop1}</p> | ||
14 | <button | ||
15 | onClick={() => { prop.onClick({ ...prop, prop1: prop.prop1 + 1 }) }} | ||
16 | > | ||
17 | Increment | ||
18 | </button> | ||
19 | <button | ||
20 | onClick={() => { prop.onClick({ ...prop, selectedComponent: "c2" }) }} | ||
21 | > | ||
22 | To component2 | ||
23 | </button> | ||
24 | <button | ||
25 | onClick={() => { prop.onClick({ ...prop, selectedComponent: "unknow name" }) }} | ||
26 | > | ||
27 | Bad component | ||
28 | </button> | ||
29 | </div> | ||
30 | ) | ||
31 | } | ||
32 | function Component2(prop: componentProp) { | ||
33 | return ( | ||
34 | <div> | ||
35 | <p>component2 {prop.prop1}</p> | ||
36 | <button | ||
37 | onClick={() => { prop.onClick({ ...prop, prop1: prop.prop1 + 1 }) }} | ||
38 | > | ||
39 | Increment | ||
40 | </button> | ||
41 | <button | ||
42 | onClick={() => { prop.onClick({ ...prop, selectedComponent: "c1" }) }} | ||
43 | > | ||
44 | To component1 | ||
45 | </button> | ||
46 | </div> | ||
47 | ) | ||
48 | } | ||
49 | |||
50 | const mapping = new Map<string, ElementType>() | ||
51 | .set("c1", Component1) | ||
52 | .set("c2", Component2); | ||
53 | |||
54 | function App() { | ||
55 | |||
56 | const [state, setState] = useState<componentProp>( | ||
57 | { | ||
58 | selectedComponent: "c1", | ||
59 | prop1: 10, | ||
60 | onClick: (q) => { | ||
61 | setState(q) | ||
62 | } | ||
63 | }); | ||
64 | |||
65 | const selectedComponent = mapping.get(state.selectedComponent); | ||
66 | |||
67 | if (selectedComponent === undefined) { | ||
68 | return (<> | ||
69 | <div>Not defined "{state.selectedComponent}"</div> | ||
70 | </>); | ||
71 | } | ||
72 | |||
73 | return ( | ||
74 | <> | ||
75 | <div> | ||
76 | {createElement(selectedComponent, state) } | ||
77 | </div> | ||
78 | </> | ||
79 | ) | ||
80 | } | ||
81 | |||
82 | export default App{{/code}} | ||
83 | |(% style="width:84px" %) |(% style="width:1353px" %) |