This article focuses on the application of React.Children. Map.
The React. Children. The map syntax
React.Children.map(children, function(item, index) {}, context)
Copy the code
React.children. Map recursively traverses all Children (leaf nodes) and expands all Children, returning null or undefined if Children are null or undefined.
Official documentation reactjs.org/docs/react-…
Try React.Children. Map
// Output [1, 2, 3]
React.Children.map([1.2.3].function(item,index) {
return item;
})
// Output [1, 2, 3]
React.Children.map([1[2[3]]].function(item,index) {
return item;
})
// Output [1, 2, 3]
React.Children.map([1.2.3].function(item,index) {
return [[[item]]];
})
// Output [1, 1, 2, 2, 3, 3]
React.Children.map([1.2.3].function(item,index) {
return [item, item];
})
// Output [1, "hello", 2, 3, "hello"]
React.Children.map([1.2.3].function(item,index) {
if(index % 2= = =0) {
return [item, 'hello'];
}
return item;
})
/ / output is null
React.Children.map(null.function(item,index) {
return item;
})
Copy the code
Actual combat to multiple operation buttons to add a dividing line, the effect is as follows
The Join components
import React from 'react';
import {Divider} from 'antd';
export default function Join({children, divider = <Divider type="vertical" style={{borderColor: 'red'/ >}}}) {
const len = React.Children.count(children)
return React.Children.map(children, (child, index) = > {
if (index < len -1) {
return [child, divider];
}
returnchild; })}Copy the code
Use the sample
import React from 'react';
import Join from '@/components/WithDivider';
function OperateGroup() {
function onClick(type) {
console.log(type)
}
return <div style={{padding: 10.backgroundColor: '#fff'}} >
<Join>
<a onClick={()= >OnClick ('detail')}> View details</a>
<a onClick={()= >> add onClick (' add ')}</a>
<a onClick={()= >The onClick (' modify ')} > modification</a>
<a onClick={()= >The onClick (' delete ')} > delete</a>
</Join>
</div>
}
export default OperateGroup
Copy the code
The component version of the array-like Join method is complete.
This article links
www.hijs.ren/article/blo…