OSDN Git Service

Regular updates
[twpd/master.git] / react@0.14.md
1 ---
2 title: React.js (v0.14)
3 category: React
4 layout: 2017/sheet
5 deprecated: true
6 intro: |
7   **Deprecated:** this guide targets an old version of React (v0.14). See the [updated React cheatsheet](react) for new versions.
8 ---
9
10 {%raw%}
11
12 ### Components
13
14 ```js
15 var Component = React.createClass({
16   render: function () {
17     return <div>Hello {this.props.name}</div>;
18   }
19 });
20 ```
21
22 ```js
23 ReactDOM.render(<Component name="John" />, document.body);
24 ```
25 {:.light}
26
27 Use the [React.js jsfiddle](http://jsfiddle.net/reactjs/69z2wepo/) to start hacking. (or the unofficial [jsbin](http://jsbin.com/yafixat/edit?js,output))
28
29 ### Nesting
30
31 ```js
32 var UserAvatar  = React.createClass({...});
33 var UserProfile = React.createClass({...});
34 ```
35 {:.light}
36
37 ```js
38 var Info = React.createClass({
39   render() {
40     return <div>
41       <UserAvatar src={this.props.avatar} />
42       <UserProfile username={this.props.username} />
43     </div>;
44   }
45 });
46 ```
47
48 Nest components to separate concerns. See [multiple components](http://facebook.github.io/react/docs/multiple-components.html).
49
50 ## States & Properties
51 {:.center}
52
53 ### States and props
54
55 ```html
56 <MyComponent fullscreen={true} />
57 ```
58 {:.light}
59  
60 ```js
61 // props
62   this.props.fullscreen //=> true
63
64 // state
65   this.setState({ username: 'rstacruz' });
66   this.replaceState({ ... });
67   this.state.username //=> 'rstacruz'
68 ```
69
70 ```js
71 render: function () {
72   return <div className={this.props.fullscreen ? 'full' : ''}>
73     Welcome, {this.state.username}
74   </div>;
75 }
76 ```
77
78 Use [props](https://facebook.github.io/react/docs/tutorial.html#using-props) (`this.props`) to access parameters passed from the parent.
79 Use [states](https://facebook.github.io/react/docs/tutorial.html#reactive-state) (`this.state`) to manage dynamic data.
80
81 ### Setting defaults
82
83 ```js
84 React.createClass({
85   getInitialState: function () {
86     return { comments: [] };
87   },
88
89   getDefaultProps: function () {
90     return { name: "Hello" };
91   }
92 );
93 ```
94
95 Pre-populates `this.state.comments` and `this.props.name`.
96
97 ## Components
98
99 ### Component API
100
101 ```js
102 ReactDOM.findDOMNode(c)  // 0.14+
103 React.findDOMNode(c)  // 0.13
104 c.getDOMNode()        // 0.12 below
105 ```
106 {:.light}
107
108 ```js
109 c.forceUpdate()
110 c.isMounted()
111
112 c.state
113 c.props
114
115 c.setState({ ... })
116 c.replaceState({ ... })
117
118 c.setProps({ ... })       // for deprecation
119 c.replaceProps({ ... })   // for deprecation
120
121 c.refs
122 ```
123
124 These are methods available for `Component` instances. See [Component API](http://facebook.github.io/react/docs/component-api.html).
125
126 ### Component specs
127
128 | Method | What |
129 | ---- | ---- |
130 | [`render()`](http://facebook.github.io/react/docs/component-specs.html#render) | |
131 | ---- | ---- |
132 | [`getInitialState()`](http://facebook.github.io/react/docs/component-specs.html#getinitialstate) | |
133 | [`getDefaultProps()`](http://facebook.github.io/react/docs/component-specs.html#getdefaultprops) |  |
134 | ---- | ---- |
135 | [`mixins: [ ... ]`](http://facebook.github.io/react/docs/component-specs.html#mixins) | Mixins ... [more](#mixins) |
136 | [`propTypes: { ... }`](http://facebook.github.io/react/docs/component-specs.html#proptypes) | Validation ... [more](#property-validation) |
137 | [`statics: { ... }`](http://facebook.github.io/react/docs/component-specs.html#statics) | Static methods |
138 | [`displayName: "..."`](http://facebook.github.io/react/docs/component-specs.html#displayname) | Automatically filled by JSX |
139 {:.greycode.no-head}
140
141 Methods and properties you can override. See [component specs](http://facebook.github.io/react/docs/component-specs.html).
142
143 ## Lifecycle
144
145 ### Mounting
146
147 | `componentWillMount()` | Before rendering (no DOM yet) |
148 | `componentDidMount()` | After rendering |
149 {:.greycode.no-head.lc}
150
151 Before initial rendering occurs. Add your DOM stuff on didMount (events, timers, etc). See [reference](http://facebook.github.io/react/docs/component-specs.html#mounting-componentwillmount).
152
153 ### Updating
154
155 | `componentWillReceiveProps`*(newProps={})* | Use `setState()` here |
156 | `shouldComponentUpdate`*(newProps={}, newState={})* | Skips `render()` if returns false |
157 | `componentWillUpdate`*(newProps={}, newState={})* | Can't use `setState()` here |
158 | `componentDidUpdate`*(prevProps={}, prevState={})* | Operate on the DOM here |
159 {:.greycode.no-head.lc}
160
161 Called when parents change properties and `.setState()`. These are not called for initial renders. See [reference](http://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops).
162
163 ### Unmounting
164
165 | `componentWillUnmount()` | Invoked before DOM removal |
166 {:.greycode.no-head.lc}
167
168 Clear your DOM stuff here (probably done on didMount). See [reference](http://facebook.github.io/react/docs/component-specs.html#unmounting-componentwillunmount).
169
170 ## Examples
171
172 ### Example: loading data
173
174 ```js
175 React.createClass({
176   componentDidMount: function () {
177     $.get(this.props.url, function (data) {
178       this.setState(data);
179     }.bind(this));
180   },
181
182   render: function () {
183     return <CommentList data={this.state.data} />
184   }
185 });
186 ```
187
188 See [initial AJAX data](http://facebook.github.io/react/tips/initial-ajax.html).
189
190 ## DOM nodes
191
192 ### References
193
194 ```html
195 <input ref="myInput">
196 ```
197 {:.light}
198
199 ```js
200 this.refs.myInput
201 ReactDOM.findDOMNode(this.refs.myInput).focus()
202 ReactDOM.findDOMNode(this.refs.myInput).value
203 ```
204
205 ### DOM Events
206 Add attributes like `onChange`. See [events](https://facebook.github.io/react/docs/events.html).
207
208 ```html
209 <input type="text"
210     value={this.state.value}
211     onChange={this.handleChange} />
212 ```
213 {:.light}
214
215 ```js
216 handleChange: function(event) {
217   this.setState({ value: event.target.value });
218 }
219 ```
220
221 Allows access to DOM nodes. See [References](http://facebook.github.io/react/docs/more-about-refs.html).
222
223 ### Two-way binding
224
225 ```html
226 Email: <input type="text" valueLink={this.linkState('email')} />
227 ```
228 {:.light}
229
230 ```js
231 React.createClass({
232   mixins: [React.addons.LinkedStateMixin]
233 });
234 ```
235
236 ```js
237 this.state.email
238 ```
239
240 Use [LinkedStateMixin](http://facebook.github.io/react/docs/two-way-binding-helpers.html) for easier two-way binding.
241
242 ## Property validation
243
244 ### Basic types
245
246 ```js
247 React.createClass({
248   propTypes: {
249     email:      React.PropTypes.string,
250     seats:      React.PropTypes.number,
251     settings:   React.PropTypes.object,
252     callback:   React.PropTypes.func,
253     isClosed:   React.PropTypes.bool,
254     any:        React.PropTypes.any,
255   }
256 });
257 ```
258 Primitive types: `.string`, `.number`, `.func`, and `.bool`. See [propTypes](http://facebook.github.io/react/docs/reusable-components.html#prop-validation).
259
260 ### Required types
261
262 ```js
263 propTypes: {
264   requiredFunc:  React.PropTypes.func.isRequired,
265   requiredAny:   React.PropTypes.any.isRequired,
266 ```
267
268 Add `.isRequired`.
269
270 ### React elements
271
272 ```js
273 propTypes: {
274   element:  React.PropTypes.element,  // react element
275   node:     React.PropTypes.node,     // num, string, element
276                                       // ...or array of those
277 ```
278
279 Use `.element`, `.node`.
280
281 ### Enumerables
282
283 ```
284 propTypes: {
285   enum:     React.PropTypes.oneOf(['M','F']),  // enum
286   union:    React.PropTypes.oneOfType([        // any
287               React.PropTypes.string,
288               React.PropTypes.number ]),
289 ```
290
291 Use `.oneOf`, `.oneOfType`.
292
293 ### Arrays and objects
294
295 ```js
296 propTypes: {
297   array:    React.PropTypes.array,
298   arrayOf:  React.PropTypes.arrayOf(React.PropTypes.number),
299   object:   React.PropTypes.object,
300   objectOf: React.PropTypes.objectOf(React.PropTypes.number),
301
302   message:  React.PropTypes.instanceOf(Message),
303
304   object2:  React.PropTypes.shape({
305     color:  React.PropTypes.string,
306     size:   React.PropTypes.number
307   }),
308 ```
309
310 Use `.array[Of]`, `.object[Of]`, `.instanceOf`, `.shape`.
311
312 ### Custom validation
313
314 ```js
315 propTypes: {
316   customProp: function(props, propName, componentName) {
317     if (!/matchme/.test(props[propName])) {
318       return new Error('Validation failed!');
319     }
320   }
321 }
322 ```
323
324 Supply your own function.
325
326 ## Other features
327
328 ### Class set
329
330 ```js
331 var cx = require('classnames');
332
333 render: function() {
334   var classes = cx({
335     'message': true,
336     'message-important': this.props.isImportant,
337     'message-read': this.props.isRead
338   });
339
340   return <div className={classes}>Great Scott!</div>;
341 }
342 ```
343
344 Manipulate DOM classes with [classnames](https://www.npmjs.org/package/classnames), previously known as `React.addons.classSet`. See [Class set](http://facebook.github.io/react/docs/class-name-manipulation.html).
345
346 ### Propagating properties
347
348 ```html
349 <VideoPlayer src="video.mp4" />
350 ```
351 {:.light}
352
353 ```js
354 var VideoPlayer = React.createClass({
355   render: function() {
356     /* propagates src="..." down to this sub component */
357     return <VideoEmbed {...this.props} controls='false' />;
358   }
359 });
360 ```
361
362 See [Transferring props](http://facebook.github.io/react/docs/transferring-props.html).
363
364 ### Mixins
365
366 ```js
367 var SetIntervalMixin = {
368   componentWillMount: function() { .. }
369 }
370 ```
371 {:.light}
372
373 ```js
374 var TickTock = React.createClass({
375   mixins: [SetIntervalMixin]
376 }
377 ```
378
379 See [addons](https://facebook.github.io/react/docs/addons.html) for some built-in mixins.
380
381 ## [Top level API](https://facebook.github.io/react/docs/top-level-api.html)
382
383 ```js
384 React.createClass({ ... })
385
386 React.isValidElement(c)
387
388 ReactDOM.findDOMNode(c) // 0.14+
389 ReactDOM.render(<Component />, domnode, [callback]) // 0.14+
390 ReactDOM.unmountComponentAtNode(domnode) // 0.14+
391
392 ReactDOMServer.renderToString(<Component />) // 0.14+
393 ReactDOMServer.renderToStaticMarkup(<Component />) // 0.14+
394 ```
395
396 ## JSX patterns
397
398 ### Style shorthand
399
400 ```js
401 var style = { backgroundImage: 'url(x.jpg)', height: 10 };
402 return <div style={style}></div>;
403 ```
404
405 See [inline styles](https://facebook.github.io/react/tips/inline-styles.html).
406
407 ### InnerHTML
408
409 ```js
410 function markdownify() { return "<p>...</p>"; }
411 <div dangerouslySetInnerHTML={{__html: markdownify()}} />
412 ```
413
414 See [dangerously set innerHTML](https://facebook.github.io/react/tips/dangerously-set-inner-html.html).
415
416 ### Lists
417
418 ```js
419 var TodoList = React.createClass({
420   render: function() {
421     function item(itemText) {
422       return <li>{itemText}</li>;
423     };
424     return <ul>{this.props.items.map(item)}</ul>;
425   }
426 });
427 ```
428
429 ## See also
430
431 * [Animations](http://facebook.github.io/react/docs/animation.html)
432 {%endraw%}