Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"react-dom": "^15.0.0 || ^16.0.0"
},
"devDependencies": {
"@types/enzyme": "^3.10.5",
"@types/jest": "^24.0.23",
"@types/react": "^16.9.3",
"@types/react-dom": "^16.9.1",
Expand All @@ -52,6 +53,7 @@
"add-dom-event-listener": "^1.1.0",
"babel-runtime": "6.x",
"prop-types": "^15.5.10",
"react-is": "^16.12.0",
"react-lifecycles-compat": "^3.0.4",
"shallowequal": "^1.1.0"
}
Expand Down
17 changes: 13 additions & 4 deletions src/Children/toArray.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import React from 'react';
import { isFragment } from 'react-is';

export default function toArray(children: React.ReactNode): React.ReactElement[] {
const ret = [];
React.Children.forEach(children, c => {
ret.push(c);
export default function toArray(
children: React.ReactNode,
): React.ReactElement[] {
let ret: React.ReactElement[] = [];

React.Children.forEach(children, (child: any) => {
if (isFragment(child) && child.props) {
ret = ret.concat(toArray(child.props.children));
} else {
ret.push(child);
}
});

return ret;
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

参考过了,沿用原本的 toArray 逻辑。否则会影响 key

54 changes: 54 additions & 0 deletions tests/toArray.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import React from 'react';
import { mount } from 'enzyme';
import toArray from '../src/Children/toArray';

describe('toArray', () => {
it('basic', () => {
const wrapper = mount(
<ul>
<li key="1">1</li>
<li key="2">2</li>
<li key="3">3</li>
</ul>,
);

const children = toArray(wrapper.props().children);
expect(children).toHaveLength(3);
expect(children.map(c => c.key)).toEqual(['1', '2', '3']);
});

it('Array', () => {
const wrapper = mount(
<ul>
<li key="1">1</li>
{[<li key="2">2</li>, <li key="3">3</li>]}
</ul>,
);

const children = toArray(wrapper.props().children);
expect(children).toHaveLength(3);
expect(children.map(c => c.key)).toEqual(['1', '2', '3']);
});

it('Fragment', () => {
const wrapper = mount(
<ul>
<li key="1">1</li>
<>
<li key="2">2</li>
<li key="3">3</li>
</>
<React.Fragment>
<>
<li key="4">4</li>
<li key="5">5</li>
</>
</React.Fragment>
</ul>,
);

const children = toArray(wrapper.props().children);
expect(children).toHaveLength(5);
expect(children.map(c => c.key)).toEqual(['1', '2', '3', '4', '5']);
});
});