Форум программистов, компьютерный форум, киберфорум
JavaScript: Фреймворки
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/5: Рейтинг темы: голосов - 5, средняя оценка - 5.00
 Аватар для radiofan
3 / 2 / 1
Регистрация: 18.04.2018
Сообщений: 51

Preact. Попытка сделать комплексный компонент. Передача и управление глобальным состоянием этого компонента

07.02.2024, 11:50. Показов 1268. Ответов 1

Студворк — интернет-сервис помощи студентам
Здравствуйте. Решил попробовать разобраться в реактивном фреймворке. Выбор пал Preact за его объем и не требовательность к сборке. Пытаюсь реализовать комплексный компонент. С версткой вроде разобрался, но вот как правильно управлять этим делом до конца разобраться не могу. Имеется объект с данными на основе которого строится дерево компонентов:

JSON
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
{
    "chapters":{
        "1":{
            "title":"Глава 1",
            "posts":[
                Post1,
                Post2,
                ...
            ]
        },
        ...,
        "-1":{
            "title":"Посты без главы",
            "posts":[
                PostN,
                ...
            ]
        }
    },
    "posts_without_section":[
        PostM,
        PostM+1,
        ...
    ],
    "order_change_action":"/api/section/2/posts/"
}
Post -
JSON
1
2
3
4
5
6
7
8
9
10
{
    "id":"3",
    "order":"0",
    "alias":"dsdsdds",
    "author_id":"1",
    "author_name":"RADIOFAN",
    "visible_translates_c":"0",
    "hidden_translates_c":"0",
    "edit_href":"/admin/posts/3/"
}
Задача компонента предоставлять интерфейс для создания/удаления глав, редактирования их заголовка, а также сортировки постов и возможности их перетаскивания из групп в группы.

Ниже представлен код компонентов:

JavaScript
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import {h, render, Component, Fragment, toChildArray} from '/libs/preact.min.js';
 
class Post extends Component{
    
    constructor(){
        super();
        
        this.remove_post = this.remove_post.bind(this);
    }
 
    remove_post(e){
        this.props.actions.remove_post(this.props.chapter_id, this.props.index, this.props.id);
    }
    
    /**
     * @param {object} props {
     *  id: int,
     *  order: int,
     *  alias: string,
     *  author_id: int,
     *  author_name: string,
     *  hidden_translates_c: int,
     *  visible_translates_c: int,
     *  edit_href: string,
     *  
     *  chapter_id: int,
     *  is_sortable: bool,
     *  is_addable: bool,
     *  index: int,
     *  actions: {function, function ...}
     * }
     */
    render(props){
        //console.log(props);
        return h('div', {
            'class':'sort-box__item chapter__post',
            'tabindex':'0',
            'title': 'Создатель '+props.author_name+' #'+props.author_id,
            'data-id':props.id,
        }, [
            h('input', {
                'type':'hidden',
                'name':'chapter_post['+props.chapter_id+'][]',
                'value':props.id
            }),
            h('div', {'class':'chapter__post__left'}, [
                h('span', null, '#'+props.id),
                h('a', {
                    'class':'link',
                    'title':'/'+props.alias+'/',
                    'href':props.edit_href,
                    'target':'_blank'
                }, '/'+props.alias+'/'),
            ]),
            h('div', {'class':'chapter__post__right'}, [
                h('span', {'class':'chapter__post__public', 'title':'Количество публичных переводов'}, props.visible_translates_c),
                h('span', {'class':'chapter__post__private', 'title':'Количество приватных переводов'}, props.hidden_translates_c),
                (props.is_sortable ?
                    h('input', {
                        'class':'chapter__post__order',
                        'type':'number',
                        'name':'post_order['+props.id+']',
                        'value':props.order,
                        'step':'1',
                        'min':'0',
                    }) :
                    null
                ),
                (props.is_addable ?
                    h('button', {
                        'type': 'button',
                        'title': 'Добавить пост в раздел',
                        'class': 'chapter__add',
                    }, '✚') :
                    h('button', {
                        'type': 'button',
                        'title': 'Открепить пост от раздела',
                        'class': 'chapter__delete',
                        'onClick': this.remove_post
                    }, '✗')
                )
            ]),
        ]);
    }
}
 
class SortBoxElement extends Component{
    render(props){
        return h('div', {'class':'sort-box__element'+(!toChildArray(props.children).length ? ' empty' : '')}, [
            props.children,
            h('div', {'class':'sort-box__place', 'tabindex':'0'}, 'Поместить сюда')
        ]);
    }
}
 
class Chapter extends Component{
 
    constructor(){
        super();
 
        this.input_chapter_title = this.input_chapter_title.bind(this);
        this.delete_chapter = this.delete_chapter.bind(this);
    }
 
    input_chapter_title(e){
        this.props.actions.input_chapter_title(this.props.id, e.target.value);
    }
 
    delete_chapter(e){
        this.props.actions.delete_chapter(this.props.id);
    }
 
    /**
     * @param {object} props {
     *  id: int,
     *  posts: [],
     *  title: string,
     *  actions: {function, function},
     * }
     */
    render(props){
        return h('div', {'class':'chapter__block color-back', 'data-id':props.id}, [
            h('div', {
                'class':'chapter__header expand chapter__expander',
                'tabindex':'0',
                'data-js':'expand',
                'data-expand':'#'+$.escapeSelector('chapter__container-'+props.id),
            }, props.id == -1 ?
                h('span', null, ['Посты без глав ', h('sub', null, '(скрыты, если хотя бы одна глава существует)')]) :
                [
                    h('span', null, '#'+props.id),
                    h('input', {
                        'type': 'text',
                        'autocomplete':'off',
                        'placeholder': 'Наименование главы',
                        'value': props.title,
                        'name': 'chapter['+props.id+']',
                        'onInput': this.input_chapter_title
                    }, null),
                    h('button', {
                        'type': 'button',
                        'title': 'Удалить главу',
                        'class': 'chapter__delete',
                        'onClick': this.delete_chapter
                    }, '✗')
                ]
            ),
            h('div', {'class':'chapter__container','id':'chapter__container-'+props.id},
                h(SortBoxElement, {key:-1}),
                props.posts.map((post, index) =>
                    h(SortBoxElement, {key:post.id}, h(Post, {
                        key: post.id,
                        actions: props.actions,
                        index: index,
                        chapter_id: props.id,
                        is_sortable: true,
                        ...post
                    }))
                ),
            )
        ]);
    }
}
 
class ChaptersContainer extends Component{
    /**
     * @param {object} props {
     *  chapters: {},
     *  actions: {function, function},
     * }
     */
    render(props){
        return h(Fragment, null,
            h('button', {
                'class':'btn chapter__add-button',
                'type':'button',
                'onClick': props.actions.add_chapter,
            }, 'Добавить главу'),
            Object.keys(props.chapters).map((chapter_id) =>
                h(Chapter, {key:chapter_id, actions:props.actions, id:chapter_id, ...props.chapters[chapter_id]})
            )
        );
    }
}
 
class SortPost extends Component{
 
    actions = {
        add_chapter: this.add_chapter.bind(this),
        delete_chapter: this.delete_chapter.bind(this),
        input_chapter_title: this.input_chapter_title.bind(this),
        remove_post: this.remove_post.bind(this),
    }
 
    constructor(props){
        super(props);
        this.state = {chapters: props.chapters, posts_without_section:props.posts_without_section};
    }
 
    /**
     * добавляет новую главу в раздел перед главой -1
     */
    add_chapter(){
        //добавляем новую главу перед -1 главой
        this.setState((prev_state) => {
            const new_name = '*';
            let ret = {};
            let prev_id = null;
            for(let id in prev_state.chapters){
                if(id == -1){
                    ret[(prev_id+1)+new_name] = {posts: [], title: ''};
                }
                ret[id] = prev_state.chapters[id];
                if(id.substring(id.length - new_name.length) === new_name){
                    prev_id = +id.substring(0, id.length - new_name.length);
                }else{
                    prev_id = +id;
                }
            }
            return {chapters:ret};
        });
    }
 
    /**
     * добавляет post в массив post_list с учетом order и id, таким образом
     * что сортировка постов производится сначала по order потом по id в порядке возрастания
     * @param {{order:int, id:int, ...}} post
     * @param  {[post, post, ...]} post_list
     * @returns
     */
    add_post_with_order(post, post_list){
 
        let left = 0;
        let right = post_list.length-1;
        let mid = 0;
 
        for(;left != right;){
            mid = left + (((right - left) / 2) | 0);
            if(post_list[mid].order <= post.order || post_list[mid].id <= post.id){
                left = mid + 1;
            }else{
                right = mid;
            }
        }
 
        mid = left;
        if(post.order > post_list[mid].order){
            mid +=1;
        }else if(post.order == post_list[mid].order && post.id > post_list[mid].id){
            mid +=1;
        }
        post_list.splice(mid, 0, post);
        return post_list;
    }
 
    /**
     * удаляет главу (кроме главы -1),если глава содержит посты, то перемещает их в главу -1
     * @param {string} id - id главы
     */
    delete_chapter(id){
        if(id == -1){
            return;
        }
 
        this.setState((prev_state) => {
            if(!prev_state.chapters.hasOwnProperty(id)){
                return {};
            }
 
            let orphan_posts = prev_state.chapters[id].posts;
            delete prev_state.chapters[id];
            for(let i in orphan_posts){
                this.add_post_with_order(orphan_posts[i], prev_state.chapters[-1].posts);
            }
 
            return {chapters:prev_state.chapters};
        });
    }
 
    /**
     * изменяет названия главы
     * @param {string} id - id главы
     * @param {string} title - наименование главы
     */
    input_chapter_title(id, title){
        this.setState((prev_state) => {
            if(!prev_state.chapters.hasOwnProperty(id)){
                return {};
            }
            prev_state.chapters[id].title = title;
 
            return {chapters:prev_state.chapters};
        });
    }
 
    /**
     * перемещает пост из текущей главы, в раздел постов без разделов
     * @param {string} chapter_id
     * @param {int} post_index
     * @param {int} post_id
     */
    remove_post(chapter_id, post_index, post_id){
        console.log(arguments);return;
        //todo
    }
 
    /**
     * @param {object} props {
     *  chapters: {},
     *  posts_without_section: []
     *  form_action: string
     * }
     */
    render(props, state){
        return h('div', {'class':'sort-box chapter'}, [
            h('form', {
                'class':'admin-form chapter__side',
                'name':'edit_order_mother_post',
                'data-ajax-reload':'true',
                'action':props.form_action,
                'method':'post',
            }, h(ChaptersContainer, {actions: this.actions, chapters:state.chapters})),
            h('div', {'class':'chapter__side'},
                h('div', {'class':'chapter__block color-back'}, [
                    h('div', {
                            'class':'chapter__header expand chapter__expander',
                            'tabindex':'0',
                            'data-js':'expand',
                            'data-expand':'#chapter__container-posts-without-section'
                        }, h('span', null, ['Посты без разделов ', h('sub', null, '(скрыты)')])
                    ),
                    h('div', {'class':'chapter__container','id':'chapter__container-posts-without-section'},
                        state.posts_without_section.map(post =>
                            h(Post, {key:post.id, chapter_id:-1, is_addable:true, ...post})
                        ),
                    )
                ])
            )
        ]);
    }
}
 
if(DATA.hasOwnProperty('chapters') && DATA.hasOwnProperty('order_change_action') && DATA.hasOwnProperty('posts_without_section')){
    render(
        h(SortPost, {
            chapters: DATA.chapters,
            posts_without_section: DATA.posts_without_section,
            form_action: DATA.order_change_action
        }),
        document.getElementById('preact-SortPost')
    );
}
Под спойлером рендер с выделенными компонентами.
Кликните здесь для просмотра всего текста


На данный момент реализовал управление следующим образом:
Родительский компонент SortPost содержит в своем состоянии (state) основной объект, в дочерние компоненты его части передаются в качестве свойств (props).
Также в каждый дочерний объект передается объект (SortPost.actions) с методами редактирования основного объекта.
Если требуется на дочерний компонент навешивается обработчик событий, который в свою очередь вызовет один из переданных методов SortPost.actions (this.props.actions).

Данная реализация мне крайне не нравится, особенно постоянная передача в глубь методов родительского компонента.
Была идея задействовать контекст, но при попытках использовать его вне метода render() он не работает.

JavaScript
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
...
class Chapter extends Component{
 
    constructor(){
        super();
 
        this.input_chapter_title = this.input_chapter_title.bind(this);
        this.delete_chapter = this.delete_chapter.bind(this);
 
        h(SortPostActions.Consumer, null, (actions) => console.log(actions)); // НЕ РАБОТАЕТ
    }
    ...
}
 
class ChaptersContainer extends Component{
    /**
     * @param {object} props {
     *  chapters: {},
     *  actions: {function, function},
     * }
     */
    render(props){
        return h(Fragment, null,
            h(SortPostActions.Consumer, null, (actions) =>  // РАБОТАЕТ
                h('button', {
                    'class':'btn chapter__add-button',
                    'type':'button',
                    'onClick': actions.add_chapter,
                }, 'Добавить главу')
            ),
            Object.keys(props.chapters).map((chapter_id) =>
                h(Chapter, {key:chapter_id, actions:props.actions, id:chapter_id, ...props.chapters[chapter_id]})
            )
        );
    }
}
 
const SortPostActions = createContext();
 
class SortPost extends Component{
    ...
    render(props, state){
        return h(SortPostActions.Provider, {value:this.actions}, 
            h('div', {'class':'sort-box chapter'}, [
                h('form', {
                    'class':'admin-form chapter__side',
                    'name':'edit_order_mother_post',
                    'data-ajax-reload':'true',
                    'action':props.form_action,
                    'method':'post',
                }, h(ChaptersContainer, {actions: this.actions, chapters:state.chapters})),
                h('div', {'class':'chapter__side'},
                    h('div', {'class':'chapter__block color-back'}, [
                        h('div', {
                                'class':'chapter__header expand chapter__expander',
                                'tabindex':'0',
                                'data-js':'expand',
                                'data-expand':'#chapter__container-posts-without-section'
                            }, h('span', null, ['Посты без разделов ', h('sub', null, '(скрыты)')])
                        ),
                        h('div', {'class':'chapter__container','id':'chapter__container-posts-without-section'},
                            state.posts_without_section.map(post =>
                                h(Post, {key:post.id, chapter_id:-1, is_addable:true, ...post})
                            ),
                        )
                    ])
                )
            ])
        );
    }
}
Также есть идея использовать делегирование событий, но тогда требуемые для обработки данные придется выносить в data атрибуты (замечание по этому поводу, и тесты для React).
В связи с эим вопрос как правильно реализовать логику взаимодействия между родительскими и дочерними компонентами?
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
07.02.2024, 11:50
Ответы с готовыми решениями:

Как сделать компонент шаблон, который принимает 3 компонента и от этого реднерит конретный подшаблон-компонент?
Как сделать компонент шаблон, который принимает 3 компонента и от этого реднерит конретный подшаблон-компонент? Если конкретнее. ...

Передача компонента в дочерние с состоянием и глобальная область видимости
Добрый вечер! Изучая для себя vue.js наткнулся на react. Развернул проект create-react-app и появился ряд вопросов которые не могу...

Передача значения переменной c одного компонента в другой компонент
Добрый день у меня задача передать в значения модели counterBuy в другой компонент по клике на counterBuy (-) (+) Как реализовать...

1
 Аватар для radiofan
3 / 2 / 1
Регистрация: 18.04.2018
Сообщений: 51
07.02.2024, 14:10  [ТС]
Решил попробовать использовать контекст подобным образом (натолкнула данная статья).

Получилось примерно так, и это работает.
JavaScript
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
class Post extends Component{
 
    actions = {};
    
    constructor(){
        super();
        
        this.remove_post = this.remove_post.bind(this);
    }
 
    remove_post(e){
        this.actions.remove_post(this.props.chapter_id, this.props.index, this.props.id);
    }
 
    render(props){
        //console.log(props);
        return h(SortPostActions.Consumer, null, (actions) => {
            this.actions = actions;
            return h(...);
        });
    }
}
 
class ChaptersContainer extends Component{
    /**
     * @param {object} props {
     *  chapters: {},
     *  actions: {function, function},
     * }
     */
    render(props){
        return h(Fragment, null,
            h(SortPostActions.Consumer, null, (actions) =>
                h('button', {
                    'class':'btn chapter__add-button',
                    'type':'button',
                    'onClick': actions.add_chapter,
                }, 'Добавить главу')
            ),
            Object.keys(props.chapters).map((chapter_id) =>
                h(Chapter, {key:chapter_id, id:chapter_id, ...props.chapters[chapter_id]})
            )
        );
    }
}
 
const SortPostActions = createContext();
 
class SortPost extends Component{
 
    actions = {
        add_chapter: this.add_chapter.bind(this),
        delete_chapter: this.delete_chapter.bind(this),
        input_chapter_title: this.input_chapter_title.bind(this),
        remove_post: this.remove_post.bind(this),
    }
 
    constructor(props){
        super(props);
        this.state = {chapters: props.chapters, posts_without_section:props.posts_without_section};
    }
    
    ...
 
    /**
     * @param {object} props {
     *  chapters: {},
     *  posts_without_section: []
     *  form_action: string
     * }
     */
    render(props, state){
        return h(SortPostActions.Provider, {value: this.actions}, 
            h('div', {'class':'sort-box chapter'}, [
                h('form', {
                    'class':'admin-form chapter__side',
                    'name':'edit_order_mother_post',
                    'data-ajax-reload':'true',
                    'action':props.form_action,
                    'method':'post',
                }, h(ChaptersContainer, {chapters:state.chapters})),
                h('div', {'class':'chapter__side'},
                    h('div', {'class':'chapter__block color-back'}, [
                        h('div', {
                                'class':'chapter__header expand chapter__expander',
                                'tabindex':'0',
                                'data-js':'expand',
                                'data-expand':'#chapter__container-posts-without-section'
                            }, h('span', null, ['Посты без разделов ', h('sub', null, '(скрыты)')])
                        ),
                        h('div', {'class':'chapter__container','id':'chapter__container-posts-without-section'},
                            state.posts_without_section.map(post =>
                                h(Post, {key:post.id, chapter_id:-1, is_addable:true, ...post})
                            ),
                        )
                    ])
                )
            ])
        );
    }
}
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
07.02.2024, 14:10
Помогаю со студенческими работами здесь

Управление состоянием объекта
Например ситуация: при столкновении объектов один меняет цвет и через 10 секунд меняет на другой или возвращается в исходное состояние ...

Управление состоянием объекта
Например ситуация: при столкновении объектов один меняет цвет и через 10 секунд меняет на другой или возвращается в исходное состояние ...

Управление состоянием checkBox'а
Здравствуйте.Подскажите пожалуйста как сделать такой момент: Имеется 2 checkbox,как сделать так чтоб если первая checkbox не выбрана то...

Управление состоянием триггера из храномой процедуры
Всем здрасьте, пытаюсь решить такую задачу: На таблицу есть два триггера отрабатывают на before insert, первый триггер генерирует id...

Управление состоянием дома через интернет
Привет. Жаль нету фотика щас, так бы показал что получилось. Вообщем на atmega16 сделал простую схемку для подключения устройства к...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Первый деплой
lagorue 16.01.2026
Не спеша развернул своё 1ое приложение в kubernetes. А дальше мне интересно создать 1фронтэнд приложения и 2 бэкэнд приложения развернуть 2 деплоя в кубере получится 2 сервиса и что-бы они. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит токи на L и напряжения на C в установ. режимах до и. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Изучаю kubernetes
lagorue 13.01.2026
А пригодятся-ли мне знания kubernetes в России?
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru