OSDN Git Service

Regular updates
[twpd/master.git] / react.md
1 ---
2 title: React.js
3 category: React
4 layout: 2017/sheet
5 ads: true
6 tags: [Featured]
7 updated: 2020-07-05
8 weight: -10
9 keywords:
10   - React.Component
11   - render()
12   - componentDidMount()
13   - props/state
14   - dangerouslySetInnerHTML
15 intro: |
16   [React](https://reactjs.org/) is a JavaScript library for building user interfaces. This guide targets React v15 to v16.
17 ---
18
19 {%raw%}
20
21 Components
22 ----------
23 {: .-three-column}
24
25 ### Components
26 {: .-prime}
27
28 ```jsx
29 import React from 'react'
30 import ReactDOM from 'react-dom'
31 ```
32 {: .-setup}
33
34 ```jsx
35 class Hello extends React.Component {
36   render () {
37     return <div className='message-box'>
38       Hello {this.props.name}
39     </div>
40   }
41 }
42 ```
43
44 ```jsx
45 const el = document.body
46 ReactDOM.render(<Hello name='John' />, el)
47 ```
48
49 Use the [React.js jsfiddle](http://jsfiddle.net/reactjs/69z2wepo/) to start hacking. (or the unofficial [jsbin](http://jsbin.com/yafixat/edit?js,output))
50
51 ### Import multiple exports
52 {: .-prime}
53
54 ```jsx
55 import React, {Component} from 'react'
56 import ReactDOM from 'react-dom'
57 ```
58 {: .-setup}
59
60 ```jsx
61 class Hello extends Component {
62   ...
63 }
64 ```
65
66 ### Properties
67
68 ```html
69 <Video fullscreen={true} autoplay={false} />
70 ```
71 {: .-setup}
72
73 ```jsx
74 render () {
75   this.props.fullscreen
76   const { fullscreen, autoplay } = this.props
77   ···
78 }
79 ```
80 {: data-line="2,3"}
81
82 Use `this.props` to access properties passed to the component.
83
84 See: [Properties](https://reactjs.org/docs/tutorial.html#using-props)
85
86 ### States
87
88 ```jsx
89 constructor(props) {
90   super(props)
91   this.state = { username: undefined }
92 }
93 ```
94
95 ```jsx
96 this.setState({ username: 'rstacruz' })
97 ```
98
99 ```jsx
100 render () {
101   this.state.username
102   const { username } = this.state
103   ···
104 }
105 ```
106 {: data-line="2,3"}
107
108 Use states (`this.state`) to manage dynamic data.
109
110 With [Babel](https://babeljs.io/) you can use [proposal-class-fields](https://github.com/tc39/proposal-class-fields) and get rid of constructor
111
112 ```jsx
113 class Hello extends Component {
114   state = { username: undefined };
115   ...
116 }
117 ```
118
119 See: [States](https://reactjs.org/docs/tutorial.html#reactive-state)
120
121
122 ### Nesting
123
124 ```jsx
125 class Info extends Component {
126   render () {
127     const { avatar, username } = this.props
128
129     return <div>
130       <UserAvatar src={avatar} />
131       <UserProfile username={username} />
132     </div>
133   }
134 }
135 ```
136 As of React v16.2.0, fragments can be used to return multiple children without adding extra wrapping nodes to the DOM.
137
138 ```jsx
139 import React, {
140   Component,
141   Fragment
142 } from 'react'
143
144 class Info extends Component {
145   render () {
146     const { avatar, username } = this.props
147
148     return (
149       <Fragment>
150         <UserAvatar src={avatar} />
151         <UserProfile username={username} />
152       </Fragment>
153     )
154   }
155 }
156 ```
157
158 {: data-line="5,6,7,8,9,10"}
159
160 Nest components to separate concerns.
161
162 See: [Composing Components](https://reactjs.org/docs/components-and-props.html#composing-components)
163
164 ### Children
165
166 ```jsx
167 <AlertBox>
168   <h1>You have pending notifications</h1>
169 </AlertBox>
170 ```
171 {: data-line="2"}
172
173 ```jsx
174 class AlertBox extends Component {
175   render () {
176     return <div className='alert-box'>
177       {this.props.children}
178     </div>
179   }
180 }
181 ```
182 {: data-line="4"}
183
184 Children are passed as the `children` property.
185
186 Defaults
187 --------
188
189 ### Setting default props
190
191 ```jsx
192 Hello.defaultProps = {
193   color: 'blue'
194 }
195 ```
196 {: data-line="1"}
197
198 See: [defaultProps](https://reactjs.org/docs/react-component.html#defaultprops)
199
200 ### Setting default state
201
202 ```jsx
203 class Hello extends Component {
204   constructor (props) {
205     super(props)
206     this.state = { visible: true }
207   }
208 }
209 ```
210 {: data-line="4"}
211
212 Set the default state in the `constructor()`.
213
214 And without constructor using [Babel](https://babeljs.io/) with [proposal-class-fields](https://github.com/tc39/proposal-class-fields).
215
216 ```jsx
217 class Hello extends Component {
218   state = { visible: true }
219 }
220 ```
221 {: data-line="2"}
222
223 See: [Setting the default state](https://reactjs.org/docs/react-without-es6.html#setting-the-initial-state)
224
225 Other components
226 ----------------
227 {: .-three-column}
228
229 ### Functional components
230
231 ```jsx
232 function MyComponent ({ name }) {
233   return <div className='message-box'>
234     Hello {name}
235   </div>
236 }
237 ```
238 {: data-line="1"}
239
240 Functional components have no state. Also, their `props` are passed as the first parameter to a function.
241
242 See: [Function and Class Components](https://reactjs.org/docs/components-and-props.html#functional-and-class-components)
243
244 ### Pure components
245
246 ```jsx
247 import React, {PureComponent} from 'react'
248
249 class MessageBox extends PureComponent {
250   ···
251 }
252 ```
253 {: data-line="3"}
254
255 Performance-optimized version of `React.Component`. Doesn't rerender if props/state hasn't changed.
256
257 See: [Pure components](https://reactjs.org/docs/react-api.html#react.purecomponent)
258
259 ### Component API
260
261 ```jsx
262 this.forceUpdate()
263 ```
264
265 ```jsx
266 this.setState({ ... })
267 this.setState(state => { ... })
268 ```
269
270 ```jsx
271 this.state
272 this.props
273 ```
274
275 These methods and properties are available for `Component` instances.
276
277 See: [Component API](http://facebook.github.io/react/docs/component-api.html)
278
279 Lifecycle
280 ---------
281 {: .-two-column}
282
283 ### Mounting
284
285 | Method                   | Description                                                                                          |
286 | ------------------------ | ---------------------------------------------------------------------------------------------------- |
287 | `constructor` _(props)_  | Before rendering [#](https://reactjs.org/docs/react-component.html#constructor)                      |
288 | `componentWillMount()`   | _Don't use this_ [#](https://reactjs.org/docs/react-component.html#componentwillmount)               |
289 | `render()`               | Render [#](https://reactjs.org/docs/react-component.html#render)                                     |
290 | `componentDidMount()`    | After rendering (DOM available) [#](https://reactjs.org/docs/react-component.html#componentdidmount) |
291 | ---                      | ---                                                                                                  |
292 | `componentWillUnmount()` | Before DOM removal [#](https://reactjs.org/docs/react-component.html#componentwillunmount)           |
293 | ---                      | ---                                                                                                  |
294 | `componentDidCatch()`    | Catch errors (16+) [#](https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html)          |
295
296 Set initial the state on `constructor()`.
297 Add DOM event handlers, timers (etc) on `componentDidMount()`, then remove them on `componentWillUnmount()`.
298
299 ### Updating
300
301 | Method                                                  | Description                                          |
302 | ------------------------------------------------------- | ---------------------------------------------------- |
303 | `componentDidUpdate` _(prevProps, prevState, snapshot)_ | Use `setState()` here, but remember to compare props |
304 | `shouldComponentUpdate` _(newProps, newState)_          | Skips `render()` if returns false                    |
305 | `render()`                                              | Render                                               |
306 | `componentDidUpdate` _(prevProps, prevState)_           | Operate on the DOM here                              |
307
308 Called when parents change properties and `.setState()`. These are not called for initial renders.
309
310 See: [Component specs](http://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops)
311
312 Hooks (New)
313 -----------
314 {: .-two-column}
315
316 ### State Hook
317
318 ```jsx
319 import React, { useState } from 'react';
320
321 function Example() {
322   // Declare a new state variable, which we'll call "count"
323   const [count, setCount] = useState(0);
324
325   return (
326     <div>
327       <p>You clicked {count} times</p>
328       <button onClick={() => setCount(count + 1)}>
329         Click me
330       </button>
331     </div>
332   );
333 }
334 ```
335 {: data-line="5,10"}
336
337 Hooks are a new addition in React 16.8.
338
339 See: [Hooks at a Glance](https://reactjs.org/docs/hooks-overview.html)
340
341 ### Declaring multiple state variables
342
343 ```jsx
344 function ExampleWithManyStates() {
345   // Declare multiple state variables!
346   const [age, setAge] = useState(42);
347   const [fruit, setFruit] = useState('banana');
348   const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
349   // ...
350 }
351 ```
352
353 ### Effect hook
354
355 ```jsx
356 import React, { useState, useEffect } from 'react';
357
358 function Example() {
359   const [count, setCount] = useState(0);
360
361   // Similar to componentDidMount and componentDidUpdate:
362   useEffect(() => {
363     // Update the document title using the browser API
364     document.title = `You clicked ${count} times`;
365   }, [count]);
366
367   return (
368     <div>
369       <p>You clicked {count} times</p>
370       <button onClick={() => setCount(count + 1)}>
371         Click me
372       </button>
373     </div>
374   );
375 }
376 ```
377 {: data-line="6,7,8,9,10"}
378
379 If you’re familiar with React class lifecycle methods, you can think of `useEffect` Hook as `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` combined.
380
381 By default, React runs the effects after every render — including the first render.
382
383 ### Building your own hooks
384
385 #### Define FriendStatus
386 ```jsx
387 import React, { useState, useEffect } from 'react';
388
389 function FriendStatus(props) {
390   const [isOnline, setIsOnline] = useState(null);
391
392   useEffect(() => {
393     function handleStatusChange(status) {
394       setIsOnline(status.isOnline);
395     }
396
397     ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
398     return () => {
399       ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
400     };
401   }, [props.friend.id]);
402
403   if (isOnline === null) {
404     return 'Loading...';
405   }
406   return isOnline ? 'Online' : 'Offline';
407 }
408 ```
409 {: data-line="11,12,13,14"}
410
411 Effects may also optionally specify how to “clean up” after them by returning a function. 
412
413 #### Use FriendStatus
414
415 ```jsx
416 function FriendStatus(props) {
417   const isOnline = useFriendStatus(props.friend.id);
418
419   if (isOnline === null) {
420     return 'Loading...';
421   }
422   return isOnline ? 'Online' : 'Offline';
423 }
424 ```
425 {: data-line="2"}
426
427 See: [Building Your Own Hooks](https://reactjs.org/docs/hooks-custom.html)
428
429 ### Hooks API Reference
430
431 Also see: [Hooks FAQ](https://reactjs.org/docs/hooks-faq.html)
432
433 #### Basic Hooks
434
435 | Hook                         | Description                               |
436 | ---------------------------- | ----------------------------------------- |
437 | `useState`_(initialState)_   |                                           |
438 | `useEffect`_(() => { ... })_ |                                           |
439 | `useContext`_(MyContext)_    | value returned from `React.createContext` |
440
441 Full details: [Basic Hooks](https://reactjs.org/docs/hooks-reference.html#basic-hooks)
442
443 #### Additional Hooks
444
445 | Hook                                         | Description                                                                 |
446 | -------------------------------------------- | ---------------------------------------------------------------------------- |
447 | `useReducer`_(reducer, initialArg, init)_    |                                                                              |
448 | `useCallback`_(() => { ... })_               |                                                                              |
449 | `useMemo`_(() => { ... })_                   |                                                                              |
450 | `useRef`_(initialValue)_                     |                                                                              |
451 | `useImperativeHandle`_(ref, () => { ... })_  |                                                                              |
452 | `useLayoutEffect`                            | identical to `useEffect`, but it fires synchronously after all DOM mutations |
453 | `useDebugValue`_(value)_                     | display a label for custom hooks in React DevTools                           |
454
455 Full details: [Additional Hooks](https://reactjs.org/docs/hooks-reference.html#additional-hooks)
456
457 DOM nodes
458 ---------
459 {: .-two-column}
460
461 ### References
462
463 ```jsx
464 class MyComponent extends Component {
465   render () {
466     return <div>
467       <input ref={el => this.input = el} />
468     </div>
469   }
470
471   componentDidMount () {
472     this.input.focus()
473   }
474 }
475 ```
476 {: data-line="4,9"}
477
478 Allows access to DOM nodes.
479
480 See: [Refs and the DOM](https://reactjs.org/docs/refs-and-the-dom.html)
481
482 ### DOM Events
483
484 ```jsx
485 class MyComponent extends Component {
486   render () {
487     <input type="text"
488         value={this.state.value}
489         onChange={event => this.onChange(event)} />
490   }
491
492   onChange (event) {
493     this.setState({ value: event.target.value })
494   }
495 }
496 ```
497 {: data-line="5,9"}
498
499 Pass functions to attributes like `onChange`.
500
501 See: [Events](https://reactjs.org/docs/events.html)
502
503 ## Other features
504
505 ### Transferring props
506
507 ```html
508 <VideoPlayer src="video.mp4" />
509 ```
510 {: .-setup}
511
512 ```jsx
513 class VideoPlayer extends Component {
514   render () {
515     return <VideoEmbed {...this.props} />
516   }
517 }
518 ```
519 {: data-line="3"}
520
521 Propagates `src="..."` down to the sub-component.
522
523 See [Transferring props](http://facebook.github.io/react/docs/transferring-props.html)
524
525 ### Top-level API
526
527 ```jsx
528 React.createClass({ ... })
529 React.isValidElement(c)
530 ```
531
532 ```jsx
533 ReactDOM.render(<Component />, domnode, [callback])
534 ReactDOM.unmountComponentAtNode(domnode)
535 ```
536
537 ```jsx
538 ReactDOMServer.renderToString(<Component />)
539 ReactDOMServer.renderToStaticMarkup(<Component />)
540 ```
541
542 There are more, but these are most common.
543
544 See: [React top-level API](https://reactjs.org/docs/react-api.html)
545
546 JSX patterns
547 ------------
548 {: .-two-column}
549
550 ### Style shorthand
551
552 ```jsx
553 const style = { height: 10 }
554 return <div style={style}></div>
555 ```
556
557 ```jsx
558 return <div style={{ margin: 0, padding: 0 }}></div>
559 ```
560
561 See: [Inline styles](https://reactjs.org/tips/inline-styles.html)
562
563 ### Inner HTML
564
565 ```jsx
566 function markdownify() { return "<p>...</p>"; }
567 <div dangerouslySetInnerHTML={{__html: markdownify()}} />
568 ```
569
570 See: [Dangerously set innerHTML](https://reactjs.org/tips/dangerously-set-inner-html.html)
571
572 ### Lists
573
574 ```jsx
575 class TodoList extends Component {
576   render () {
577     const { items } = this.props
578
579     return <ul>
580       {items.map(item =>
581         <TodoItem item={item} key={item.key} />)}
582     </ul>
583   }
584 }
585 ```
586 {: data-line="6,7"}
587
588 Always supply a `key` property.
589
590 ### Conditionals
591
592 ```jsx
593 <Fragment>
594   {showMyComponent
595     ? <MyComponent />
596     : <OtherComponent />}
597 </Fragment>
598 ```
599
600 ### Short-circuit evaluation
601
602 ```jsx
603 <Fragment>
604   {showPopup && <Popup />}
605   ...
606 </Fragment>
607 ```
608
609 New features
610 ------------
611 {: .-three-column}
612
613 ### Returning multiple elements
614
615 You can return multiple elements as arrays or fragments.
616
617 #### Arrays
618
619 ```js
620 render () {
621   // Don't forget the keys!
622   return [
623     <li key="A">First item</li>,
624     <li key="B">Second item</li>
625   ]
626 }
627 ```
628 {: data-line="3,4,5,6"}
629
630 #### Fragments
631 ```js
632 render () {
633   return (
634     <Fragment>
635       <li>First item</li>
636       <li>Second item</li>
637     </Fragment>
638   )
639 }
640 ```
641 {: data-line="3,4,5,6,7,8"}
642
643 See: [Fragments and strings](https://reactjs.org/blog/2017/09/26/react-v16.0.html#new-render-return-types-fragments-and-strings)
644
645 ### Returning strings
646
647 ```js
648 render() {
649   return 'Look ma, no spans!';
650 }
651 ```
652 {: data-line="2"}
653
654 You can return just a string.
655
656 See: [Fragments and strings](https://reactjs.org/blog/2017/09/26/react-v16.0.html#new-render-return-types-fragments-and-strings)
657
658 ### Errors
659
660 ```js
661 class MyComponent extends Component {
662   ···
663   componentDidCatch (error, info) {
664     this.setState({ error })
665   }
666 }
667 ```
668 {: data-line="3,4,5"}
669
670 Catch errors via `componentDidCatch`. (React 16+)
671
672 See: [Error handling in React 16](https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html)
673
674 ### Portals
675
676 ```js
677 render () {
678   return React.createPortal(
679     this.props.children,
680     document.getElementById('menu')
681   )
682 }
683 ```
684 {: data-line="2,3,4,5"}
685
686 This renders `this.props.children` into any location in the DOM.
687
688 See: [Portals](https://reactjs.org/docs/portals.html)
689
690 ### Hydration
691
692 ```js
693 const el = document.getElementById('app')
694 ReactDOM.hydrate(<App />, el)
695 ```
696 {: data-line="2"}
697
698 Use `ReactDOM.hydrate` instead of using `ReactDOM.render` if you're rendering over the output of [ReactDOMServer](https://reactjs.org/docs/react-dom-server.html).
699
700 See: [Hydrate](https://reactjs.org/docs/react-dom.html#hydrate)
701
702 Property validation
703 -------------------
704 {: .-three-column}
705
706 ### PropTypes
707
708 ```js
709 import PropTypes from 'prop-types'
710 ```
711 {: .-setup}
712
713 See: [Typechecking with PropTypes](https://reactjs.org/docs/typechecking-with-proptypes.html)
714
715 | Key   | Description |
716 | ----- | ----------- |
717 | `any` | Anything    |
718
719 #### Basic
720
721 | Key      | Description   |
722 | -------- | ------------- |
723 | `string` |               |
724 | `number` |               |
725 | `func`   | Function      |
726 | `bool`   | True or false |
727
728 #### Enum
729
730 | Key                       | Description |
731 | ------------------------- | ----------- |
732 | `oneOf`_(any)_            | Enum types  |
733 | `oneOfType`_(type array)_ | Union       |
734
735 #### Array
736
737 | Key              | Description |
738 | ---------------- | ----------- |
739 | `array`          |             |
740 | `arrayOf`_(...)_ |             |
741
742 #### Object
743
744 | Key                 | Description                          |
745 | ------------------- | ------------------------------------ |
746 | `object`            |                                      |
747 | `objectOf`_(...)_   | Object with values of a certain type |
748 | `instanceOf`_(...)_ | Instance of a class                  |
749 | `shape`_(...)_      |                                      |
750
751 #### Elements
752
753 | Key       | Description   |
754 | --------- | ------------- |
755 | `element` | React element |
756 | `node`    | DOM node      |
757
758 #### Required
759
760 | Key                | Description |
761 | ------------------ | ----------- |
762 | `(···).isRequired` | Required    |
763
764 ### Basic types
765
766 ```jsx
767 MyComponent.propTypes = {
768   email:      PropTypes.string,
769   seats:      PropTypes.number,
770   callback:   PropTypes.func,
771   isClosed:   PropTypes.bool,
772   any:        PropTypes.any
773 }
774 ```
775
776 ### Required types
777
778 ```jsx
779 MyCo.propTypes = {
780   name:  PropTypes.string.isRequired
781 }
782 ```
783
784 ### Elements
785
786 ```jsx
787 MyCo.propTypes = {
788   // React element
789   element: PropTypes.element,
790
791   // num, string, element, or an array of those
792   node: PropTypes.node
793 }
794 ```
795
796 ### Enumerables (oneOf)
797
798 ```jsx
799 MyCo.propTypes = {
800   direction: PropTypes.oneOf([
801     'left', 'right'
802   ])
803 }
804 ```
805
806 ### Arrays and objects
807
808 ```jsx
809 MyCo.propTypes = {
810   list: PropTypes.array,
811   ages: PropTypes.arrayOf(PropTypes.number),
812   user: PropTypes.object,
813   user: PropTypes.objectOf(PropTypes.number),
814   message: PropTypes.instanceOf(Message)
815 }
816 ```
817
818 ```jsx
819 MyCo.propTypes = {
820   user: PropTypes.shape({
821     name: PropTypes.string,
822     age:  PropTypes.number
823   })
824 }
825 ```
826
827 Use `.array[Of]`, `.object[Of]`, `.instanceOf`, `.shape`.
828
829 ### Custom validation
830
831 ```jsx
832 MyCo.propTypes = {
833   customProp: (props, key, componentName) => {
834     if (!/matchme/.test(props[key])) {
835       return new Error('Validation failed!')
836     }
837   }
838 }
839 ```
840
841 Also see
842 --------
843
844 * [React website](https://reactjs.org) _(reactjs.org)_
845 * [React cheatsheet](https://reactcheatsheet.com/) _(reactcheatsheet.com)_
846 * [Awesome React](https://github.com/enaqx/awesome-react) _(github.com)_
847 * [React v0.14 cheatsheet](react@0.14) _Legacy version_
848
849 {%endraw%}