Skip to content

Commit

Permalink
update(web-React): React children array API
Browse files Browse the repository at this point in the history
issue #105
  • Loading branch information
sabertazimi committed Aug 4, 2021
1 parent 51a54a0 commit 91bc504
Showing 1 changed file with 79 additions and 0 deletions.
79 changes: 79 additions & 0 deletions notes/web/react/reactBasicNotes.md
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,85 @@ function App() {
}
```

#### React Children API

```jsx
import { Children, cloneElement } from 'react';

function Breadcrumbs({ children }) {
const arrayChildren = Children.toArray(children);

return (
<ul
style={{
listStyle: 'none',
display: 'flex',
}}
>
{Children.map(arrayChildren, (child, index) => {
const isLast = index === arrayChildren.length - 1;

if (!isLast && !child.props.link) {
throw new Error(
`BreadcrumbItem child no. ${index + 1}
should be passed a 'link' prop`
);
}

return (
<>
{child.props.link ? (
<a
href={child.props.link}
style={{
display: 'inline-block',
textDecoration: 'none',
}}
>
<div style={{ marginRight: '5px' }}>
{cloneElement(child, {
isLast,
})}
</div>
</a>
) : (
<div style={{ marginRight: '5px' }}>
{cloneElement(child, {
isLast,
})}
</div>
)}
{!isLast && <div style={{ marginRight: '5px' }}>></div>}
</>
);
})}
</ul>
);
}

function BreadcrumbItem({ isLast, children }) {
return (
<li
style={{
color: isLast ? 'black' : 'blue',
}}
>
{children}
</li>
);
}

export default function App() {
return (
<Breadcrumbs>
<BreadcrumbItem link="https://example.com/">Example</BreadcrumbItem>
<BreadcrumbItem link="https://example.com/hotels/">Hotels</BreadcrumbItem>
<BreadcrumbItem>A Fancy Hotel Name</BreadcrumbItem>
</Breadcrumbs>
);
}
```

### Refs

Refs 用于返回对元素的引用.
Expand Down

0 comments on commit 91bc504

Please sign in to comment.