From 68906806330cd7b30edd7accd595cfa26d64f754 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BA=8C=E8=B4=A7=E6=9C=BA=E5=99=A8=E4=BA=BA?= Date: Fri, 28 Aug 2020 10:54:02 +0800 Subject: [PATCH] feat: toArray support empty (#141) --- src/Children/toArray.ts | 9 +++++++-- tests/toArray.test.js | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/src/Children/toArray.ts b/src/Children/toArray.ts index 17f96cd9..91ba5a41 100644 --- a/src/Children/toArray.ts +++ b/src/Children/toArray.ts @@ -1,20 +1,25 @@ import React from 'react'; import { isFragment } from 'react-is'; +export interface Option { + keepEmpty?: boolean; +} + export default function toArray( children: React.ReactNode, + option: Option = {}, ): React.ReactElement[] { let ret: React.ReactElement[] = []; React.Children.forEach(children, (child: any) => { - if (child === undefined || child === null) { + if ((child === undefined || child === null) && !option.keepEmpty) { return; } if (Array.isArray(child)) { ret = ret.concat(toArray(child)); } else if (isFragment(child) && child.props) { - ret = ret.concat(toArray(child.props.children)); + ret = ret.concat(toArray(child.props.children, option)); } else { ret.push(child); } diff --git a/tests/toArray.test.js b/tests/toArray.test.js index ca566d6a..37b5b81b 100644 --- a/tests/toArray.test.js +++ b/tests/toArray.test.js @@ -51,4 +51,40 @@ describe('toArray', () => { expect(children).toHaveLength(5); expect(children.map(c => c.key)).toEqual(['1', '2', '3', '4', '5']); }); + + it('keep empty', () => { + const wrapper = mount( + , + ); + + const children = toArray(wrapper.props().children, { keepEmpty: true }); + expect(children).toHaveLength(9); + expect(children.map(c => c && c.key)).toEqual([ + null, + '1', + '2', + null, + '3', + '4', + null, + '5', + null, + ]); + }); });