Skip to content

Commit 6a6d690

Browse files
committed
update demo05 for React.Children
1 parent cb7cb65 commit 6a6d690

File tree

2 files changed

+8
-6
lines changed

2 files changed

+8
-6
lines changed

README.md

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -127,14 +127,14 @@ Components can have attributes, and you can use `this.props.[attribute]` to acce
127127

128128
React uses `this.props.children` to access a component's children nodes.
129129

130-
```js
130+
```javascript
131131
var NotesList = React.createClass({
132132
render: function() {
133133
return (
134134
<ol>
135135
{
136-
this.props.children.map(function (child) {
137-
return <li>{child}</li>
136+
React.Children.map(this.props.children, function (child) {
137+
return <li>{child}</li>;
138138
})
139139
}
140140
</ol>
@@ -151,7 +151,9 @@ ReactDOM.render(
151151
);
152152
```
153153

154-
Please be minded that only if the component has more than one child node, you could take `this.props.children` as an array, otherwise `this.props.children.map` throws a TypeError.
154+
Please be minded that the value of `this.props.children` has three possibilities. If the component has no children node, the value is `undefined`; If single children node, an object; If multiple children nodes, an array. You should be careful to handle it.
155+
156+
React gave us an utility [`React.Children`](https://facebook.github.io/react/docs/top-level-api.html#react.children) for dealing with the `this.props.children`'s opaque data structure. You could use `React.Children.map` to iterate `this.props.children` without worring its data type being `undefined` or `object`. Check [official document](https://facebook.github.io/react/docs/top-level-api.html#react.children) for more methods `React.Children` offers.
155157

156158
## Demo06: PropTypes ([source](https://github.com/ruanyf/react-demos/blob/master/demo06/index.html))
157159

demo05/index.html

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@
1212
return (
1313
<ol>
1414
{
15-
this.props.children.map(function (child) {
16-
return <li>{child}</li>
15+
React.Children.map(this.props.children, function (child) {
16+
return <li>{child}</li>;
1717
})
1818
}
1919
</ol>

0 commit comments

Comments
 (0)