@samitouri / QOS-React / commits / 455d2d1b48

New Documentation

Kevin Lacker committed Oct 21, 2016 at 20:58 UTC 455d2d1b48e5cdaeac5d0b4fd92b29b4d52bcaec
355 files changed +7520 -27325
.gitignore
+1 -1
@@ -15,7 +15,7 @@ docs/code
15 docs/_site
16 docs/.sass-cache
17 docs/js/*
18 -docs/downloads
18 +docs/downloads/*.zip
19 docs/vendor/bundle
20 examples/shared/*.js
21 examples/**/bundle.js
docs/README.md
+1 -1
@@ -38,7 +38,7 @@ $ cd react/docs
38 $ bundle exec rake
39 $ bundle exec rake fetch_remotes
40 $ bundle exec jekyll serve -w
41 -$ open http://localhost:4000/react/
41 +$ open http://localhost:4000/react/index.html
42 ```
43
44 We use [SASS](http://sass-lang.com/) (with [Bourbon](http://bourbon.io/)) for our CSS, and we use JSX to transform some of our JS.
docs/_config.yml
+10 -3
@@ -20,6 +20,12 @@ defaults:
20 type: pages
21 values:
22 sectionid: blog
23 +- scope:
24 + path: tutorial
25 + type: pages
26 + values:
27 + layout: tutorial
28 + sectionid: tutorial
29 - scope:
30 path: docs
31 type: pages
@@ -27,15 +33,16 @@ defaults:
33 layout: docs
34 sectionid: docs
35 - scope:
30 - path: tips
36 + path: contributing
37 type: pages
38 values:
39 sectionid: docs
40 - scope:
35 - path: contributing
41 + path: community
42 type: pages
43 values:
38 - sectionid: docs
44 + layout: community
45 + sectionid: community
46 exclude:
47 - Gemfile
48 - Gemfile.lock
docs/_data/nav_community.yml new
+14
@@ -0,0 +1,14 @@
1 +- title: Community Resources
2 + items:
3 + - id: support
4 + title: Where To Get Support
5 + - id: conferences
6 + title: Conferences
7 + - id: videos
8 + title: Videos
9 + - id: complementary-tools
10 + title: Complementary Tools
11 + href: https://github.com/facebook/react/wiki/Complementary-Tools
12 + - id: examples
13 + title: Examples
14 + href: https://github.com/facebook/react/wiki/Examples
docs/_data/nav_docs.yml
+77 -98
@@ -1,104 +1,83 @@
1 - title: Quick Start
2 items:
3 - - id: getting-started
4 - title: Getting Started
5 - - id: tutorial
6 - title: Tutorial
7 - - id: thinking-in-react
8 - title: Thinking in React
9 -- title: Community Resources
3 + - id: installation
4 + title: Installation
5 + - id: hello-world
6 + title: Hello World
7 + - id: introducing-jsx
8 + title: Introducing JSX
9 + - id: rendering-elements
10 + title: Rendering Elements
11 + - id: components-and-props
12 + title: Components and Props
13 + - id: state-and-lifecycle
14 + title: State and Lifecycle
15 + - id: handling-events
16 + title: Handling Events
17 + - id: conditional-rendering
18 + title: Conditional Rendering
19 + - id: lists-and-keys
20 + title: Lists and Keys
21 + - id: forms
22 + title: Forms
23 + - id: lifting-state-up
24 + title: Lifting State Up
25 + - id: composition-vs-inheritance
26 + title: Composition vs Inheritance
27 + - id: thinking-in-react
28 + title: Thinking In React
29 +- title: Advanced Guides
30 items:
11 - - id: conferences
12 - title: Conferences
13 - - id: videos
14 - title: Videos
15 - - id: complementary-tools
16 - title: Complementary Tools
17 - href: https://github.com/facebook/react/wiki/Complementary-Tools
18 - - id: examples
19 - title: Examples
20 - href: https://github.com/facebook/react/wiki/Examples
21 -- title: Guides
22 - items:
23 - - id: why-react
24 - title: Why React?
25 - - id: displaying-data
26 - title: Displaying Data
27 - subitems:
31 - id: jsx-in-depth
29 - title: JSX in Depth
30 - - id: jsx-spread
31 - title: JSX Spread Attributes
32 - - id: jsx-gotchas
33 - title: JSX Gotchas
34 - - id: interactivity-and-dynamic-uis
35 - title: Interactivity and Dynamic UIs
36 - - id: multiple-components
37 - title: Multiple Components
38 - - id: reusable-components
39 - title: Reusable Components
40 - - id: transferring-props
41 - title: Transferring Props
42 - - id: forms
43 - title: Forms
44 - - id: working-with-the-browser
45 - title: Working With the Browser
46 - subitems:
47 - - id: more-about-refs
48 - title: Refs to Components
49 - - id: tooling-integration
50 - title: Tooling Integration
51 - subitems:
52 - - id: language-tooling
53 - title: Language Tooling
54 - - id: package-management
55 - title: Package Management
56 - - id: environments
57 - title: Server-side Environments
58 - - id: addons
59 - title: Add-Ons
60 - subitems:
61 - - id: animation
62 - title: Animation
63 - - id: two-way-binding-helpers
64 - title: Two-Way Binding Helpers
65 - - id: test-utils
66 - title: Test Utilities
67 - - id: clone-with-props
68 - title: Cloning Elements
69 - - id: create-fragment
70 - title: Keyed Fragments
71 - - id: update
72 - title: Immutability Helpers
73 - - id: pure-render-mixin
74 - title: PureRenderMixin
75 - - id: perf
76 - title: Performance Tools
77 - - id: shallow-compare
78 - title: Shallow Compare
79 - - id: advanced-performance
80 - title: Advanced Performance
81 - - id: context
82 - title: Context
32 + title: JSX In Depth
33 + - id: typechecking-with-proptypes
34 + title: Typechecking With PropTypes
35 + - id: refs-and-the-dom
36 + title: Refs and the DOM
37 + - id: optimizing-performance
38 + title: Optimizing Performance
39 + - id: react-without-es6
40 + title: React Without ES6
41 + - id: react-without-jsx
42 + title: React Without JSX
43 + - id: reconciliation
44 + title: Reconciliation
45 + - id: context
46 + title: Context
47 + - id: web-components
48 + title: Web Components
49 - title: Reference
50 items:
85 - - id: top-level-api
86 - title: Top-Level API
87 - - id: component-api
88 - title: Component API
89 - - id: component-specs
90 - title: Component Specs and Lifecycle
91 - - id: tags-and-attributes
92 - title: Supported Tags and Attributes
93 - - id: events
94 - title: Event System
95 - - id: dom-differences
96 - title: DOM Differences
97 - - id: special-non-dom-attributes
98 - title: Special Non-DOM Attributes
99 - - id: reconciliation
100 - title: Reconciliation
101 - - id: webcomponents
102 - title: Web Components
103 - - id: glossary
104 - title: React (Virtual) DOM Terminology
51 + - id: react-api
52 + title: React
53 + subitems:
54 + - id: react-component
55 + title: React.Component
56 + - id: react-dom
57 + title: ReactDOM
58 + - id: react-dom-server
59 + title: ReactDOMServer
60 + - id: dom-elements
61 + title: DOM Elements
62 + - id: events
63 + title: SyntheticEvent
64 + - id: addons
65 + title: Add-Ons
66 + subitems:
67 + - id: perf
68 + title: Performance Tools
69 + - id: test-utils
70 + title: Test Utilities
71 + - id: animation
72 + title: Animation
73 + - id: create-fragment
74 + title: Keyed Fragments
75 + - id: update
76 + title: Immutability Helpers
77 + - id: pure-render-mixin
78 + title: PureRenderMixin
79 + - id: shallow-compare
80 + title: Shallow Compare
81 + - id: two-way-binding-helpers
82 + title: Two-way Binding Helpers
83 +
docs/_data/nav_tips.yml deleted
-38
@@ -1,38 +0,0 @@
1 -- title: Tips
2 - items:
3 - - id: introduction
4 - title: Introduction
5 - - id: inline-styles
6 - title: Inline Styles
7 - - id: if-else-in-JSX
8 - title: If-Else in JSX
9 - - id: self-closing-tag
10 - title: Self-Closing Tag
11 - - id: maximum-number-of-jsx-root-nodes
12 - title: Maximum Number of JSX Root Nodes
13 - - id: style-props-value-px
14 - title: Shorthand for Specifying Pixel Values in style props
15 - - id: children-props-type
16 - title: Type of the Children props
17 - - id: controlled-input-null-value
18 - title: Value of null for Controlled Input
19 - - id: componentWillReceiveProps-not-triggered-after-mounting
20 - title: componentWillReceiveProps Not Triggered After Mounting
21 - - id: props-in-getInitialState-as-anti-pattern
22 - title: Props in getInitialState Is an Anti-Pattern
23 - - id: dom-event-listeners
24 - title: DOM Event Listeners in a Component
25 - - id: initial-ajax
26 - title: Load Initial Data via AJAX
27 - - id: false-in-jsx
28 - title: False in JSX
29 - - id: communicate-between-components
30 - title: Communicate Between Components
31 - - id: expose-component-functions
32 - title: Expose Component Functions
33 - - id: children-undefined
34 - title: this.props.children undefined
35 - - id: use-react-with-other-libraries
36 - title: Use React with Other Libraries
37 - - id: dangerously-set-inner-html
38 - title: Dangerously Set innerHTML
docs/_data/nav_tutorial.yml new
+71
@@ -0,0 +1,71 @@
1 +- title: Tutorial
2 + items:
3 + - id: tutorial
4 + title: Overview
5 + subitems:
6 + - id: what-were-building
7 + title: What We're Building
8 + href: /react/tutorial/tutorial.html#what-were-building
9 + forceInternal: true
10 + - id: what-is-react
11 + title: What is React?
12 + href: /react/tutorial/tutorial.html#what-is-react
13 + forceInternal: true
14 + - id: getting-started
15 + title: Getting Started
16 + href: /react/tutorial/tutorial.html#getting-started
17 + forceInternal: true
18 + - id: passing-data-through-props
19 + title: Passing Data Through Props
20 + href: /react/tutorial/tutorial.html#passing-data-through-props
21 + forceInternal: true
22 + - id: an-interactive-component
23 + title: An Interactive Component
24 + href: /react/tutorial/tutorial.html#an-interactive-component
25 + forceInternal: true
26 + - id: developer-tools
27 + title: Developer Tools
28 + href: /react/tutorial/tutorial.html#developer-tools
29 + forceInternal: true
30 + - id: lifting-state-up
31 + title: Lifting State Up
32 + href: /react/tutorial/tutorial.html#lifting-state-up
33 + forceInternal: true
34 + subitems:
35 + - id: why-immutability-is-important
36 + title: Why Immutability Is Important
37 + href: /react/tutorial/tutorial.html#why-immutability-is-important
38 + forceInternal: true
39 + - id: functional-components
40 + title: Functional Components
41 + href: /react/tutorial/tutorial.html#functional-components
42 + forceInternal: true
43 + - id: taking-turns
44 + title: Taking Turns
45 + href: /react/tutorial/tutorial.html#taking-turns
46 + forceInternal: true
47 + - id: declaring-a-winner
48 + title: Declaring a Winner
49 + href: /react/tutorial/tutorial.html#declaring-a-winner
50 + forceInternal: true
51 + - id: storing-a-history
52 + title: Storing A History
53 + href: /react/tutorial/tutorial.html#storing-a-history
54 + forceInternal: true
55 + subitems:
56 + - id: showing-the-moves
57 + title: Showing the Moves
58 + href: /react/tutorial/tutorial.html#showing-the-moves
59 + forceInternal: true
60 + - id: keys
61 + title: Keys
62 + href: /react/tutorial/tutorial.html#keys
63 + forceInternal: true
64 + - id: implementing-time-travel
65 + title: Implementing Time Travel
66 + href: /react/tutorial/tutorial.html#implementing-time-travel
67 + forceInternal: true
68 + - id: wrapping-up
69 + title: Wrapping Up
70 + href: /react/tutorial/tutorial.html#wrapping-up
71 + forceInternal: true
docs/_includes/footer.html new
+41
@@ -0,0 +1,41 @@
1 +<footer class="nav-footer">
2 + <section class="sitemap">
3 + <a href="/react/" class="nav-home">
4 + </a>
5 + <div>
6 + <h5><a href="/react/docs/">Docs</a></h5>
7 + <a href="/react/docs/hello-world.html">Quick Start</a>
8 + <a href="/react/docs/thinking-in-react.html">Thinking in React</a>
9 + <a href="/react/tutorial/tutorial.html">Tutorial</a>
10 + <a href="/react/docs/jsx-in-depth.html">Advanced Guides</a>
11 + </div>
12 + <div>
13 + <h5><a href="/react/community/support.html">Community</a></h5>
14 + <a href="http://stackoverflow.com/questions/tagged/reactjs" target="_blank">Stack Overflow</a>
15 + <a href="https://discuss.reactjs.org/" target="_blank">Discussion Forum</a>
16 + <a href="https://discord.gg/0ZcbPKXt5bZjGY5n" target="_blank">Reactiflux Chat</a>
17 + <a href="https://www.facebook.com/react" target="_blank">Facebook</a>
18 + <a href="https://twitter.com/reactjs" target="_blank">Twitter</a>
19 + </div>
20 + <div>
21 + <h5><a href="/react/community/support.html">Resources</a></h5>
22 + <a href="/react/community/conferences.html">Conferences</a>
23 + <a href="/react/community/videos.html">Videos</a>
24 + <a href="https://github.com/facebook/react/wiki/Examples" target="_blank">Examples</a>
25 + <a href="https://github.com/facebook/react/wiki/Complementary-Tools" target="_blank">Complementary Tools</a>
26 + </div>
27 + <div>
28 + <h5>More</h5>
29 + <a href="/react/blog/">Blog</a>
30 + <a href="https://github.com/facebook/react" target="_blank">GitHub</a>
31 + <a href="http://facebook.github.io/react-native/" target="_blank">React Native</a>
32 + <a href="/react/acknowledgements.html">Acknowledgements</a>
33 + </div>
34 + </section>
35 + <a href="https://code.facebook.com/projects/" target="_blank" class="fbOpenSource">
36 + <img src="/react/img/oss_logo.png" alt="Facebook Open Source" width="170" height="45"/>
37 + </a>
38 + <section class="copyright">
39 + Copyright © {{ site.time | date: '%Y' }} Facebook Inc.
40 + </section>
41 +</footer>
docs/_includes/hero.html new
+13
@@ -0,0 +1,13 @@
1 +<div class="hero">
2 + <div class="wrap">
3 + <div class="text"><strong>React</strong></div>
4 + <div class="minitext">
5 + A JavaScript library for building user interfaces
6 + </div>
7 +
8 + <div class="buttons-unit">
9 + <a href="/react/docs/hello-world.html" class="button">Get Started</a>
10 + <a href="/react/tutorial/tutorial.html" class="button">Take the Tutorial</a>
11 + </div>
12 + </div>
13 +</div>
docs/_includes/nav_community.html new
+24
@@ -0,0 +1,24 @@
1 +<div class="nav-docs">
2 + <!-- Community Nav -->
3 + {% for section in site.data.nav_community %}
4 + <div class="nav-docs-section">
5 + <h3>{{ section.title }}</h3>
6 + <ul>
7 + {% for item in section.items %}
8 + <li>
9 + {{ item | community_sidebar_link }}
10 + {% if item.subitems %}
11 + <ul>
12 + {% for subitem in item.subitems %}
13 + <li>
14 + {{ subitem | community_sidebar_link }}
15 + </li>
16 + {% endfor %}
17 + </ul>
18 + {% endif %}
19 + </li>
20 + {% endfor %}
21 + </ul>
22 + </div>
23 + {% endfor %}
24 +</div>
docs/_includes/nav_docs.html
+3 -16
@@ -6,12 +6,12 @@
6 <ul>
7 {% for item in section.items %}
8 <li>
9 - {{ item | sidebar_item_link}}
9 + {{ item | docs_sidebar_link}}
10 {% if item.subitems %}
11 <ul>
12 {% for subitem in item.subitems %}
13 <li>
14 - {{ subitem | sidebar_item_link}}
14 + {{ subitem | docs_sidebar_link }}
15 </li>
16 {% endfor %}
17 </ul>
@@ -22,20 +22,6 @@
22 </div>
23 {% endfor %}
24
25 - <!-- Tips Nav -->
26 - {% for section in site.data.nav_tips %}
27 - <div class="nav-docs-section">
28 - <h3>{{ section.title }}</h3>
29 - <ul>
30 - {% for item in section.items %}
31 - <li>
32 - <a href="/react/tips/{{ item.id }}.html"{% if page.id == item.id %} class="active"{% endif %}>{{ item.title }}</a>
33 - </li>
34 - {% endfor %}
35 - </ul>
36 - </div>
37 - {% endfor %}
38 -
25 <!-- Contributing Nav -->
26 {% for section in site.data.nav_contributing %}
27 <div class="nav-docs-section">
@@ -49,4 +35,5 @@
35 </ul>
36 </div>
37 {% endfor %}
38 +
39 </div>
docs/_includes/nav_tutorial.html new
+24
@@ -0,0 +1,24 @@
1 +<div class="nav-docs">
2 + <!-- Tutorial Nav -->
3 + {% for section in site.data.nav_tutorial %}
4 + <div class="nav-docs-section">
5 + <h3>{{ section.title }}</h3>
6 + <ul>
7 + {% for item in section.items %}
8 + <li>
9 + {{ item | tutorial_sidebar_link }}
10 + {% if item.subitems %}
11 + <ul>
12 + {% for subitem in item.subitems %}
13 + <li>
14 + {{ subitem | tutorial_sidebar_link }}
15 + </li>
16 + {% endfor %}
17 + </ul>
18 + {% endif %}
19 + </li>
20 + {% endfor %}
21 + </ul>
22 + </div>
23 + {% endfor %}
24 +</div>
docs/_includes/navigation.html new
+23
@@ -0,0 +1,23 @@
1 +<div class="nav-main">
2 + <div class="wrap">
3 + <a class="nav-home" href="/react/index.html">
4 + <img class="nav-logo" src="/react/img/logo.svg" width="36" height="36">
5 + React
6 + </a>
7 + <div class="nav-lists">
8 + <ul class="nav-site nav-site-internal">
9 + <li><a href="/react/docs/hello-world.html"{% if page.sectionid == 'docs' or page.sectionid == 'tips' or page.sectionid == 'contributing' %} class="active"{% endif %}>Docs</a></li>
10 + <li><a href="/react/tutorial/tutorial.html"{% if page.sectionid == 'tutorial' %} class="active"{% endif %}>Tutorial</a></li>
11 + <li><a href="/react/community/support.html"{% if page.sectionid == 'community' %} class="active"{% endif %}>Community</a></li>
12 + <li><a href="/react/blog/"{% if page.sectionid == 'blog' %} class="active"{% endif %}>Blog</a></li>
13 + <li class="nav-site-search">
14 + <input id="algolia-doc-search" type="text" placeholder="Search docs..." />
15 + </li>
16 + </ul>
17 + <ul class="nav-site nav-site-external">
18 + <li><a href="https://github.com/facebook/react">GitHub</a></li>
19 + <li><a href="https://facebook.github.io/react-native/">React Native</a></li>
20 + </ul>
21 + </div>
22 + </div>
23 +</div>
docs/_layouts/community.html new
+29
@@ -0,0 +1,29 @@
1 +---
2 +layout: default
3 +sectionid: community
4 +---
5 +
6 +<section class="content wrap communityContent">
7 + <div class="inner-content">
8 + <a class="edit-page-link"
9 + href="https://github.com/facebook/react/tree/master/docs/{{ page.path }}"
10 + target="_blank">Edit on GitHub</a>
11 + <h1>
12 + {{ page.title }}
13 + </h1>
14 + <div class="subHeader">{{ page.description }}</div>
15 +
16 + {{ content }}
17 +
18 + <div class="docs-prevnext">
19 + {% if page.prev %}
20 + <a class="docs-prev" href="/react/community/{{ page.prev }}">&larr; Prev</a>
21 + {% endif %}
22 + {% if page.next %}
23 + <a class="docs-next" href="/react/community/{{ page.next }}">Next &rarr;</a>
24 + {% endif %}
25 + </div>
26 + </div>
27 +
28 + {% include nav_community.html %}
29 +</section>
docs/_layouts/contributing.html
+2 -2
@@ -4,8 +4,6 @@ sectionid: contributing
4 ---
5
6 <section class="content wrap documentationContent">
7 - {% include nav_docs.html %}
8 -
7 <div class="inner-content">
8 <h1>{{ page.title }}</h1>
9 <div class="subHeader">{{ page.description }}</div>
@@ -20,4 +18,6 @@ sectionid: contributing
18 {% endif %}
19 </div>
20 </div>
21 +
22 + {% include nav_docs.html %}
23 </section>
docs/_layouts/default.html
+18 -54
@@ -1,16 +1,26 @@
1 +{% if page.excerpt %}
2 +{% assign type = 'article' %}
3 +{% assign sectionTitle = 'React Blog' %}
4 +{% assign description = page.excerpt | remove: '<p>' | remove: '</p>' %}
5 +{% else %}
6 +{% assign type = 'website' %}
7 +{% assign sectionTitle = 'React' %}
8 +{% assign description = 'A JavaScript library for building user interfaces' %}
9 +{% endif %}
10 +{% assign title = page.title | append: ' - ' | append: sectionTitle %}
11 <!DOCTYPE html>
12 <!--[if IE]><![endif]-->
13 <html>
14 <head>
15 <meta charset="utf-8">
16 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
7 - <title>{{ page.title }} | React</title>
8 - <meta name="viewport" content="width=device-width">
9 - <meta property="og:title" content="{{ page.title }} | React">
10 - <meta property="og:type" content="website">
17 + <title>{{ title }}</title>
18 + <meta name="viewport" content="width=device-width, initial-scale=1">
19 + <meta property="og:title" content="{{ title }}">
20 + <meta property="og:type" content="{{ type }}">
21 <meta property="og:url" content="https://facebook.github.io/react{{ page.url }}">
22 <meta property="og:image" content="https://facebook.github.io/react/img/logo_og.png">
13 - <meta property="og:description" content="A JavaScript library for building user interfaces">
23 + <meta property="og:description" content="{{ description }}">
24 <meta property="fb:app_id" content="623268441017527">
25
26 <link rel="shortcut icon" href="/react/favicon.ico">
@@ -43,60 +53,14 @@
53
54 <div class="container">
55
46 - <div class="nav-main">
47 - <div class="wrap">
48 - <a class="nav-home" href="/react/index.html">
49 - <img class="nav-logo" src="/react/img/logo.svg" width="36" height="36">
50 - React
51 - </a>
52 - <ul class="nav-site nav-site-internal">
53 - <li><a href="/react/docs/getting-started.html"{% if page.sectionid == 'docs' or page.sectionid == 'tips' or page.sectionid == 'contributing' %} class="active"{% endif %}>Docs</a></li>
54 - <li><a href="/react/support.html"{% if page.id == 'support' %} class="active"{% endif %}>Support</a></li>
55 - <li><a href="/react/downloads.html"{% if page.id == 'downloads' %} class="active"{% endif %}>Download</a></li>
56 - <li><a href="/react/blog/"{% if page.sectionid == 'blog' %} class="active"{% endif %}>Blog</a></li>
57 - <li>
58 - <input id="algolia-doc-search" type="text" placeholder="Search docs..." />
59 - </li>
60 - </ul>
61 -
62 - <ul class="nav-site nav-site-external">
63 - <li><a href="https://github.com/facebook/react">GitHub</a></li>
64 - <li><a href="https://facebook.github.io/react-native/">React Native</a></li>
65 - </ul>
66 - </div>
67 - </div>
68 -
69 - {% if page.id == 'home' %}
70 - <div class="hero">
71 - <div class="wrap">
72 - <div class="text"><strong>React</strong></div>
73 - <div class="minitext">
74 - A JavaScript library for building user interfaces
75 - </div>
76 -
77 - <div class="buttons-unit">
78 - <a href="/react/docs/getting-started.html" class="button">Get Started</a>
79 - <a href="/react/downloads.html" class="button">Download React v{{site.react_version}}</a>
80 - </div>
81 - </div>
82 - </div>
83 - {% endif %}
56 + {% include navigation.html %}
57
58 {{ content }}
59
87 - <footer class="wrap">
88 - <div class="left">
89 - A Facebook &amp; Instagram collaboration.<br>
90 - <a href="/react/acknowledgements.html">Acknowledgements</a>
91 - </div>
92 - <div class="right">
93 - &copy; 2013&ndash;{{ site.time | date: '%Y' }} Facebook Inc.<br>
94 - Documentation licensed under <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>.
95 - </div>
96 - </footer>
60 + {% include footer.html %}
61 </div>
98 - <div id="fb-root"></div>
62
63 + <div id="fb-root"></div>
64 <script>
65 (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
66 (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
docs/_layouts/docs.html
+2 -2
@@ -4,8 +4,6 @@ sectionid: docs
4 ---
5
6 <section class="content wrap documentationContent">
7 - {% include nav_docs.html %}
8 -
7 <div class="inner-content">
8 <a class="edit-page-link" href="https://github.com/facebook/react/tree/master/docs/{{ page.path }}" target="_blank">Edit on GitHub</a>
9 <h1>
@@ -24,4 +22,6 @@ sectionid: docs
22 {% endif %}
23 </div>
24 </div>
25 +
26 + {% include nav_docs.html %}
27 </section>
docs/_layouts/hero.html new
+11
@@ -0,0 +1,11 @@
1 +---
2 +layout: default
3 +---
4 +
5 +{% if page.id == 'home' %}
6 + {% include hero.html %}
7 +{% endif %}
8 +
9 +<section class="content wrap">
10 + {{ content }}
11 +</section>
docs/_layouts/post.html
+2 -1
@@ -4,8 +4,9 @@ sectionid: blog
4 ---
5
6 <section class="content wrap blogContent">
7 - {% include nav_blog.html %}
7 +
8 <div class="inner-content">
9 {% include blog_post.html isPermalink="true" page=page content=content %}
10 </div>
11 + {% include nav_blog.html %}
12 </section>
docs/_layouts/tips.html deleted
-23
@@ -1,23 +0,0 @@
1 ----
2 -layout: default
3 -sectionid: tips
4 ----
5 -
6 -<section class="content wrap documentationContent">
7 - {% include nav_docs.html %}
8 -
9 - <div class="inner-content">
10 - <h1>{{ page.title }}</h1>
11 - <div class="subHeader">{{ page.description }}</div>
12 - {{ content }}
13 -
14 - <div class="docs-prevnext">
15 - {% if page.prev %}
16 - <a class="docs-prev" href="/react/tips/{{ page.prev }}">&larr; Prev</a>
17 - {% endif %}
18 - {% if page.next %}
19 - <a class="docs-next" href="/react/tips/{{ page.next }}">Next &rarr;</a>
20 - {% endif %}
21 - </div>
22 - </div>
23 -</section>
docs/_layouts/tutorial.html new
+29
@@ -0,0 +1,29 @@
1 +---
2 +layout: default
3 +sectionid: tutorial
4 +---
5 +
6 +<section class="content wrap documentationContent">
7 + {% include nav_tutorial.html %}
8 +
9 + <div class="inner-content">
10 + <a class="edit-page-link"
11 + href="https://github.com/facebook/react/tree/master/docs/{{ page.path }}"
12 + target="_blank">Edit on GitHub</a>
13 + <h1>
14 + {{ page.title }}
15 + </h1>
16 + <div class="subHeader">{{ page.description }}</div>
17 +
18 + {{ content }}
19 +
20 + <div class="docs-prevnext">
21 + {% if page.prev %}
22 + <a class="docs-prev" href="/react/tutorial/{{ page.prev }}">&larr; Prev</a>
23 + {% endif %}
24 + {% if page.next %}
25 + <a class="docs-next" href="/react/tutorial/{{ page.next }}">Next &rarr;</a>
26 + {% endif %}
27 + </div>
28 + </div>
29 +</section>
docs/_plugins/sidebar_item.rb
+22 -3
@@ -1,20 +1,39 @@
1 module Jekyll
2 module SidebarItemFilter
3 - def sidebar_item_link(item)
3 + def docs_sidebar_link(item)
4 + return sidebar_helper(item, 'docs')
5 + end
6 +
7 + def docs_old_sidebar_link(item)
8 + return sidebar_helper(item, 'docs-old')
9 + end
10 +
11 + def community_sidebar_link(item)
12 + return sidebar_helper(item, 'community')
13 + end
14 +
15 + def tutorial_sidebar_link(item)
16 + return sidebar_helper(item, 'tutorial')
17 + end
18 +
19 + def sidebar_helper(item, group)
20 + forceInternal = item["forceInternal"]
21 +
22 pageID = @context.registers[:page]["id"]
23 itemID = item["id"]
6 - href = item["href"] || "/react/docs/#{itemID}.html"
24 + href = item["href"] || "/react/#{group}/#{itemID}.html"
25 classes = []
26 if pageID == itemID
27 classes.push("active")
28 end
11 - if item["href"]
29 + if item["href"] && (forceInternal == nil)
30 classes.push("external")
31 end
32 className = classes.size > 0 ? " class=\"#{classes.join(' ')}\"" : ""
33
34 return "<a href=\"#{href}\"#{className}>#{item["title"]}</a>"
35 end
36 +
37 end
38 end
39
docs/_posts/2013-07-03-community-roundup-4.md
+1 -1
@@ -47,7 +47,7 @@ Over the past several weeks, members of our team, [Pete Hunt](http://www.petehun
47
48 [Pete Hunt](http://www.petehunt.net/) recorded himself implementing a simple `<Blink>` tag in React.
49
50 -<figure><iframe src="https://player.vimeo.com/video/67248575" width="500" height="340" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></figure>
50 +<figure><iframe src="https://player.vimeo.com/video/67248575" width="100%" height="340" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></figure>
51
52 ## Snake in React
53
docs/_posts/2013-07-23-community-roundup-5.md
+2 -2
@@ -68,14 +68,14 @@ React.renderComponent(
68
69 [Domenic Denicola](http://domenicdenicola.com/) wrote a slide deck about the great applications of ES6 features and one slide shows how we could use Template Strings to compile JSX at run-time without the need for a pre-processing phase.
70
71 -<figure><iframe src="https://www.slideshare.net/slideshow/embed_code/24187146?rel=0&startSlide=36" width="600" height="356" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="border:1px solid #CCC;border-width:1px 1px 0;margin-bottom:5px" allowfullscreen webkitallowfullscreen mozallowfullscreen> </iframe></figure>
71 +<figure><iframe src="https://www.slideshare.net/slideshow/embed_code/24187146?rel=0&startSlide=36" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="border:1px solid #CCC;border-width:1px 1px 0;margin-bottom:5px" allowfullscreen webkitallowfullscreen mozallowfullscreen> </iframe></figure>
72
73
74 ## React Presentation
75
76 [Tom Occhino](http://tomocchino.com/) and [Jordan Walke](https://github.com/jordwalke), React developers, did a presentation of React at Facebook Seattle's office. Check out the first 25 minutes for the presentation and the remaining 45 for a Q&A. I highly recommend you watching this video.
77
78 -<figure><iframe width="650" height="400" src="//www.youtube-nocookie.com/embed/XxVg_s8xAms" frameborder="0" allowfullscreen></iframe></figure>
78 +<figure><iframe width="100%" height="400" src="//www.youtube-nocookie.com/embed/XxVg_s8xAms" frameborder="0" allowfullscreen></iframe></figure>
79
80
81 ## Docs
docs/_posts/2013-10-3-community-roundup-9.md
+1 -2
@@ -29,7 +29,7 @@ We organized a React hackathon last week-end in the Facebook Seattle office. 50
29
30 The video will be available soon on the [JSConf EU website](http://2013.jsconf.eu/speakers/pete-hunt-react-rethinking-best-practices.html), but in the meantime, here are Pete's slides:
31
32 -<figure><iframe src="https://www.slideshare.net/slideshow/embed_code/26589373" width="550" height="450" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" allowfullscreen></iframe></figure>
32 +<figure><iframe src="https://www.slideshare.net/slideshow/embed_code/26589373" width="100%" height="450" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" allowfullscreen></iframe></figure>
33
34
35 ## Pump - Clojure bindings for React
@@ -96,4 +96,3 @@ var Table = React.createClass({
96 > You see that React components are defined using a regular JS object. Some properties and methods of the object such as render() have special meanings, the rest is upforgrabs.
97 >
98 > [Read the full article...](http://www.phpied.com/reactive-table/)
99 -
docs/_posts/2013-11-06-community-roundup-10.md
+1 -1
@@ -26,7 +26,7 @@ The best part is that no drastic changes have been required to support all those
26
27 [Pete Hunt](http://www.petehunt.net/)'s talk at JSConf EU 2013 is now available in video.
28
29 -<figure><iframe width="600" height="370" src="//www.youtube-nocookie.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe></figure>
29 +<figure><iframe width="100%" height="370" src="//www.youtube-nocookie.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe></figure>
30
31
32 ## Server-side React with PHP
docs/_posts/2013-11-18-community-roundup-11.md
+2 -2
@@ -9,7 +9,7 @@ This round-up is the proof that React has taken off from its Facebook's root: it
9
10 [Steve Luscher](https://github.com/steveluscher) working at [LeanPub](https://leanpub.com/) made a 30 min talk at [Super VanJS](https://twitter.com/vanjs). He does a remarkable job at explaining why React is so fast with very exciting demos using the HTML5 Audio API.
11
12 -<figure><iframe width="600" height="338" src="//www.youtube-nocookie.com/embed/1OeXsL5mr4g" frameborder="0" allowfullscreen></iframe></figure>
12 +<figure><iframe width="100%" height="338" src="//www.youtube-nocookie.com/embed/1OeXsL5mr4g" frameborder="0" allowfullscreen></iframe></figure>
13
14
15 ## React Tips
@@ -64,7 +64,7 @@ This round-up is the proof that React has taken off from its Facebook's root: it
64 >
65 > [Read the full article...](http://rz.scale-it.pl/2013/10/20/frontend_components_in_react.html)
66
67 -<figure><iframe src="https://docs.google.com/presentation/d/1JSFbjCuuexwOHCeHWBMNRIJdyfD2Z0ZQwX65WOWkfaI/embed?start=false" frameborder="0" width="600" height="468" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"> </iframe></figure>
67 +<figure><iframe src="https://docs.google.com/presentation/d/1JSFbjCuuexwOHCeHWBMNRIJdyfD2Z0ZQwX65WOWkfaI/embed?start=false" frameborder="0" width="100%" height="468" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"> </iframe></figure>
68
69
70 ## JSX
docs/_posts/2013-12-30-community-roundup-13.md
+2 -3
@@ -10,7 +10,7 @@ Happy holidays! This blog post is a little-late Christmas present for all the Re
10
11 [Pete Hunt](http://www.petehunt.net/) wrote three demos showing that React can be used to run 60fps native-like experiences on mobile web. A frosted glass effect, an image gallery with 3d animations and an infinite scroll view.
12
13 -<figure><iframe src="//player.vimeo.com/video/79659941" width="220" height="400" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></figure>
13 +<figure><iframe src="//player.vimeo.com/video/79659941" width="100%" height="400" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></figure>
14
15 [Try out the demos!](https://petehunt.github.io/react-touch/)
16
@@ -19,7 +19,7 @@ Happy holidays! This blog post is a little-late Christmas present for all the Re
19
20 [Stoyan Stefanov](http://www.phpied.com/) talked at Joe Dev On Tech about React. He goes over all the features of the library and ends with a concrete example.
21
22 -<figure><iframe width="560" height="315" src="//www.youtube-nocookie.com/embed/SMMRJif5QW0" frameborder="0" allowfullscreen></iframe></figure>
22 +<figure><iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/SMMRJif5QW0" frameborder="0" allowfullscreen></iframe></figure>
23
24
25 ## JSX: E4X The Good Parts
@@ -115,4 +115,3 @@ var MyComponent = React.createClass({
115 ## Random Tweet
116
117 <center><blockquote class="twitter-tweet" lang="en"><p>I may be starting to get annoying with this, but ReactJS is really exciting. I truly feel the virtual DOM is a game changer.</p>&mdash; Eric Florenzano (@ericflo) <a href="https://twitter.com/ericflo/statuses/413842834974732288">December 20, 2013</a></blockquote></center>
118 -
docs/_posts/2014-01-02-react-chrome-developer-tools.md
+1 -2
@@ -5,7 +5,7 @@ author: sebmarkbage
5
6 With the new year, we thought you'd enjoy some new tools for debugging React code. Today we're releasing the [React Developer Tools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi), an extension to the Chrome Developer Tools. [Download them from the Chrome Web Store](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi).
7
8 -<figure><iframe width="560" height="315" src="//www.youtube-nocookie.com/embed/Cey7BS6dE0M" frameborder="0" allowfullscreen></iframe></figure>
8 +<figure><iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/Cey7BS6dE0M" frameborder="0" allowfullscreen></iframe></figure>
9
10 You will get a new tab titled "React" in your Chrome DevTools. This tab shows you a list of the root React Components that are rendered on the page as well as the subcomponents that each root renders.
11
@@ -15,4 +15,3 @@ When you inspect a DOM element using the regular Elements tab, you can switch ov
15 <figure>[![](/react/img/blog/react-dev-tools.jpg)](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi)</figure>
16
17 We hope these tools will help your team better understand your component hierarchy and track down bugs. We're very excited about this initial launch and appreciate any feedback you may have. As always, we also accept [pull requests on GitHub](https://github.com/facebook/react-devtools).
18 -
docs/_posts/2014-01-06-community-roundup-14.md
+1 -1
@@ -28,7 +28,7 @@ React is only one-piece of your web application stack. [Mark Lussier](https://gi
28
29 ## React Rails Tutorial
30
31 -[Selem Delul](http://selem.im) bundled the [React Tutorial](/react/docs/tutorial.html) into a rails app. This is a good example on how to get started with a rails project.
31 +[Selem Delul](http://selem.im) bundled the [React Tutorial](/react/tutorial/tutorial.html) into a rails app. This is a good example on how to get started with a rails project.
32
33 > ```
34 git clone https://github.com/necrodome/react-rails-tutorial
docs/_posts/2014-02-05-community-roundup-15.md
+1 -1
@@ -34,7 +34,7 @@ React's one-way data-binding naturally lends itself to a functional programming
34
35 Pete also explains this in detail at his #MeteorDevShop talk (about 30 Minutes):
36
37 -<iframe width="560" height="315" src="//www.youtube-nocookie.com/embed/Lqcs6hPOcFw?start=2963" frameborder="0" allowfullscreen></iframe>
37 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/Lqcs6hPOcFw?start=2963" frameborder="0" allowfullscreen></iframe>
38
39
40
docs/_posts/2014-02-15-community-roundup-16.md
+1 -1
@@ -9,7 +9,7 @@ There have been many posts recently covering the <i>why</i> and <i>how</i> of Re
9 ## React in a nutshell
10 Got five minutes to pitch React to your coworkers? John Lynch ([@johnrlynch](https://twitter.com/johnrlynch)) put together [this excellent and refreshing slideshow](http://slid.es/johnlynch/reactjs):
11
12 -<iframe src="//slid.es/johnlynch/reactjs/embed" width="576" height="420" scrolling="no" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
12 +<iframe src="//slid.es/johnlynch/reactjs/embed" width="100%" height="420" scrolling="no" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
13
14
15
docs/_posts/2014-02-24-community-roundup-17.md
+1 -1
@@ -55,7 +55,7 @@ Rafał Cieślak ([@Ravicious](https://twitter.com/Ravicious)) wrote a [React ver
55
56 Emanuele shared this awesome demo video with us:
57
58 -<iframe width="560" height="315" src="//www.youtube-nocookie.com/embed/jYcpaemt90M" frameborder="0" allowfullscreen></iframe>
58 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/jYcpaemt90M" frameborder="0" allowfullscreen></iframe>
59
60
61
docs/_posts/2014-03-14-community-roundup-18.md
+1 -1
@@ -75,7 +75,7 @@ Ian Bicking ([@ianbicking](https://twitter.com/ianbicking)) of Mozilla Labs [exp
75
76 React was also recently mentioned at ng-conf, where the Angular team commented on React's concept of the virtual DOM:
77
78 -<iframe width="560" height="315" src="//www.youtube-nocookie.com/embed/srt3OBP2kGc?start=113" frameborder="0" allowfullscreen></iframe>
78 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/srt3OBP2kGc?start=113" frameborder="0" allowfullscreen></iframe>
79
80 ## React and Web Components
81
docs/_posts/2014-05-06-flux.md
+1 -1
@@ -5,7 +5,7 @@ author: [fisherwebdev, jingc]
5
6 We recently spoke at one of f8's breakout session about Flux, a data flow architecture that works well with React. Check out the video here:
7
8 -<figure><iframe width="560" height="315" src="//www.youtube-nocookie.com/embed/nYkdrAPrdcw?list=PLb0IAmt7-GS188xDYE-u1ShQmFFGbrk0v&start=621" frameborder="0" allowfullscreen></iframe></figure>
8 +<figure><iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/nYkdrAPrdcw?list=PLb0IAmt7-GS188xDYE-u1ShQmFFGbrk0v&start=621" frameborder="0" allowfullscreen></iframe></figure>
9
10 To summarize, Flux works well for us because the single directional data flow makes it easy to understand and modify an application as it becomes more complicated. We found that two-way data bindings lead to cascading updates, where changing one data model led to another data model updating, making it very difficult to predict what would change as the result of a single user interaction.
11
docs/_posts/2014-06-27-community-roundup-19.md
+1 -1
@@ -23,7 +23,7 @@ These are some of the links that often pop up on the #reactjs IRC channel. If yo
23
24 The core concepts React themselves is something very valuable that the community is exploring and pushing further. A year ago, we wouldn't have imagined something like [Bruce Hauman](http://rigsomelight.com)'s [Flappy Bird ClojureScript port](http://rigsomelight.com/2014/05/01/interactive-programming-flappy-bird-clojurescript.html), whose interactive programming has been made possible through React:
25
26 -<iframe width="560" height="315" src="//www.youtube-nocookie.com/embed/KZjFVdU8VLI" frameborder="0" allowfullscreen></iframe>
26 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/KZjFVdU8VLI" frameborder="0" allowfullscreen></iframe>
27
28 And don't forget [Pete Hunt](https://github.com/petehunt)'s Wolfenstein 3D rendering engine in React ([source code](https://github.com/petehunt/wolfenstein3D-react/blob/master/js/renderer.js#L183)). While it's nearly a year old, it's still a nice demo.
29
docs/_posts/2014-07-28-community-roundup-20.md
+3 -3
@@ -16,14 +16,14 @@ It's an exciting time for React as there are now more commits from open source c
16
17 At the last [JSConf.us](http://2014.jsconf.us/), Vjeux talked about the design decisions made in the API that allows it to scale to a large number of developers. If you don't have 20 minutes, take a look at the [annotated slides](https://speakerdeck.com/vjeux/why-does-react-scale-jsconf-2014).
18
19 -<iframe width="650" height="315" src="//www.youtube-nocookie.com/embed/D-ioDiacTm8" frameborder="0" allowfullscreen></iframe>
19 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/D-ioDiacTm8" frameborder="0" allowfullscreen></iframe>
20
21
22 ## Live Editing
23
24 One of the best features of React is that it provides the foundations to implement concepts that were otherwise extremely difficult, like server-side rendering, undo-redo, rendering to non-DOM environments like canvas... [Dan Abramov](https://twitter.com/dan_abramov) got hot code reloading working with webpack in order to [live edit a React project](https://gaearon.github.io/react-hot-loader/)!
25
26 -<iframe src="//player.vimeo.com/video/100010922" width="650" height="315" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
26 +<iframe src="//player.vimeo.com/video/100010922" width="100%" height="315" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
27
28
29 ## ReactIntl Mixin by Yahoo
@@ -63,7 +63,7 @@ If you missed the last [London React Meetup](http://www.meetup.com/London-React-
63 - React on Rails - How to use React with Ruby on Rails to build isomorphic apps
64 - Building an isomorphic, real-time to-do list with moped and node.js
65
66 -<iframe width="650" height="315" src="//www.youtube-nocookie.com/embed/CP3lvm5Ppqo" frameborder="0" allowfullscreen></iframe>
66 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/CP3lvm5Ppqo" frameborder="0" allowfullscreen></iframe>
67
68 In related news, the next [React SF Meetup](http://www.meetup.com/ReactJS-San-Francisco/events/195518392/) will be from Prezi: [“Immediate Mode on the Web: How We Implemented the Prezi Viewer in JavaScript”](https://medium.com/prezi-engineering/how-and-why-prezi-turned-to-javascript-56e0ca57d135). While not in React, their tech is really awesome and shares a lot of React's design principles and perf optimizations.
69
docs/_posts/2014-08-03-community-roundup-21.md
+1 -1
@@ -104,7 +104,7 @@ var parsedComponent = reactParser(html, React);
104
105 If you haven't yet tried out React, Jacob Rios did a Hangout where he covers the most important aspects and thankfully he recorded it!
106
107 -<iframe width="650" height="315" src="//www.youtube-nocookie.com/embed/lAn7GVoGlKU" frameborder="0" allowfullscreen></iframe>
107 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/lAn7GVoGlKU" frameborder="0" allowfullscreen></iframe>
108
109
110 ## Random Tweets
docs/_posts/2014-09-12-community-round-up-22.md
+2 -2
@@ -20,7 +20,7 @@ This has been an exciting summer as four big companies: Yahoo, Mozilla, Airbnb a
20
21 [Vjeux](http://blog.vjeux.com/), from the React team, gave a talk at OSCON on the history of React and the various optimizations strategies that are implemented. You can also check out the [annotated slides](https://speakerdeck.com/vjeux/oscon-react-architecture) or [Chris Dawson](http://thenewstack.io/author/chrisdawson/)'s notes titled [JavaScript’s History and How it Led To React](http://thenewstack.io/javascripts-history-and-how-it-led-to-reactjs/).
22
23 -<iframe width="650" height="315" src="//www.youtube-nocookie.com/embed/eCf5CquV_Bw" frameborder="0" allowfullscreen></iframe>
23 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/eCf5CquV_Bw" frameborder="0" allowfullscreen></iframe>
24
25
26 ## v8 optimizations
@@ -89,7 +89,7 @@ var Button = React.createClass({
89
90 If you are getting started with React, [Joe Maddalone](http://www.joemaddalone.com/) made a good tutorial on how to build your first component.
91
92 -<iframe width="650" height="200" src="//www.youtube-nocookie.com/embed/rFvZydtmsxM" frameborder="0" allowfullscreen></iframe>
92 +<iframe width="100%" height="200" src="//www.youtube-nocookie.com/embed/rFvZydtmsxM" frameborder="0" allowfullscreen></iframe>
93
94
95 ## Saving time & staying sane?
docs/_posts/2014-10-17-community-roundup-23.md
+3 -3
@@ -10,7 +10,7 @@ This round-up is a special edition on [Flux](https://facebook.github.io/flux/).
10
11 Facebook engineers [Jing Chen](https://github.com/jingc) and [Bill Fisher](https://github.com/fisherwebdev) gave a talk about Flux and React at [ForwardJS](http://forwardjs.com/), and how using an application architecture with a unidirectional data flow helped solve recurring bugs.
12
13 -<iframe width="650" height="315" src="//www.youtube-nocookie.com/embed/i__969noyAM" frameborder="0" allowfullscreen></iframe>
13 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/i__969noyAM" frameborder="0" allowfullscreen></iframe>
14
15 # Yahoo
16
@@ -102,7 +102,7 @@ undo: function() {
102
103 [Dan Abramov](https://twitter.com/dan_abramov) working at Stampsy made a talk about React and Flux. It's a very good overview of the concepts at play.
104
105 -<iframe src="//slides.com/danabramov/components-react-flux-wip/embed" width="650" height="315" scrolling="no" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
105 +<iframe src="//slides.com/danabramov/components-react-flux-wip/embed" width="100%" height="315" scrolling="no" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
106
107
108 ## React and Flux
@@ -144,7 +144,7 @@ undo: function() {
144
145 Last but not least, Flux and React ideas are not limited to JavaScript inside of the browser. The iOS team at Facebook re-implemented Newsfeed using very similar patterns.
146
147 -<iframe width="650" height="315" src="//www.youtube-nocookie.com/embed/XhXC4SKOGfQ" frameborder="0" allowfullscreen></iframe>
147 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/XhXC4SKOGfQ" frameborder="0" allowfullscreen></iframe>
148
149
150 ## Random Tweet
docs/_posts/2014-11-25-community-roundup-24.md
+4 -4
@@ -14,11 +14,11 @@ Murilo Pereira ([mpereira](https://github.com/mpereira)) tussles with the topic
14
15 I ([steveluscher](https://github.com/steveluscher)) spoke at Manning Publications' “Powered By JavaScript” Strangeloop pre-conf in St. Louis. There, I proposed a new notation to talk about development complexity – Big-Coffee Notation ☕(n) – and spoke about the features of React that help keep our Big-Coffee from going quadratic, as our user interfaces get more complex.
16
17 -<iframe width="560" height="315" src="//www.youtube-nocookie.com/embed/rI0GQc__0SM" frameborder="0" allowfullscreen></iframe>
17 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/rI0GQc__0SM" frameborder="0" allowfullscreen></iframe>
18
19 James Pearce ([jamesgpearce](https://github.com/jamesgpearce)) carried Big-Coffee all the way to Raleigh, NC. At the _All Things Open_ conference, he spoke about some of the design decisions that went into React, particularly those that lend themselves to simpler, more reliable code.
20
21 -<iframe width="560" height="315" src="//www.youtube-nocookie.com/embed/m2fuO2wl_3c" frameborder="0" allowfullscreen></iframe>
21 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/m2fuO2wl_3c" frameborder="0" allowfullscreen></iframe>
22
23 ## All About Isomorphism
24
@@ -38,7 +38,7 @@ Ryan Florence ([rpflorence](https://github.com/rpflorence])) and Michael Jackson
38
39 Jonathan Beebe ([somethingkindawierd](https://github.com/somethingkindawierd)) spoke about how he uses React to build tools that deliver hope to those trying to make the best of a bad situation. Watch his talk from this year's _Nodevember_ conference in Nashville
40
41 -<iframe width="420" height="315" src="//www.youtube-nocookie.com/embed/uZgAq1CZ1N8" frameborder="0" allowfullscreen></iframe>
41 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/uZgAq1CZ1N8" frameborder="0" allowfullscreen></iframe>
42
43 If you take a peek under the covers, you'll find that React powers [Carousel](https://blog.carousel.com/2014/11/introducing-carousel-for-web-ipad-and-android-tablet/), Dropbox's new photo and video gallery app.
44
@@ -48,7 +48,7 @@ We enjoyed a cinematic/narrative experience with this React-powered, interactive
48
49 Spend the next 60 seconds watching Daniel Woelfel ([dwwoelfel](https://github.com/dwwoelfel)) serialize a React app's state as a string, then deserialize it to produce a working UI. Read about how he uses this technique to [reproduce bugs](http://blog.circleci.com/local-state-global-concerns/) reported to him by his users.
50
51 -<iframe width="420" height="315" src="//www.youtube-nocookie.com/embed/5yHFTN-_mOo" frameborder="0" allowfullscreen></iframe>
51 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/5yHFTN-_mOo" frameborder="0" allowfullscreen></iframe>
52
53 ## Community Components
54
docs/_posts/2015-02-18-react-conf-roundup-2015.md
+21 -21
@@ -16,7 +16,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
16 </p>
17 </div>
18 <div class="skinny-col">
19 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/KVZ-P-ZI6W4" frameborder="0" allowfullscreen></iframe>
19 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/KVZ-P-ZI6W4" frameborder="0" allowfullscreen></iframe>
20 </div>
21 </div>
22
@@ -28,7 +28,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
28 </p>
29 </div>
30 <div class="skinny-col">
31 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/yaymfLj5tjA" frameborder="0" allowfullscreen></iframe>
31 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/yaymfLj5tjA" frameborder="0" allowfullscreen></iframe>
32 </div>
33 </div>
34
@@ -40,7 +40,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
40 </p>
41 </div>
42 <div class="skinny-col">
43 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/OZGgVxFxSIs" frameborder="0" allowfullscreen></iframe>
43 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/OZGgVxFxSIs" frameborder="0" allowfullscreen></iframe>
44 </div>
45 </div>
46
@@ -52,7 +52,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
52 </p>
53 </div>
54 <div class="skinny-col">
55 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/9sc8Pyc51uU" frameborder="0" allowfullscreen></iframe>
55 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/9sc8Pyc51uU" frameborder="0" allowfullscreen></iframe>
56 </div>
57 </div>
58
@@ -64,7 +64,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
64 </p>
65 </div>
66 <div class="skinny-col">
67 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/W2DgDNQZOwo" frameborder="0" allowfullscreen></iframe>
67 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/W2DgDNQZOwo" frameborder="0" allowfullscreen></iframe>
68 </div>
69 </div>
70
@@ -76,7 +76,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
76 </p>
77 </div>
78 <div class="skinny-col">
79 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/XZfvW1a8Xac" frameborder="0" allowfullscreen></iframe>
79 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/XZfvW1a8Xac" frameborder="0" allowfullscreen></iframe>
80 </div>
81 </div>
82
@@ -88,7 +88,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
88 </p>
89 </div>
90 <div class="skinny-col">
91 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/KtmjkCuV-EU" frameborder="0" allowfullscreen></iframe>
91 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/KtmjkCuV-EU" frameborder="0" allowfullscreen></iframe>
92 </div>
93 </div>
94
@@ -100,7 +100,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
100 </p>
101 </div>
102 <div class="skinny-col">
103 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/KYzlpRvWZ6c" frameborder="0" allowfullscreen></iframe>
103 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/KYzlpRvWZ6c" frameborder="0" allowfullscreen></iframe>
104 </div>
105 </div>
106
@@ -112,7 +112,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
112 </p>
113 </div>
114 <div class="skinny-col">
115 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/Sla-DkvmIHY" frameborder="0" allowfullscreen></iframe>
115 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/Sla-DkvmIHY" frameborder="0" allowfullscreen></iframe>
116 </div>
117 </div>
118
@@ -124,7 +124,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
124 </p>
125 </div>
126 <div class="skinny-col">
127 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/z5e7kWSHWTg" frameborder="0" allowfullscreen></iframe>
127 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/z5e7kWSHWTg" frameborder="0" allowfullscreen></iframe>
128 </div>
129 </div>
130
@@ -136,7 +136,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
136 </p>
137 </div>
138 <div class="skinny-col">
139 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/7rDsRXj9-cU" frameborder="0" allowfullscreen></iframe>
139 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/7rDsRXj9-cU" frameborder="0" allowfullscreen></iframe>
140 </div>
141 </div>
142
@@ -148,7 +148,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
148 </p>
149 </div>
150 <div class="skinny-col">
151 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/g0TD0efcwVg" frameborder="0" allowfullscreen></iframe>
151 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/g0TD0efcwVg" frameborder="0" allowfullscreen></iframe>
152 </div>
153 </div>
154
@@ -160,7 +160,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
160 </p>
161 </div>
162 <div class="skinny-col">
163 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/I7IdS-PbEgI" frameborder="0" allowfullscreen></iframe>
163 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/I7IdS-PbEgI" frameborder="0" allowfullscreen></iframe>
164 </div>
165 </div>
166
@@ -171,7 +171,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
171 <strong>Jafar Husain</strong> told us a story about how Netflix was able to push React into places where the DOM could not go.
172 </div>
173 <div class="skinny-col">
174 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/eNC0mRYGWgc" frameborder="0" allowfullscreen></iframe>
174 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/eNC0mRYGWgc" frameborder="0" allowfullscreen></iframe>
175 </div>
176 </div>
177
@@ -182,7 +182,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
182 <strong>Zach Nation</strong> showed us how we can produce visualizations from over 45 million data points without breaking a sweat.
183 </div>
184 <div class="skinny-col">
185 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/2ii1lEkIv1s" frameborder="0" allowfullscreen></iframe>
185 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/2ii1lEkIv1s" frameborder="0" allowfullscreen></iframe>
186 </div>
187 </div>
188
@@ -193,7 +193,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
193 <strong>David Nolen</strong> gave us a view of React from a non-JavaScript perspective, challenging some common intuition along the way.
194 </div>
195 <div class="skinny-col">
196 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/5hGHdETNteE" frameborder="0" allowfullscreen></iframe>
196 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/5hGHdETNteE" frameborder="0" allowfullscreen></iframe>
197 </div>
198 </div>
199
@@ -204,7 +204,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
204 <strong>Bill Fisher</strong> coordinated a Flux panel together with <strong>Michael Ridgway</strong>, <strong>Spike Brehm</strong>, <strong>Andres Suarez</strong>, <strong>Jing Chen</strong>, <strong>Ian Obermiller</strong>, and <strong>Kyle Davis</strong>.
205 </div>
206 <div class="skinny-col">
207 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/LTj4O7WJJ98" frameborder="0" allowfullscreen></iframe>
207 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/LTj4O7WJJ98" frameborder="0" allowfullscreen></iframe>
208 </div>
209 </div>
210
@@ -215,7 +215,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
215 <strong>Bonnie Eisenman</strong> led us through the ‘adapter’ approach to inter-component communication taken by her team at Codecademy.
216 </div>
217 <div class="skinny-col">
218 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/ZM6wXoFTY3o" frameborder="0" allowfullscreen></iframe>
218 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/ZM6wXoFTY3o" frameborder="0" allowfullscreen></iframe>
219 </div>
220 </div>
221
@@ -226,7 +226,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
226 <strong>James Brantly</strong> demonstrated how we can reap the benefits of static typing using both Flow and TypeScript.
227 </div>
228 <div class="skinny-col">
229 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/9PTa9-PPVAc" frameborder="0" allowfullscreen></iframe>
229 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/9PTa9-PPVAc" frameborder="0" allowfullscreen></iframe>
230 </div>
231 </div>
232
@@ -237,7 +237,7 @@ It was a privilege to welcome the React community to Facebook HQ on January 28
237 <strong>Tom Occhino</strong>, <strong>Ben Alpert</strong>, <strong>Lee Byron</strong>, <strong>Christopher Chedeau</strong>, <strong>Sebastian Markbåge</strong>, <strong>Jing Chen</strong>, and <strong>Dan Schafer</strong> closed the conference with a Q&amp;A session.
238 </div>
239 <div class="skinny-col">
240 - <iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/EPpkboSKvPI" frameborder="0" allowfullscreen></iframe>
240 + <iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/EPpkboSKvPI" frameborder="0" allowfullscreen></iframe>
241 </div>
242 </div>
243
@@ -266,4 +266,4 @@ And, in case you missed a session, you can borrow **Michael Chan’s** [drawings
266
267 **All proceeds from React.js Conf 2015 were donated to the wonderful programs at [code.org](http://code.org)**. These programs aim to increase access to the field of computer science by underrepresented members of our community. Watch this video to learn more.
268
269 -<iframe width="305" height="171" src="https://www.youtube-nocookie.com/embed/FC5FbmsH4fw" frameborder="0" allowfullscreen></iframe>
269 +<iframe width="100%" height="171" src="https://www.youtube-nocookie.com/embed/FC5FbmsH4fw" frameborder="0" allowfullscreen></iframe>
docs/_posts/2015-02-20-introducing-relay-and-graphql.md
+1 -1
@@ -8,7 +8,7 @@ author: wincent
8
9 There's more to building an application than creating a user interface. Data fetching is still a tricky problem, especially as applications become more complicated. At [React.js Conf](http://conf.reactjs.com/) we announced two projects we've created at Facebook to make data fetching simple for developers, even as a product grows to include dozens of contributors and the application becomes as complex as Facebook itself.
10
11 -<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/9sc8Pyc51uU" frameborder="0" allowfullscreen></iframe>
11 +<iframe width="100%" height="315" src="https://www.youtube-nocookie.com/embed/9sc8Pyc51uU" frameborder="0" allowfullscreen></iframe>
12
13 The two projects &mdash; Relay and GraphQL &mdash; have been in use in production at Facebook for some time, and we're excited to be bringing them to the world as open source in the future. In the meantime, we wanted to share some additional information about the projects here.
14
docs/_posts/2015-03-04-community-roundup-25.md
+2 -2
@@ -12,7 +12,7 @@ Interest in React has been exploding recently, so it's a good time to explore so
12
13 [Formidable Labs](https://github.com/FormidableLabs) and [Seattle JS](http://www.meetup.com/seattlejs/) recently hosted a series of React, Flux, and Flow workshops, and the first part is available to watch online:
14
15 -<iframe width="650" height="300" src="//www.youtube-nocookie.com/embed/Pd6Ub7Ju2RM" frameborder="0" allowfullscreen></iframe>
15 +<iframe width="100%" height="300" src="//www.youtube-nocookie.com/embed/Pd6Ub7Ju2RM" frameborder="0" allowfullscreen></iframe>
16
17 [AEFlash](https://github.com/aearly) writes up [some best practices and tips](http://aeflash.com/2015-02/react-tips-and-best-practices.html) to help you avoid potential pitfalls when developing with React.
18
@@ -20,7 +20,7 @@ Black Mutt Media [takes us through their usage of React](http://blackmuttmedia.c
20
21 Our own [Sebastian Markbåge](https://github.com/sebmarkbage) was on the [Web Platform Podcast](http://thewebplatform.libsyn.com/31-building-with-reactjs) to have a chat about all aspects of React.
22
23 -<iframe style="border: none" src="//html5-player.libsyn.com/embed/episode/id/3370114/height/75/width/200/theme/standard-mini/direction/no/autoplay/no/autonext/no/thumbnail/yes/preload/no/no_addthis/no/" height="26" width="650" scrolling="no" allowfullscreen="" webkitallowfullscreen="" mozallowfullscreen="" oallowfullscreen="" msallowfullscreen=""></iframe>
23 +<iframe style="border: none" src="//html5-player.libsyn.com/embed/episode/id/3370114/height/75/width/200/theme/standard-mini/direction/no/autoplay/no/autonext/no/thumbnail/yes/preload/no/no_addthis/no/" height="26" width="100%" scrolling="no" allowfullscreen="" webkitallowfullscreen="" mozallowfullscreen="" oallowfullscreen="" msallowfullscreen=""></iframe>
24
25 ## Community Additions
26
docs/_posts/2015-03-30-community-roundup-26.md
+1 -2
@@ -13,7 +13,7 @@ We open sourced React Native last week and the community reception blew away all
13
14 **Give us 6 months**. At Facebook, we strive to only open-source projects that we are using in production. While the Android backend for React Native is starting to work (see video below at 37min), it hasn't been shipped to any users yet. There's a lot of work that goes into open-sourcing a project, and we want to do it right so that you have a great experience when using it.
15
16 -<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/X6YbAKiLCLU?start=2220" frameborder="0" allowfullscreen></iframe>
16 +<iframe width="100%" height="315" src="https://www.youtube-nocookie.com/embed/X6YbAKiLCLU?start=2220" frameborder="0" allowfullscreen></iframe>
17
18
19 ## Ray Wenderlich - Property Finder
@@ -92,4 +92,3 @@ Clay Allsopp wrote a post about [all the crazy things you could do with a JavaSc
92 We've spent a lot of efforts getting the onboarding as easy as possible and we're really happy that people noticed. We still have a lot of work to do on documentation, stay tuned!
93
94 <blockquote class="twitter-tweet" lang="en"><p>Wow. Getting started with React Native might have been the smoothest experience I’ve ever had with a new developer product.</p>&mdash; Andreas Eldh (@eldh) <a href="https://twitter.com/eldh/status/581186172094980096">March 26, 2015</a></blockquote>
95 -
docs/_posts/2015-05-22-react-native-release-process.md
+1 -1
@@ -19,4 +19,4 @@ You now have three ways to get React Native. You should chose the one you want b
19
20 If you want more details, I highly recommend this video that explains how Facebook mobile release process works and why it was setup this way.
21
22 -<iframe width="650" height="300" src="https://www.youtube.com/embed/mOyoTUETmSM" frameborder="0" allowfullscreen></iframe>
22 +<iframe width="100%" height="300" src="https://www.youtube.com/embed/mOyoTUETmSM" frameborder="0" allowfullscreen></iframe>
docs/_posts/2015-08-13-reacteurope-roundup.md
+9 -9
@@ -8,39 +8,39 @@ Last month, the first React.js European conference took place in the city of Par
8
9 [Christopher Chedeau](https://github.com/vjeux) gave the opening keynote to the conference:
10
11 -<iframe width="650" height="366" src="//www.youtube.com/embed/PAA9O4E1IM4" frameborder="0" allowfullscreen></iframe>
11 +<iframe width="100%" height="366" src="//www.youtube.com/embed/PAA9O4E1IM4" frameborder="0" allowfullscreen></iframe>
12
13 [Spencer Ahrens](https://github.com/sahrens) walks through building an advanced gestural UI leveraging the unique power of the React Native layout and animation systems to build a complex and fluid experience:
14
15 -<iframe width="650" height="366" src="//www.youtube.com/embed/xDlfrcM6YBk" frameborder="0" allowfullscreen></iframe>
15 +<iframe width="100%" height="366" src="//www.youtube.com/embed/xDlfrcM6YBk" frameborder="0" allowfullscreen></iframe>
16
17 [Lee Byron](https://github.com/leebyron) explores GraphQL, its core principles, how it works, and what makes it a powerful tool:
18
19 -<iframe width="650" height="366" src="//www.youtube.com/embed/WQLzZf34FJ8" frameborder="0" allowfullscreen></iframe>
19 +<iframe width="100%" height="366" src="//www.youtube.com/embed/WQLzZf34FJ8" frameborder="0" allowfullscreen></iframe>
20
21 [Joseph Savona](https://github.com/josephsavona) explores the problems Relay solves, its architecture and the query lifecycle, and how can you use Relay to build more scalable apps. There are examples of how Relay powers applications as complex as the Facebook News Feed:
22
23 -<iframe width="650" height="366" src="//www.youtube.com/embed/IrgHurBjQbg" frameborder="0" allowfullscreen></iframe>
23 +<iframe width="100%" height="366" src="//www.youtube.com/embed/IrgHurBjQbg" frameborder="0" allowfullscreen></iframe>
24
25 [Nick Schrock](https://github.com/schrockn) and [Dan Schafer](https://github.com/dschafer) take a deeper dive into putting GraphQL to work. How can we build a GraphQL API to work with an existing REST API or server-side data model? What are best practices when building a GraphQL API, and how do they differ from traditional REST best practices? How does Facebook use GraphQL? Most importantly, what does a complete and coherent GraphQL API looks like, and how can we get started building one?
26
27 -<iframe width="650" height="366" src="//www.youtube.com/embed/gY48GW87Feo" frameborder="0" allowfullscreen></iframe>
27 +<iframe width="100%" height="366" src="//www.youtube.com/embed/gY48GW87Feo" frameborder="0" allowfullscreen></iframe>
28
29 [Sebastian Markbåge](https://github.com/sebmarkbage) talks about why the DOM is flawed and how it is becoming a second-class citizen in the land of React apps:
30
31 -<iframe width="650" height="366" src="//www.youtube.com/embed/Zemce4Y1Y-A" frameborder="0" allowfullscreen></iframe>
31 +<iframe width="100%" height="366" src="//www.youtube.com/embed/Zemce4Y1Y-A" frameborder="0" allowfullscreen></iframe>
32
33 [Sebastian McKenzie](https://github.com/sebmck) goes over how existing JSX build pipeline infrastructure can be further utilised to perform even more significant code transformations such as transpilation, optimisation, profiling and more, reducing bugs, making your code faster and you as a developer more productive and happy:
34
35 -<iframe width="650" height="366" src="//www.youtube.com/embed/OFuDvqZmUrE" frameborder="0" allowfullscreen></iframe>
35 +<iframe width="100%" height="366" src="//www.youtube.com/embed/OFuDvqZmUrE" frameborder="0" allowfullscreen></iframe>
36
37 [Cheng Lou](https://github.com/chenglou) gives a talk on the past, the present and the future of animation, and the place React can potentially take in this:
38
39 -<iframe width="650" height="366" src="//www.youtube.com/embed/1tavDv5hXpo" frameborder="0" allowfullscreen></iframe>
39 +<iframe width="100%" height="366" src="//www.youtube.com/embed/1tavDv5hXpo" frameborder="0" allowfullscreen></iframe>
40
41 And there was a Q&A session with the whole team covering a range of React topics:
42
43 -<iframe width="650" height="366" src="//www.youtube.com/embed/CRJZBZ_-6hQ" frameborder="0" allowfullscreen></iframe>
43 +<iframe width="100%" height="366" src="//www.youtube.com/embed/CRJZBZ_-6hQ" frameborder="0" allowfullscreen></iframe>
44
45 And there were lots of great talks from the React community:
46
docs/community/complementary-tools.it-IT.md renamed
docs/community/complementary-tools.ko-KR.md renamed
docs/community/complementary-tools.md renamed
docs/community/complementary-tools.zh-CN.md renamed
docs/community/conferences.it-IT.md renamed
+1 -1
@@ -11,7 +11,7 @@ next: videos-it-IT.html
11
12 [Sito web](http://conf.reactjs.com/) - [Agenda](http://conf.reactjs.com/schedule.html) - [Video](https://www.youtube-nocookie.com/playlist?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr)
13
14 -<iframe width="650" height="315" src="//www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe>
14 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe>
15
16 ### ReactEurope 2015
17 2 e 3 Luglio
docs/community/conferences.ko-KR.md renamed
+1 -1
@@ -11,7 +11,7 @@ next: videos-ko-KR.html
11
12 [웹사이트](http://conf.reactjs.com/) - [스케줄](http://conf.reactjs.com/schedule.html) - [비디오들](https://www.youtube-nocookie.com/playlist?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr)
13
14 -<iframe width="650" height="315" src="//www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe>
14 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe>
15
16 ### ReactEurope 2015
17 7월 2일 & 3일
docs/community/conferences.md renamed
+5 -4
@@ -1,9 +1,10 @@
1 ---
2 id: conferences
3 title: Conferences
4 -permalink: docs/conferences.html
5 -prev: thinking-in-react.html
6 -next: videos.html
4 +layout: community
5 +sectionid: community
6 +permalink: community/conferences.html
7 +redirect_from: "docs/conferences.html"
8 ---
9
10 ### React.js Conf 2015
@@ -11,7 +12,7 @@ January 28 & 29 in Facebook HQ, CA
12
13 [Website](http://conf2015.reactjs.org/) - [Schedule](http://conf2015.reactjs.org/schedule.html) - [Videos](https://www.youtube.com/playlist?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr)
14
14 -<iframe width="650" height="315" src="//www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe>
15 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe>
16
17 ### ReactEurope 2015
18 July 2 & 3 in Paris, France
docs/community/conferences.zh-CN.md renamed
+1 -1
@@ -11,7 +11,7 @@ next: videos-zh-CN.html
11
12 [Website](http://conf.reactjs.com/) - [Schedule](http://conf.reactjs.com/schedule.html) - [Videos](https://www.youtube-nocookie.com/playlist?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr)
13
14 -<iframe width="650" height="315" src="//www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe>
14 +<iframe width="100%" height="315" src="//www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe>
15
16 ### ReactEurope 2015
17 七月 2 & 3
docs/community/examples.it-IT.md renamed
docs/community/examples.ko-KR.md renamed
docs/community/examples.md renamed
docs/community/examples.zh-CN.md renamed
docs/community/support.md renamed
+9 -7
@@ -1,8 +1,10 @@
1 ---
2 -title: Need help?
3 -layout: single
2 id: support
5 -permalink: support.html
3 +title: Where To Get Support
4 +layout: community
5 +sectionid: community
6 +permalink: community/support.html
7 +redirect_from: "support.html"
8 ---
9
10 **React** is worked on full-time by Facebook's product infrastructure and Instagram's user interface engineering teams. They're often around and available for questions.
@@ -17,12 +19,12 @@ For longer-form conversations about React, we've set up a [discussion forum at *
19
20 In the forum there's also a category for job posts and a category for discussion of our weekly meeting notes.
21
20 -## IRC
22 +## Reactiflux Chat
23
22 -Many developers and users idle on Freenode.net's IRC network in **[#reactjs on freenode](irc://chat.freenode.net/reactjs)**.
24 +If you need an answer right away, check out the [Reactiflux Discord](https://discord.gg/0ZcbPKXt5bZjGY5n) community. There are usually a number of React experts there who can help out or point you to somewhere you might want to look.
25
24 -## Twitter
26 +## Facebook and Twitter
27
26 -For the latest news about React, [follow **@reactjs** on Twitter](https://twitter.com/reactjs). In addition, you can use the #reactjs hashtag to see what others are saying or add to the conversation.
28 +For the latest news about React, [like us on Facebook](https://facebook/react) and [follow **@reactjs** on Twitter](https://twitter.com/reactjs). In addition, you can use the [#reactjs](https://twitter.com/hashtag/reactjs) hashtag to see what others are saying or add to the conversation.
29
30 <div><a class="twitter-timeline" data-dnt="true" data-chrome="nofooter noheader transparent" href="https://twitter.com/search?q=%23reactjs" data-widget-id="342522405270470656"></a></div>
docs/community/videos.it-IT.md renamed
+12 -12
@@ -8,7 +8,7 @@ next: complementary-tools-it-IT.html
8
9 ### Riconsiderare le best practice - JSConf.eu
10
11 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe>
11 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe>
12
13 "A Facebook e Instagram, con React stiamo provando a spingerci oltre i limiti di ciò che è possibile realizzare sul web. Il mio talk comincerà con una breve introduzione al framework, e poi approfondirà tre argomenti controversi: Gettare via la nozione dei template e costruire le viste con JavaScript, effettuare il “ri-rendering” dell'intera applicazione quando i dati cambiano, e un'implementazione leggera del DOM e degli eventi." -- [Pete Hunt](http://www.petehunt.net/)
14
@@ -23,7 +23,7 @@ Un video di [tagtree.tv](http://tagtree.tv/) che espone i principi di [Pensare i
23
24 ### I Segreti del DOM Virtuale - MtnWest JS
25
26 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/h3KksH8gfcQ" frameborder="0" allowfullscreen></iframe>
26 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/h3KksH8gfcQ" frameborder="0" allowfullscreen></iframe>
27
28 "In questo talk discuterò perché abbiamo costruito un DOM virtuale, i vantaggi rispetto ad altri sistemi, e la sua rilevanza per il futuro della tecnologia dei browser." -- [Pete Hunt](http://www.petehunt.net/)
29
@@ -99,14 +99,14 @@ Un video di [tagtree.tv](http://tagtree.tv/) che espone i principi di [Pensare i
99
100 ### Introduzione a React.js - Facebook Seattle
101
102 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/XxVg_s8xAms" frameborder="0" allowfullscreen></iframe>
102 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/XxVg_s8xAms" frameborder="0" allowfullscreen></iframe>
103
104 Di [Tom Occhino](http://tomocchino.com/) e [Jordan Walke](https://github.com/jordwalke)
105
106 * * *
107
108 ### Backbone + React + Middleman Screencast
109 -<iframe width="650" height="488" src="https://www.youtube-nocookie.com/embed/iul1fWHVU6A" frameborder="0" allowfullscreen></iframe>
109 +<iframe width="100%" height="488" src="https://www.youtube-nocookie.com/embed/iul1fWHVU6A" frameborder="0" allowfullscreen></iframe>
110
111 Backbone è una grande maniera di interfacciare una API REST con React. Questo screencast mostra come integrare i due usando [Backbone-React-Component](https://github.com/magalhas/backbone-react-component). Middleman è il framework utilizzato in questo esempio, ma può essere facilmente sostituito con altri framework. Si può trovare un template supportato per questo esempio [qui](https://github.com/jbhatab/middleman-backbone-react-template). -- [Open Minded Innovations](http://www.openmindedinnovations.com/)
112
@@ -114,7 +114,7 @@ Backbone è una grande maniera di interfacciare una API REST con React. Questo s
114
115 ### Sviluppare Interfacce Utente Con React - Super VanJS
116
117 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/1OeXsL5mr4g" frameborder="0" allowfullscreen></iframe>
117 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/1OeXsL5mr4g" frameborder="0" allowfullscreen></iframe>
118
119 Di [Steven Luscher](https://github.com/steveluscher)
120
@@ -122,7 +122,7 @@ Di [Steven Luscher](https://github.com/steveluscher)
122
123 ### Introduzione a React - LAWebSpeed meetup
124
125 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/SMMRJif5QW0" frameborder="0" allowfullscreen></iframe>
125 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/SMMRJif5QW0" frameborder="0" allowfullscreen></iframe>
126
127 Di [Stoyan Stefanov](http://www.phpied.com/)
128
@@ -130,7 +130,7 @@ Di [Stoyan Stefanov](http://www.phpied.com/)
130
131 ### React, o come rendere la vita più semplice - FrontEnd Dev Conf '14
132
133 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/YJNUK0EA_Jo" frameborder="0" allowfullscreen></iframe>
133 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/YJNUK0EA_Jo" frameborder="0" allowfullscreen></iframe>
134
135 **In Russo** di [Alexander Solovyov](http://solovyov.net/)
136
@@ -138,19 +138,19 @@ Di [Stoyan Stefanov](http://www.phpied.com/)
138
139 ### "Programmazione funzionale del DOM" - Meteor DevShop 11
140
141 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/qqVbr_LaCIo" frameborder="0" allowfullscreen></iframe>
141 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/qqVbr_LaCIo" frameborder="0" allowfullscreen></iframe>
142
143 * * *
144
145 ### "Ripensare lo Sviluppo di Applicazioni Web a Facebook" - Facebook F8 Conference 2014
146
147 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/nYkdrAPrdcw" frameborder="0" allowfullscreen></iframe>
147 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/nYkdrAPrdcw" frameborder="0" allowfullscreen></iframe>
148
149 * * *
150
151 ### React e Flux: Costruire Applicazioni con un Flusso Dati Unidirezionale - Forward JS 2014
152
153 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/i__969noyAM" frameborder="0" allowfullscreen></iframe>
153 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/i__969noyAM" frameborder="0" allowfullscreen></iframe>
154
155 Gli ingegneri di Facebook [Bill Fisher](https://twitter.com/fisherwebdev) e [Jing Chen](https://twitter.com/jingc) parlano di Flux e React, e di come usare un'architettura dell'applicazione con un flusso di dati unidirezionale rende gran parte del loro codice più pulito.
156
@@ -158,7 +158,7 @@ Gli ingegneri di Facebook [Bill Fisher](https://twitter.com/fisherwebdev) e [Jin
158
159 ### Rendering Lato Server di Applicazioni Isomorfiche a SoundCloud
160
161 -<iframe src="https://player.vimeo.com/video/108488724" width="650" height="365" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
161 +<iframe src="https://player.vimeo.com/video/108488724" width="100%" height="365" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
162
163 [Andres Suarez](https://github.com/zertosh) ci accompagna alla scoperta di come [SoundCloud](https://developers.soundcloud.com/blog/) usa React e Flux per il rendering lato server.
164
@@ -168,6 +168,6 @@ Gli ingegneri di Facebook [Bill Fisher](https://twitter.com/fisherwebdev) e [Jin
168
169 ### Introduzione a React Native (+Playlist) - React.js Conf 2015
170
171 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe>
171 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe>
172
173 [Tom Occhino](https://twitter.com/tomocchino) ripercorre il passato e il presente di React nel 2015, e ci mostra dove è diretto nell'immediato futuro.
docs/community/videos.ko-KR.md renamed
+12 -12
@@ -8,7 +8,7 @@ next: complementary-tools-ko-KR.html
8
9 ### Rethinking best practices - JSConf.eu
10
11 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe>
11 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe>
12
13 "페이스북과 인스타그램에서, 우리는 React 를 이용해 웹에서 벌어질 수 있는 한계를 뛰어넘으려 노력하고 있습니다. 저는 프레임워크에 대한 짤막한 소개로 시작해서, 논쟁이 벌어질 수 있는 다음의 세가지 주제로 넘어갈겁니다. 템플릿의 개념을 버리고 JavaScript 를 이용해 View 를 구축하기, 자료가 변할때 전체 어플리케이션을 다시 그리기(“re-rendering”), 그리고 DOM과 events의 경량화된 구현 입니다." -- [Pete Hunt](http://www.petehunt.net/)
14
@@ -23,7 +23,7 @@ next: complementary-tools-ko-KR.html
23
24 ### Secrets of the Virtual DOM - MtnWest JS
25
26 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/h3KksH8gfcQ" frameborder="0" allowfullscreen></iframe>
26 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/h3KksH8gfcQ" frameborder="0" allowfullscreen></iframe>
27
28 "이번에는 왜 우리가 virtual DOM을 만들었는지, 이것이 다른 시스템들과는 어떻게 다른지, 그리고 브라우져 기술들의 미래와 어떻게 관련이 있는지에 대해서 이야기 해 볼 겁니다." -- [Pete Hunt](http://www.petehunt.net/)
29
@@ -101,14 +101,14 @@ JavaScript Jabber 73에서 [Pete Hunt](http://www.petehunt.net/)와 [Jordan Walk
101
102 ### Introduction to React.js - Facebook Seattle
103
104 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/XxVg_s8xAms" frameborder="0" allowfullscreen></iframe>
104 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/XxVg_s8xAms" frameborder="0" allowfullscreen></iframe>
105
106 By [Tom Occhino](http://tomocchino.com/), [Jordan Walke](https://github.com/jordwalke)
107
108 * * *
109
110 ### Backbone + React + Middleman Screencast
111 -<iframe width="650" height="488" src="https://www.youtube-nocookie.com/embed/iul1fWHVU6A" frameborder="0" allowfullscreen></iframe>
111 +<iframe width="100%" height="488" src="https://www.youtube-nocookie.com/embed/iul1fWHVU6A" frameborder="0" allowfullscreen></iframe>
112
113 Backbone은 React로 REST API를 제공하기 위한 아주 좋은 방법입니다. 이 화면중개는 [Backbone-React-Component](https://github.com/magalhas/backbone-react-component)을 이용해서 어떻게 이 두가지를 연동하는지 보여줍니다. Middleman은 이 예제에서 사용되는 프레임워크이지만, 쉽게 다른 프레임워크로 대체하실 수 있습니다. 지원되는 템플릿은 [이곳](https://github.com/jbhatab/middleman-backbone-react-template)에서 찾으실 수 있습니다. -- [열린 마음의 혁명들](http://www.openmindedinnovations.com/)
114
@@ -116,7 +116,7 @@ Backbone은 React로 REST API를 제공하기 위한 아주 좋은 방법입니
116
117 ### Developing User Interfaces With React - Super VanJS
118
119 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/1OeXsL5mr4g" frameborder="0" allowfullscreen></iframe>
119 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/1OeXsL5mr4g" frameborder="0" allowfullscreen></iframe>
120
121 By [Steven Luscher](https://github.com/steveluscher)
122
@@ -124,7 +124,7 @@ By [Steven Luscher](https://github.com/steveluscher)
124
125 ### Introduction to React - LAWebSpeed meetup
126
127 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/SMMRJif5QW0" frameborder="0" allowfullscreen></iframe>
127 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/SMMRJif5QW0" frameborder="0" allowfullscreen></iframe>
128
129 by [Stoyan Stefanov](http://www.phpied.com/)
130
@@ -132,7 +132,7 @@ by [Stoyan Stefanov](http://www.phpied.com/)
132
133 ### React, or how to make life simpler - FrontEnd Dev Conf '14
134
135 -<iframe width="560" height="366" src="https://www.youtube-nocookie.com/embed/YJNUK0EA_Jo" frameborder="0" allowfullscreen></iframe>
135 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/YJNUK0EA_Jo" frameborder="0" allowfullscreen></iframe>
136
137 **러시아어** by [Alexander Solovyov](http://solovyov.net/)
138
@@ -140,19 +140,19 @@ by [Stoyan Stefanov](http://www.phpied.com/)
140
141 ### "Functional DOM programming" - Meteor DevShop 11
142
143 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/qqVbr_LaCIo" frameborder="0" allowfullscreen></iframe>
143 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/qqVbr_LaCIo" frameborder="0" allowfullscreen></iframe>
144
145 * * *
146
147 ### "Rethinking Web App Development at Facebook" - Facebook F8 Conference 2014
148
149 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/nYkdrAPrdcw" frameborder="0" allowfullscreen></iframe>
149 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/nYkdrAPrdcw" frameborder="0" allowfullscreen></iframe>
150
151 * * *
152
153 ### React and Flux: Building Applications with a Unidirectional Data Flow - Forward JS 2014
154
155 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/i__969noyAM" frameborder="0" allowfullscreen></iframe>
155 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/i__969noyAM" frameborder="0" allowfullscreen></iframe>
156
157 Facebook 개발자 [Bill Fisher](https://twitter.com/fisherwebdev)와 [Jing Chen](https://twitter.com/jingc)가 Flux 와 React 에 대해서 이야기합니다. 그리고 어떻게 단일 방향의 자료흐름을 사용하는 어플리케이션 구조가 방대한 코드를 정리하는지에 대해서 이야기합니다."
158
@@ -160,7 +160,7 @@ Facebook 개발자 [Bill Fisher](https://twitter.com/fisherwebdev)와 [Jing Chen
160
161 ### Server-Side Rendering of Isomorphic Apps at SoundCloud
162
163 -<iframe src="https://player.vimeo.com/video/108488724" width="650" height="365" frameborder="0" allowfullscreen></iframe>
163 +<iframe src="https://player.vimeo.com/video/108488724" width="100%" height="365" frameborder="0" allowfullscreen></iframe>
164
165 Server-side rendering을 위해 [SoundCloud](https://developers.soundcloud.com/blog/)가 React 와 Flux를 사용하는지 by [Andres Suarez](https://github.com/zertosh)
166 [발표 자료와 예제 코드](https://github.com/zertosh/ssr-demo-kit)
@@ -169,6 +169,6 @@ Server-side rendering을 위해 [SoundCloud](https://developers.soundcloud.com/b
169
170 ### Introducing React Native (+Playlist) - React.js Conf 2015
171
172 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/v/KVZ-P-ZI6W4&index=1&list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe>
172 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/v/KVZ-P-ZI6W4&index=1&list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe>
173
174 2015년에 [Tom Occhino](https://twitter.com/tomocchino)님이 React의 과거와 현재를 리뷰하고 나아갈 방향을 제시했습니다.
docs/community/videos.md new
+180
@@ -0,0 +1,180 @@
1 +---
2 +id: videos
3 +title: Videos
4 +layout: community
5 +sectionid: community
6 +permalink: community/videos.html
7 +redirect_from: "docs/videos.html"
8 +---
9 +
10 +### Introduction to React
11 +
12 +[Tom Occhino](http://tomocchino.com/) and [Jordan Walke](https://github.com/jordwalke) introduce React at Facebook Seattle.
13 +
14 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/XxVg_s8xAms" frameborder="0" allowfullscreen></iframe>
15 +
16 +### Introducing React Native
17 +
18 +[Tom Occhino](https://twitter.com/tomocchino) reviews the past and present of React in 2015, and teases where it's going next.
19 +
20 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe>
21 +
22 +### Rethinking Web App Development at Facebook
23 +
24 +Delivering reliable, high-performance web experiences at Facebook's scale has required us to challenge some long-held assumptions about software development. Watch this Facebook F8 2014 talk to learn how we abandoned the traditional MVC paradigm in favor of a more functional application architecture.
25 +
26 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/nYkdrAPrdcw" frameborder="0" allowfullscreen></iframe>
27 +
28 +### Secrets of the Virtual DOM
29 +
30 +[Pete Hunt](http://www.petehunt.net/) at Mountain West JavaScript 2014 discusses why a virtual DOM was built for React, how it compares to other systems, and its relevance to the future of browser technologies.
31 +
32 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/h3KksH8gfcQ" frameborder="0" allowfullscreen></iframe>
33 +
34 +### Rethinking Best Practices
35 +
36 +[Pete Hunt](http://www.petehunt.net/)'s talk at JSConf EU 2013 covers three topics: throwing out the notion of templates and building views with JavaScript, “re-rendering” your entire application when your data changes, and a lightweight implementation of the DOM and events.
37 +
38 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe>
39 +
40 +
41 +### High performance functional DOM programming
42 +
43 +Tech Talk by [Pete Hunt](http://www.petehunt.net/) at Meteor DevShop 11.
44 +
45 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/qqVbr_LaCIo" frameborder="0" allowfullscreen></iframe>
46 +
47 +
48 +### Developing User Interfaces With React
49 +
50 +[Steven Luscher](https://github.com/steveluscher) at Super VanJS 2013.
51 +
52 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/1OeXsL5mr4g" frameborder="0" allowfullscreen></iframe>
53 +
54 +
55 +### Introduction to React
56 +
57 +[Stoyan Stefanov](http://www.phpied.com/) at LAWebSpeed meetup.
58 +
59 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/SMMRJif5QW0" frameborder="0" allowfullscreen></iframe>
60 +
61 +### Going big with React
62 +
63 +Areeb Malik investigates how React performs in a high stress situation, and how it helped his team build safe code on a massive scale.
64 +
65 +[![](https://i.vimeocdn.com/video/481670116_650.jpg)](https://skillsmatter.com/skillscasts/5429-going-big-with-react#video)
66 +
67 +### Backbone + React + Middleman Screencast
68 +
69 +This screencast shows how to integrate Backbone with React using [Backbone-React-Component](https://github.com/magalhas/backbone-react-component).
70 +
71 +<iframe width="100%" height="488" src="https://www.youtube-nocookie.com/embed/iul1fWHVU6A" frameborder="0" allowfullscreen></iframe>
72 +
73 +### React, or how to make life simpler
74 +
75 +Tech talk by [Alexander Solovyov](http://solovyov.net/) at FrontEnd Dev Conf '14 (Russian).
76 +
77 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/YJNUK0EA_Jo" frameborder="0" allowfullscreen></iframe>
78 +
79 +
80 +### React and Flux: Building Applications with a Unidirectional Data Flow
81 +
82 +Facebook engineers [Bill Fisher](https://twitter.com/fisherwebdev) and [Jing Chen](https://twitter.com/jingc) talk about Flux and React at Forward JS 2014, and how using an application architecture with a unidirectional data flow cleans up a lot of their code.
83 +
84 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/i__969noyAM" frameborder="0" allowfullscreen></iframe>
85 +
86 +### Server-Side Rendering of Isomorphic Apps at SoundCloud
87 +
88 +Walk-through by [Andres Suarez](https://github.com/zertosh) on how [SoundCloud](https://developers.soundcloud.com/blog/) is using React and Flux for server-side rendering.
89 +
90 +<iframe src="https://player.vimeo.com/video/108488724" width="100%" height="365" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
91 +
92 +> [Slides and sample code](https://github.com/zertosh/ssr-demo-kit)
93 +
94 +### CodeWinds Podcast
95 +
96 +[Pete Hunt](http://www.petehunt.net/) talked with [Jeff Barczewski](http://jeff.barczewski.com/) about React in [CodeWinds Episode 4](http://codewinds.com/podcast/004.html).
97 +<figure>[![](/react/img/docs/codewinds-004.png)](http://codewinds.com/4)</figure>
98 +
99 +<table width="100%">
100 +<tr>
101 +<th>02:08</th><td>What is React and why use it?</td>
102 +<th>27:17</th><td>Rendering HTML on the server with Node.js. Rendering backends</td>
103 +</tr>
104 +<tr>
105 +<th>03:08</th><td>The symbiotic relationship of ClojureScript and React</td>
106 +<th>29:20</th><td>React evolved through survival of the fittest at Facebook</td>
107 +</tr>
108 +<tr>
109 +<th>04:54</th><td>The history of React and why it was created</td>
110 +<th>30:15</th><td>Ideas for having state on server and client, using web sockets.</td>
111 +</tr>
112 +<tr>
113 +<th>09:43</th><td>Updating web page with React without using data binding</td>
114 +<th>32:05</th><td>React-multiuser - distributed shared mutable state using Firebase</td>
115 +</tr>
116 +<tr>
117 +<th>13:11</th><td>Using the virtual DOM to change the browser DOM</td>
118 +<th>33:03</th><td>Better debugging with React using the state transitions, replaying events</td>
119 +</tr>
120 +<tr>
121 +<th>13:57</th><td>Programming with React, render targets HTML, canvas, other</td>
122 +<th>34:08</th><td>Differences from Web Components</td>
123 +</tr>
124 +<tr>
125 +<th>16:45</th><td>Working with designers. Contrasted with Ember and AngularJS</td>
126 +<th>34:25</th><td>Notable companies using React</td>
127 +</tr>
128 +<tr>
129 +<th>21:45</th><td>JSX Compiler bridging HTML and React javascript</td>
130 +<th>35:16</th><td>Could a React backend plugin be created to target PDF?</td>
131 +</tr>
132 +<tr>
133 +<th>23:50</th><td>Autobuilding JSX and in browser tools for React</td>
134 +<th>36:30</th><td>Future of React, what's next?</td>
135 +</tr>
136 +<tr>
137 +<th>24:50</th><td>Tips and tricks to working with React, getting started</td>
138 +<th>39:38</th><td>Contributing and getting help</td>
139 +</tr>
140 +</table>
141 +
142 +### JavaScript Jabber Podcast
143 +
144 +[Pete Hunt](http://www.petehunt.net/) and [Jordan Walke](https://github.com/jordwalke) talked about React in [JavaScript Jabber 73](https://devchat.tv/js-jabber/073-jsj-react-with-pete-hunt-and-jordan-walke).
145 +<figure>[![](/react/img/docs/javascript-jabber.png)](http://javascriptjabber.com/073-jsj-react-with-pete-hunt-and-jordan-walke/#content)</figure>
146 +
147 +<table width="100%">
148 + <tr>
149 + <th>01:34</th><td>Pete Hunt Introduction</td>
150 + <th>23:06</th><td>Supporting Node.js</td>
151 + </tr>
152 + <tr>
153 + <th>02:45</th><td>Jordan Walke Introduction</td>
154 + <th>24:03</th><td>rendr</td>
155 + </tr>
156 + <tr>
157 + <th>04:15</th><td>React</td>
158 + <th>26:02</th><td>JSX</td>
159 + </tr>
160 + <tr>
161 + <th>06:38</th><td>60 Frames Per Second</td>
162 + <th>30:31</th><td>requestAnimationFrame</td>
163 + </tr>
164 + <tr>
165 + <th>09:34</th><td>Data Binding</td>
166 + <th>34:15</th><td>React and Applications</td>
167 + </tr>
168 + <tr>
169 + <th>12:31</th><td>Performance</td>
170 + <th>38:12</th><td>React Users Khan Academy</td>
171 + </tr>
172 + <tr>
173 + <th>17:39</th><td>Diffing Algorithm</td>
174 + <th>39:53</th><td>Making it work</td>
175 + </tr>
176 + <tr>
177 + <th>19:36</th><td>DOM Manipulation</td>
178 + <th></th><td></td>
179 + </tr>
180 +</table>
docs/community/videos.zh-CN.md renamed
+12 -12
@@ -8,7 +8,7 @@ next: complementary-tools-zh-CN.html
8
9 ### Rethinking best practices - JSConf.eu
10
11 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe>
11 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe>
12
13 "在 Facebook 和 Instagram, 我们正在努力挑战React在web上能达到的极限。我的讲话会从对框架的简单介绍开始,然后深入三个有争议的话题:扔掉模板的概念并用JavaScript构建views, 当数据改变 “re-rendering” 你的整个应用,以及一个DOM和events的轻量级实现。" -- [Pete Hunt](http://www.petehunt.net/)
14
@@ -23,7 +23,7 @@ next: complementary-tools-zh-CN.html
23
24 ### Secrets of the Virtual DOM - MtnWest JS
25
26 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/h3KksH8gfcQ" frameborder="0" allowfullscreen></iframe>
26 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/h3KksH8gfcQ" frameborder="0" allowfullscreen></iframe>
27
28 "在这次讲座里,我会讨论为什么我们构建了一个虚拟 DOM,它比起其他系统如何,以及它与未来浏览器技术的关系。" -- [Pete Hunt](http://www.petehunt.net/)
29
@@ -99,14 +99,14 @@ next: complementary-tools-zh-CN.html
99
100 ### Introduction to React.js - Facebook Seattle
101
102 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/XxVg_s8xAms" frameborder="0" allowfullscreen></iframe>
102 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/XxVg_s8xAms" frameborder="0" allowfullscreen></iframe>
103
104 由 [Tom Occhino](http://tomocchino.com/) 和 [Jordan Walke](https://github.com/jordwalke)
105
106 * * *
107
108 ### Backbone + React + Middleman Screencast
109 -<iframe width="650" height="488" src="https://www.youtube-nocookie.com/embed/iul1fWHVU6A" frameborder="0" allowfullscreen></iframe>
109 +<iframe width="100%" height="488" src="https://www.youtube-nocookie.com/embed/iul1fWHVU6A" frameborder="0" allowfullscreen></iframe>
110
111 Backbone 是一个在用React实现 REST API 接口的极好方法。这个屏博展示了用 [Backbone-React-Component](https://github.com/magalhas/backbone-react-component)如何整合两者. Middleman 是在本例中使用的框架但很容易被替换成其他框架。对此可支持的template可以在[这里](https://github.com/jbhatab/middleman-backbone-react-template) 找到. -- [Open Minded Innovations](http://www.openmindedinnovations.com/)
112
@@ -114,7 +114,7 @@ Backbone 是一个在用React实现 REST API 接口的极好方法。这个屏
114
115 ### Developing User Interfaces With React - Super VanJS
116
117 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/1OeXsL5mr4g" frameborder="0" allowfullscreen></iframe>
117 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/1OeXsL5mr4g" frameborder="0" allowfullscreen></iframe>
118
119 来自 [Steven Luscher](https://github.com/steveluscher)
120
@@ -122,7 +122,7 @@ Backbone 是一个在用React实现 REST API 接口的极好方法。这个屏
122
123 ### Introduction to React - LAWebSpeed meetup
124
125 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/SMMRJif5QW0" frameborder="0" allowfullscreen></iframe>
125 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/SMMRJif5QW0" frameborder="0" allowfullscreen></iframe>
126
127 来自 [Stoyan Stefanov](http://www.phpied.com/)
128
@@ -130,7 +130,7 @@ Backbone 是一个在用React实现 REST API 接口的极好方法。这个屏
130
131 ### React, or how to make life simpler - FrontEnd Dev Conf '14
132
133 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/YJNUK0EA_Jo" frameborder="0" allowfullscreen></iframe>
133 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/YJNUK0EA_Jo" frameborder="0" allowfullscreen></iframe>
134
135 **俄语** by [Alexander Solovyov](http://solovyov.net/)
136
@@ -138,19 +138,19 @@ Backbone 是一个在用React实现 REST API 接口的极好方法。这个屏
138
139 ### "Functional DOM programming" - Meteor DevShop 11
140
141 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/qqVbr_LaCIo" frameborder="0" allowfullscreen></iframe>
141 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/qqVbr_LaCIo" frameborder="0" allowfullscreen></iframe>
142
143 * * *
144
145 ### "Rethinking Web App Development at Facebook" - Facebook F8 Conference 2014
146
147 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/nYkdrAPrdcw" frameborder="0" allowfullscreen></iframe>
147 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/nYkdrAPrdcw" frameborder="0" allowfullscreen></iframe>
148
149 * * *
150
151 ### React and Flux: Building Applications with a Unidirectional Data Flow - Forward JS 2014
152
153 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/i__969noyAM" frameborder="0" allowfullscreen></iframe>
153 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/i__969noyAM" frameborder="0" allowfullscreen></iframe>
154
155 Facebook 工程师 [Bill Fisher](https://twitter.com/fisherwebdev) 和 [Jing Chen](https://twitter.com/jingc) 谈论 Flux 和 React, 以及如何使用单向数据流的程序架构清理他们的代码 .
156
@@ -158,7 +158,7 @@ Facebook 工程师 [Bill Fisher](https://twitter.com/fisherwebdev) 和 [Jing Che
158
159 ### Server-Side Rendering of Isomorphic Apps at SoundCloud
160
161 -<iframe src="https://player.vimeo.com/video/108488724" width="650" height="365" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
161 +<iframe src="https://player.vimeo.com/video/108488724" width="100%" height="365" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
162
163 来自 [Andres Suarez](https://github.com/zertosh) 的演练,关于 [SoundCloud](https://developers.soundcloud.com/blog/) 如何使用 React 和 Flux 在服务器端渲染.
164
@@ -168,6 +168,6 @@ Facebook 工程师 [Bill Fisher](https://twitter.com/fisherwebdev) 和 [Jing Che
168
169 ### Introducing React Native (+Playlist) - React.js Conf 2015
170
171 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe>
171 +<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe>
172
173 [Tom Occhino](https://twitter.com/tomocchino) 回顾了React的过去和现在,在2015年。梳理了下一步要做什么。
docs/contributing/codebase-overview.md
+12 -12
@@ -38,7 +38,7 @@ var setInnerHTML = require('setInnerHTML');
38
39 Haste was originally developed for giant apps like Facebook. It's easy to move files to different folders and import them without worrying about relative paths. The fuzzy file search in any editor always takes you to the correct place thanks to globally unique names.
40
41 -React itself was extracted from Facebook codebase and uses Haste for historical reasons. In the future, we will probably [migrate React to use CommonJS or ES Modules](https://github.com/facebook/react/issues/6336) to be more aligned with the community. However this requires changes in Facebook internal infrastructure so it is unlikely to happen very soon.
41 +React itself was extracted from the Facebook codebase and uses Haste for historical reasons. In the future, we will probably [migrate React to use CommonJS or ES Modules](https://github.com/facebook/react/issues/6336) to be more aligned with the community. However, this requires changes in Facebook internal infrastructure so it is unlikely to happen very soon.
42
43 **Haste will make more sense to you if you remember a few rules:**
44
@@ -54,7 +54,7 @@ This is a GitHub shortcut for searching the current repo for fuzzy filename matc
54
55 ### External Dependencies
56
57 -React has almost no external dependencies. Usually a `require()` points to a file in React's own codebase. However there are a few relatively rare exceptions.
57 +React has almost no external dependencies. Usually, a `require()` points to a file in React's own codebase. However, there are a few relatively rare exceptions.
58
59 If you see a `require()` that does not correspond to a file in the React repository, you can look in a special repository called [fbjs](https://github.com/facebook/fbjs). For example, `require('warning')` will resolve to the [`warning` module from fbjs](https://github.com/facebook/fbjs/blob/df9047fec0bbd1e64635ae369c045975777cba7c/packages/fbjs/src/__forks__/warning.js).
60
@@ -67,7 +67,7 @@ After cloning the [React repository](https://github.com/facebook/react), you wil
67 * [`src`](https://github.com/facebook/react/tree/master/src) is the source code of React. **If your change is related to the code, `src` is where you'll spend most of your time.**
68 * [`docs`](https://github.com/facebook/react/tree/master/docs) is the React documentation website. When you change APIs, make sure to update the relevant Markdown files.
69 * [`examples`](https://github.com/facebook/react/tree/master/examples) contains a few small React demos with different build setups.
70 -* [`packages`](https://github.com/facebook/react/tree/master/packages) contains metadata (such as `package.json`) for all packages in the React repository. Nevertheless their source code is still located inside [`src`](https://github.com/facebook/react/tree/master/src).
70 +* [`packages`](https://github.com/facebook/react/tree/master/packages) contains metadata (such as `package.json`) for all packages in the React repository. Nevertheless, their source code is still located inside [`src`](https://github.com/facebook/react/tree/master/src).
71 * `build` is the build output of React. It is not in the repository but it will appear in your React clone after you [build it](/react/contributing/how-to-contribute.html#development-workflow) for the first time.
72
73 There are a few other top-level folders but they are mostly used for the tooling and you likely won't ever encounter them when contributing.
@@ -86,7 +86,7 @@ For example, files inside [`src/renderers/dom/client`](https://github.com/facebo
86
87 However they can't import modules from [`src/renderers/dom/server`](https://github.com/facebook/react/tree/master/src/renderers/dom/server) because it is not a child directory of [`src/renderers/dom/client`](https://github.com/facebook/react/tree/master/src/renderers/dom/client).
88
89 -There is an exception to this rule. Sometimes we *do* need to share functionality between two groups of modules. In this case we hoist the shared module up to a folder called `shared` inside the closest common ancestor folder of the modules that need to rely on it.
89 +There is an exception to this rule. Sometimes we *do* need to share functionality between two groups of modules. In this case, we hoist the shared module up to a folder called `shared` inside the closest common ancestor folder of the modules that need to rely on it.
90
91 For example, code shared between [`src/renderers/dom/client`](https://github.com/facebook/react/tree/master/src/renderers/dom/client) and [`src/renderers/dom/server`](https://github.com/facebook/react/tree/master/src/renderers/dom/server) lives in [`src/renderers/dom/shared`](https://github.com/facebook/react/tree/master/src/renderers/dom/shared).
92
@@ -196,7 +196,7 @@ You can run `npm run flow` locally to check your code with Flow.
196
197 ### Classes and Mixins
198
199 -React was originally written in ES5. We have since enabled ES2015 features with [Babel](http://babeljs.io/), including classes. However most of React code is still written in ES5.
199 +React was originally written in ES5. We have since enabled ES6 features with [Babel](http://babeljs.io/), including classes. However, most of React code is still written in ES5.
200
201 In particular, you might see the following pattern quite often:
202
@@ -224,7 +224,7 @@ module.exports = ReactDOMComponent;
224
225 The `Mixin` in this code has no relation to React `mixins` feature. It is just a way of grouping a few methods under an object. Those methods may later get attached to some other class. We use this pattern in a few places although we try to avoid it in the new code.
226
227 -Equivalent code in ES2015 would like this:
227 +Equivalent code in ES6 would like this:
228
229 ```js
230 class ReactDOMComponent {
@@ -240,7 +240,7 @@ class ReactDOMComponent {
240 module.exports = ReactDOMComponent;
241 ```
242
243 -Sometimes we [convert old code to ES2015 classes](https://github.com/facebook/react/pull/7647/files). However this is not very important to us because there is an [ongoing effort](#fiber-reconciler) to replace the React reconciler implementation with a less object-oriented approach which wouldn't use classes at all.
243 +Sometimes we [convert old code to ES6 classes](https://github.com/facebook/react/pull/7647/files). However, this is not very important to us because there is an [ongoing effort](#fiber-reconciler) to replace the React reconciler implementation with a less object-oriented approach which wouldn't use classes at all.
244
245 ### Dynamic Injection
246
@@ -291,7 +291,7 @@ There are multiple injection points in the codebase. In the future, we intend to
291
292 React is a [monorepo](http://danluu.com/monorepo/). Its repository contains multiple separate packages so that their changes can be coordinated together, and documentation and issues live in one place.
293
294 -The npm metadata such as `package.json` files is located in the [`packages`](https://github.com/facebook/react/tree/master/packages) top-level folder. However there is almost no real code in it.
294 +The npm metadata such as `package.json` files is located in the [`packages`](https://github.com/facebook/react/tree/master/packages) top-level folder. However, there is almost no real code in it.
295
296 For example, [`packages/react/react.js`](https://github.com/facebook/react/blob/87724bd87506325fcaf2648c70fc1f43411a87be/packages/react/react.js) re-exports [`src/isomorphic/React.js`](https://github.com/facebook/react/blob/87724bd87506325fcaf2648c70fc1f43411a87be/src/isomorphic/React.js), the real npm entry point. Other packages mostly repeat this pattern. All the important code lives in [`src`](https://github.com/facebook/react/tree/master/src).
297
@@ -313,7 +313,7 @@ The code for React core is located in [`src/isomorphic`](https://github.com/face
313
314 >**Note:**
315 >
316 ->Until very recently, `react` npm package and `react.js` standalone build contained all React code (including React DOM) rather than just the core. This was done for backwards compatibility and historical reasons. Since React 15.4.0, the core is better separated in the build output.
316 +>Until very recently, `react` npm package and `react.js` standalone build contained all React code (including React DOM) rather than just the core. This was done for backward compatibility and historical reasons. Since React 15.4.0, the core is better separated in the build output.
317 >
318 >There is also an additional standalone browser build called `react-with-addons.js` which we will consider separately further below.
319
@@ -329,7 +329,7 @@ Renderers are located in [`src/renderers`](https://github.com/facebook/react/tre
329 * [React Native Renderer](https://github.com/facebook/react/tree/master/src/renderers/native) renders React components to native views. It is used internally by React Native via [`react-native-renderer`](https://www.npmjs.com/package/react-native-renderer) npm package. In the future a copy of it may get checked into the React Native [repository](https://github.com/facebook/react-native) so that React Native can update React at its own pace.
330 * [React Test Renderer](https://github.com/facebook/react/tree/master/src/renderers/testing) renders React components to JSON trees. It is used by the [Snapshot Testing](https://facebook.github.io/jest/blog/2016/07/27/jest-14.html) feature of [Jest](https://facebook.github.io/jest) and is available as [react-test-renderer](https://www.npmjs.com/package/react-test-renderer) npm package.
331
332 -The only other officially supported renderer is [`react-art`](https://github.com/reactjs/react-art). To avoid accidentally breaking it as we make changes to React, we checked it in as [`src/renderers/art`](https://github.com/facebook/react/tree/master/src/renderers/art) and run its test suite. Nevertheless its [GitHub repository](https://github.com/reactjs/react-art) still acts as the source of truth.
332 +The only other officially supported renderer is [`react-art`](https://github.com/reactjs/react-art). To avoid accidentally breaking it as we make changes to React, we checked it in as [`src/renderers/art`](https://github.com/facebook/react/tree/master/src/renderers/art) and run its test suite. Nevertheless, its [GitHub repository](https://github.com/reactjs/react-art) still acts as the source of truth.
333
334 While it is [technically possible](https://github.com/iamdustan/tiny-react-renderer) to create custom React renderer, this is currently not officially supported. There is no stable public contract for custom renderers yet which is another reason why we keep them all in a single place.
335
@@ -365,7 +365,7 @@ User-defined ("composite") components should behave the same way with all render
365
366 Composite components also implement [mounting](https://github.com/facebook/react/blob/87724bd87506325fcaf2648c70fc1f43411a87be/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js#L181), [updating](https://github.com/facebook/react/blob/87724bd87506325fcaf2648c70fc1f43411a87be/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js#L703), and [unmounting](https://github.com/facebook/react/blob/87724bd87506325fcaf2648c70fc1f43411a87be/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js#L524). However, unlike host components, `ReactCompositeComponent` needs to behave differently depending on user's code. This is why it calls methods, such as `render()` and `componentDidMount()`, on the user-supplied class.
367
368 -During an update, `ReactCompositeComponent` checks whether the `render()` output has a different `type` or `key` than the last time. If neither `type` nor `key` has changed, it delegates the update to the existing child internal instance. Otherwise, it unmounts the old child instance, and mounts a new one. This is described in the [reconciliation algorithm](/react/docs/reconciliation.html).
368 +During an update, `ReactCompositeComponent` checks whether the `render()` output has a different `type` or `key` than the last time. If neither `type` nor `key` has changed, it delegates the update to the existing child internal instance. Otherwise, it unmounts the old child instance and mounts a new one. This is described in the [reconciliation algorithm](/react/docs/reconciliation.html).
369
370 #### Recursion
371
@@ -381,7 +381,7 @@ It is important to understand that the stack reconciler always processes the com
381
382 The "fiber" reconciler is a new effort aiming to resolve the problems inherent in the stack reconciler and fix a few long-standing issues.
383
384 -It is a complete rewrite of the reconciler, and is currently [in active development](https://github.com/facebook/react/pulls?utf8=%E2%9C%93&q=is%3Apr%20is%3Aopen%20fiber).
384 +It is a complete rewrite of the reconciler and is currently [in active development](https://github.com/facebook/react/pulls?utf8=%E2%9C%93&q=is%3Apr%20is%3Aopen%20fiber).
385
386 Its main goals are:
387
docs/contributing/design-principles.md
+1 -1
@@ -3,7 +3,7 @@ id: design-principles
3 title: Design Principles
4 layout: contributing
5 permalink: contributing/design-principles.html
6 -prev: codebase-overview.html
6 +prev: implementation-notes.html
7 ---
8
9 We wrote this document so that you have a better idea of how we decide what React does and what React doesn't do, and what our development philosophy is like. While we are excited to see community contributions, we are not likely to choose a path that violates one or more of these principles.
docs/contributing/how-to-contribute.md
+3 -2
@@ -4,6 +4,7 @@ title: How to Contribute
4 layout: contributing
5 permalink: contributing/how-to-contribute.html
6 next: codebase-overview.html
7 +redirect_from: "/tips/introduction.html"
8 ---
9
10 React is one of Facebook's first open source projects that is both under very active development and is also being used to ship code to everybody on [facebook.com](https://www.facebook.com). We're still working out the kinks to make contributing to this project as easy and transparent as possible, but we're not quite there yet. Hopefully this document makes the process for contributing clear and answers some questions that you may have.
@@ -26,7 +27,7 @@ If you send a pull request, please do it against the `master` branch. We maintai
27
28 React follows [semantic versioning](http://semver.org/). We release patch versions for bugfixes, minor versions for new features, and major versions for any breaking changes. When we make breaking changes, we also introduce deprecation warnings in a minor version so that our users learn about the upcoming changes and migrate their code in advance.
29
29 -We tag every pull request with a label marking whether the change should go in the next [patch](https://github.com/facebook/react/pulls?q=is%3Aopen+is%3Apr+label%3Asemver-patch), [minor](https://github.com/facebook/react/pulls?q=is%3Aopen+is%3Apr+label%3Asemver-minor), or a [major](https://github.com/facebook/react/pulls?q=is%3Aopen+is%3Apr+label%3Asemver-major) version. We release new patch versions every few weeks, minor versions every few months, and major versions one or two times a year.
30 +We tag every pull request with a label marking whether the change should go in the next [patch](https://github.com/facebook/react/pulls?q=is%3Aopen+is%3Apr+label%3Asemver-patch), [minor](https://github.com/facebook/react/pulls?q=is%3Aopen+is%3Apr+label%3Asemver-minor), or a [major](https://github.com/facebook/react/pulls?q=is%3Aopen+is%3Apr+label%3Asemver-major) version. We release new patch versions every few weeks, minor versions every few months, and major versions one or two times a year.
31
32 Every significant change is documented in the [changelog file](https://github.com/facebook/react/blob/master/CHANGELOG.md).
33
@@ -38,7 +39,7 @@ We are using [GitHub Issues](https://github.com/facebook/react/issues) for our p
39
40 #### Reporting New Issues
41
41 -The best way to get your bug fixed is to provide a reduced test case. This [JSFiddle template](https://jsfiddle.net/reactjs/69z2wepo/) is a great starting point.
42 +The best way to get your bug fixed is to provide a reduced test case. This [JSFiddle template](https://jsfiddle.net/reactjs/69z2wepo/) is a great starting point.
43
44 #### Security Bugs
45
docs/contributing/implementation-notes.md
+1 -1
@@ -406,7 +406,7 @@ The host internal instances need to store:
406
407 If you're struggling to imagine how an internal instance tree is structured in more complex applications, [React DevTools](https://github.com/facebook/react-devtools) can give you a close approximation, as it highlights host instances with grey, and composite instances with purple:
408
409 - <img src="/react/img/docs/implementation-notes-tree.png" width="500" alt="React DevTools tree" />
409 + <img src="/react/img/docs/implementation-notes-tree.png" width="500" style="max-width: 100%" alt="React DevTools tree" />
410
411 To complete this refactoring, we will introduce a function that mounts a complete tree into a container node, just like `ReactDOM.render()`. It returns a public instance, also like `ReactDOM.render()`:
412
docs/css/react.scss
+363 -39
@@ -7,8 +7,9 @@
7
8 @mixin code-typography {
9 font-family: 'source-code-pro', Menlo, Consolas, 'Courier New', monospace;
10 - font-size: 13px;
10 line-height: 1.5;
11 + font-size: 13px;
12 + -webkit-text-size-adjust: none;
13 }
14
15 $skinnyContentWidth: 650px;
@@ -19,7 +20,28 @@ $columnGutter: 40px;
20 $twoColumnWidth: 2 * $columnWidth + $columnGutter;
21 $navHeight: 50px;
22
23 +// Breakpoints
24 +$bp-large: 960px;
25 +$bp-medium: 640px;
26 +$bp-small: 480px;
27
28 +@mixin bp-small {
29 + @media (max-width: $bp-small) {
30 + @content;
31 + }
32 +}
33 +
34 +@mixin bp-medium {
35 + @media (max-width: $bp-medium) {
36 + @content;
37 + }
38 +}
39 +
40 +@mixin bp-large {
41 + @media (max-width: $bp-large) {
42 + @content;
43 + }
44 +}
45
46 // basic reset
47 * {
@@ -46,15 +68,20 @@ html {
68
69 .container {
70 padding-top: $navHeight;
49 - min-width: $contentWidth + (2 * $contentPadding);
71 + width: 100%;
72 }
73
74 .wrap {
53 - width: $contentWidth + (2 * $contentPadding);
75 + max-width: $contentWidth + (2 * $contentPadding);
76 margin-left: auto;
77 margin-right: auto;
78 padding-left: 20px;
79 padding-right: 20px;
80 +
81 + @include bp-large {
82 + padding-left: 10px;
83 + padding-right: 10px;
84 + }
85 }
86
87 .skinnyWrap {
@@ -110,21 +137,19 @@ h1, h2, h3, h4, h5, h6 {
137 width: 100%;
138 z-index: 100;
139
140 + @include bp-large {
141 + height: auto;
142 + }
143 +
144 a {
145 color: $lightColor;
146 text-decoration: none;
147 }
148
118 - .nav-site-internal {
119 - margin: 0 0 0 20px;
120 - }
121 -
122 - .nav-site-external {
123 - float: right;
124 - margin: 0;
125 - }
126 -
149 .nav-site {
150 + display: inline-flex;
151 + flex: 1;
152 +
153 li {
154 margin: 0;
155 }
@@ -136,17 +161,81 @@ h1, h2, h3, h4, h5, h6 {
161 display: inline-block;
162 height: $navHeight;
163 color: #ddd;
164 + white-space: nowrap;
165 +
166 + @include bp-large {
167 + display: flex;
168 + justify-content: center;
169 + align-items: center;
170 + padding: 0 5px;
171 + line-height: inherit;
172 + }
173
174 &:hover {
175 color: #fff;
176 }
177
178 &.active {
179 + position: relative;
180 color: $lightTextColor;
146 - border-bottom: 3px solid $primary;
181 background: #333;
182 +
183 + &:after {
184 + content: "";
185 + position: absolute;
186 + bottom: 0;
187 + left: 0;
188 + right: 0;
189 + border-bottom: 3px solid $primary;
190 + }
191 +
192 + @include bp-large {
193 + background: inherit;
194 + }
195 }
196 }
197 +
198 + .nav-site-item {
199 + &--hidden-sm {
200 + @include bp-large {
201 + display: none;
202 + }
203 + }
204 + }
205 +
206 + .nav-site-search {
207 + @include bp-large {
208 + position: absolute;
209 + z-index: 1;
210 + right: 0;
211 + top: 0;
212 + margin: 0 10px;
213 +
214 + &:focus {
215 + width: 170px;
216 + }
217 + }
218 + }
219 + }
220 +
221 + .nav-site-internal {
222 + margin: 0 0 0 20px;
223 +
224 + @include bp-large {
225 + margin: 0;
226 + }
227 + }
228 +
229 + .nav-site-external {
230 + float: right;
231 + margin: 0;
232 +
233 + @include bp-large {
234 + position: absolute;
235 + top: 0;
236 + right: 55px;
237 + float: none;
238 + }
239 }
240
241 .nav-home {
@@ -155,11 +244,20 @@ h1, h2, h3, h4, h5, h6 {
244 line-height: $navHeight;
245 height: $navHeight;
246 display: inline-block;
247 +
248 + @include bp-large {
249 + font-size: 20px;
250 + }
251 }
252
253 .nav-logo {
254 vertical-align: middle;
255 display: inline-block;
256 +
257 + @include bp-large {
258 + height: 30px;
259 + width: auto;
260 + }
261 }
262
263 ul {
@@ -172,10 +270,35 @@ h1, h2, h3, h4, h5, h6 {
270 }
271 }
272
273 +.nav-lists {
274 + display: inline-block;
275 + vertical-align: top;
276 + width: calc(100% - 120px);
277 +
278 + @include bp-large {
279 + display: flex;
280 + width: calc(100% + 20px);
281 + margin: 0 -10px;
282 + font-size: 0.9em;
283 +
284 + li {
285 + display: flex;
286 + flex: 1 0 auto;
287 + align-items: center;
288 +
289 + a {
290 + flex: 1;
291 + text-align: center;
292 + line-height: 1.2;
293 + }
294 + }
295 + }
296 +}
297 +
298 // Hero!
299
300 .hero {
178 - height: 300px;
301 + min-height: 300px;
302 // background: $darkColor url(../img/header.png) no-repeat center;
303 background: $darkColor;
304 padding-top: 50px;
@@ -200,8 +323,12 @@ h1, h2, h3, h4, h5, h6 {
323 }
324
325 .buttons-unit {
326 + display: flex;
327 + justify-content: center;
328 + flex-wrap: wrap;
329 margin-top: 60px;
330 text-align: center;
331 + font-size: 1em;
332
333 a {
334 color: $blueColor;
@@ -215,6 +342,11 @@ h1, h2, h3, h4, h5, h6 {
342 &:active {
343 background: darken($primary, 5%);
344 }
345 +
346 + @include bp-large {
347 + margin: 5px;
348 + font-size: 1em;
349 + }
350 }
351 }
352
@@ -233,12 +365,17 @@ h1, h2, h3, h4, h5, h6 {
365 float: left;
366 width: 210px;
367
368 + @include bp-medium {
369 + width: 100%;
370 + padding-bottom: 40px;
371 + }
372 +
373 ul {
374 list-style: none;
375 margin: 0;
376 }
377 ul ul {
241 - margin: 6px 0 0 20px;
378 + margin: 0 0 6px 20px;
379 }
380 li {
381 line-height: 16px;
@@ -292,6 +429,25 @@ h1, h2, h3, h4, h5, h6 {
429 padding-bottom: 0;
430 border-bottom: 0;
431 }
432 +
433 + > ul {
434 + @include bp-medium {
435 + columns: 2
436 + }
437 +
438 + @include bp-small {
439 + columns: 1;
440 + }
441 +
442 + li {
443 + margin: 0;
444 +
445 + a {
446 + padding: 0;
447 + line-height: 1.6;
448 + }
449 + }
450 + }
451 }
452
453 }
@@ -311,7 +467,8 @@ h1, h2, h3, h4, h5, h6 {
467 .home-divider {
468 border-top-color: #bbb;
469 margin: 0 auto;
314 - width: 400px;
470 + width: 100%;
471 + max-width: 400px;
472 }
473
474 .skinny-row {
@@ -337,6 +494,11 @@ h1, h2, h3, h4, h5, h6 {
494 margin-left: 40px;
495 width: $columnWidth;
496
497 + @include bp-large {
498 + margin: 0;
499 + width: 100%;
500 + }
501 +
502 h3 {
503 color: $darkColor;
504 font-size: 24px;
@@ -447,14 +609,6 @@ h1, h2, h3, h4, h5, h6 {
609 float: right;
610 }
611
450 -footer {
451 - font-size: 13px;
452 - font-weight: 600;
453 - margin-top: 36px;
454 - margin-bottom: 18px;
455 - overflow: auto;
456 -}
457 -
612 section.black content {
613 padding-bottom: 18px;
614 }
@@ -467,6 +621,10 @@ section.black content {
621 @include clearfix;
622
623 padding-top: 20px;
624 + padding-bottom: 80px;
625 + @include bp-medium {
626 + padding-bottom: 0;
627 + }
628
629 blockquote {
630 padding: 5px 15px;
@@ -501,13 +659,17 @@ section.black content {
659 }
660
661 padding-top: 20px;
662 + padding-bottom: 80px;
663 + @include bp-medium {
664 + padding-bottom: 0;
665 + }
666
667 // Make a notice box out of blockquotes in the documentation:
668 blockquote {
669 padding: 15px 30px 15px 15px;
670 margin: 20px 0;
509 - background-color: rgba(204, 122, 111, 0.09999999999999998);
510 - border-left: 5px solid rgba(191, 87, 73, 0.19999999999999996);
671 + background-color: rgba(248, 245, 236, 0.5);
672 + border-left: 5px solid rgba(191, 87, 73, 0.2);
673 h4 {
674 margin-top: 0;
675 }
@@ -608,7 +770,17 @@ figure {
770
771 .inner-content {
772 float: right;
611 - width: $skinnyContentWidth;
773 + width: 100%;
774 + max-width: $skinnyContentWidth;
775 +
776 + @include bp-large {
777 + width: calc(100% - 240px);
778 + max-width: 100%;
779 + }
780 +
781 + @include bp-medium {
782 + width: 100%;
783 + }
784 }
785
786 .nosidebar .inner-content {
@@ -627,8 +799,48 @@ h1 {
799 font-weight: normal;
800 line-height: 20px;
801 margin-top: 17px;
802 +
803 + @include bp-medium {
804 + float: left;
805 + width: 100%;
806 + }
807 +}
808 +
809 +/**
810 + * Community
811 + */
812 +
813 +.communityContent {
814 + @include clearfix;
815 +
816 + h3 {
817 + margin-top: 30px;
818 + }
819 +
820 + padding-top: 20px;
821 +
822 + blockquote {
823 + padding: 5px 15px;
824 + margin: 20px 0;
825 + background-color: #f8f5ec;
826 + border-left: 5px solid #f7ebc6;
827 + }
828 +
829 + th {
830 + padding-right: 6px;
831 + text-align: right;
832 + vertical-align: top;
833 + font-weight: normal;
834 + @include code-typography;
835 + }
836 +
837 + td {
838 + vertical-align: top;
839 + text-align: left;
840 + }
841 }
842
843 +
844 /* Blog */
845
846 .post-list-item + .post-list-item {
@@ -702,7 +914,8 @@ p a code {
914 border-radius: 0 3px 3px 3px;
915 float: left;
916 overflow: hidden;
705 - width: $twoColumnWidth;
917 + width: 100%;
918 + max-width: $twoColumnWidth;
919 }
920
921 .playgroundPreview {
@@ -806,9 +1019,9 @@ p a code {
1019 text-decoration: none !important;
1020 }
1021
809 -@media screen and (max-width: 960px) {
1022 +@include bp-large {
1023 .nav-main {
811 - position: static;
1024 + position: relative;
1025 }
1026 .container {
1027 padding-top: 0;
@@ -821,6 +1034,7 @@ p a code {
1034
1035 .post img {
1036 max-width: 100%;
1037 + height: auto;
1038 }
1039
1040 .pagination {
@@ -841,6 +1055,20 @@ div[data-twttr-id] iframe {
1055 width: 100% !important;
1056 }
1057
1058 +.fb_iframe_widget {
1059 + max-width: 100%;
1060 +
1061 + * {
1062 + max-width: 100%;
1063 + }
1064 +}
1065 +
1066 +#twitter-widget-0 {
1067 + @include bp-large {
1068 + display: none !important; // Need !important because they inline display on the iframe.
1069 + }
1070 +}
1071 +
1072 /* Acknowledgements */
1073
1074 .three-column {
@@ -860,12 +1088,6 @@ div[data-twttr-id] iframe {
1088
1089 /* Algolia Doc Search */
1090
863 -@media screen and (max-width: 960px) {
864 - #algolia-doc-search {
865 - display: none;
866 - }
867 -}
868 -
1091 input#algolia-doc-search {
1092 background: transparent url('/react/img/search.png') no-repeat 10px center;
1093 background-size: 16px 16px;
@@ -886,10 +1108,21 @@ input#algolia-doc-search {
1108 width: 170px;
1109
1110 transition: width .2s ease;
889 -}
1111
891 -input#algolia-doc-search:focus {
892 - width: 240px;
1112 + &:focus {
1113 + width: 240px;
1114 + }
1115 +
1116 + @include bp-large {
1117 + background-color: transparent;
1118 + width: 0;
1119 + cursor: pointer;
1120 +
1121 + &:focus {
1122 + width: 200px;
1123 + background-color: #333;
1124 + }
1125 + }
1126 }
1127
1128 .algolia-autocomplete .aa-dropdown-menu {
@@ -925,3 +1158,94 @@ input#algolia-doc-search:focus {
1158 .aa-cursor .algolia-docsearch-suggestion {
1159 background: #f1f3f5;
1160 }
1161 +
1162 +/**
1163 + * Footer
1164 + */
1165 +
1166 +footer.nav-footer {
1167 + box-sizing: border-box;
1168 + border: none;
1169 + font-weight: 300;
1170 + color: #202020;
1171 + font-size: 15px;
1172 + line-height: 24px;
1173 + background: #2D2D2D;
1174 + box-shadow: inset 0 10px 10px -5px #0d1116;
1175 + padding-top: 2em;
1176 + padding-bottom: 2em;
1177 + -webkit-font-smoothing: antialiased;
1178 + -moz-osx-font-smoothing: grayscale;
1179 +}
1180 +footer .sitemap {
1181 + display: flex;
1182 + justify-content: space-between;
1183 + max-width: 1080px;
1184 + margin: 0 auto 3em;
1185 +}
1186 +footer .sitemap div {
1187 + flex: 1;
1188 +}
1189 +footer .sitemap .nav-home {
1190 + display: table;
1191 + margin: -12px 20px 0 0;
1192 + padding: 10px;
1193 + width: 60px;
1194 + height: 60px;
1195 + transition: opacity 0.15s ease-in-out;
1196 + background: url("../img/logo_small_gray.png") no-repeat content-box;
1197 +}
1198 +footer .sitemap .nav-home:hover,
1199 +footer .sitemap .nav-home:focus {
1200 + background-image: url("../img/logo_small.png");
1201 +}
1202 +@media screen and (max-width: 740px) {
1203 + footer .sitemap {
1204 + display: none;
1205 + }
1206 +}
1207 +
1208 +footer .sitemap a {
1209 + color: white;
1210 + display: table;
1211 + margin: 2px -10px;
1212 + padding: 3px 10px;
1213 +}
1214 +footer .sitemap a:hover,
1215 +footer .sitemap a:focus {
1216 + color: #61dafb;
1217 + text-decoration: none;
1218 +}
1219 +footer .sitemap h6 > a:hover,
1220 +footer .sitemap h6 > a:focus {
1221 + color: #61dafb;
1222 + text-decoration: none;
1223 +}
1224 +footer .sitemap h5,
1225 +footer .sitemap h6 {
1226 + margin: 0 0 10px;
1227 +}
1228 +footer .sitemap h5,
1229 +footer .sitemap h6,
1230 +footer .sitemap h5 > a,
1231 +footer .sitemap h6 > a {
1232 + color: white;
1233 +}
1234 +footer .sitemap h5 > a,
1235 +footer .sitemap h6 > a {
1236 + margin: 0 -10px;
1237 +}
1238 +footer .fbOpenSource {
1239 + display: block;
1240 + margin: 1em auto;
1241 + opacity: 0.4;
1242 + transition: opacity 0.15s ease-in-out;
1243 + width: 170px;
1244 +}
1245 +footer .fbOpenSource:hover {
1246 + opacity: 1.0;
1247 +}
1248 +footer .copyright {
1249 + color: rgba(255, 255, 255, 0.4);
1250 + text-align: center;
1251 +}
docs/docs/01-why-react.de-DE.md deleted
-28
@@ -1,28 +0,0 @@
1 ----
2 -id: why-react-de-DE
3 -title: Warum React?
4 -permalink: docs/why-react-de-DE.html
5 ----
6 -React ist eine JavaScript-Bibliothek von Facebook und Instagram für Benutzeroberflächen. Man kann sich React als das **V** in **[MVC](https://de.wikipedia.org/wiki/Model_View_Controller)** vorstellen.
7 -
8 -Wir haben React für folgende Aufgabe entwickelt: **umfangreiche Anwendungen zu bauen, deren Daten sich zeitlich ändern**.
9 -
10 -## Einfach
11 -
12 -Beschreibe, wie sich Deine App zu jedem gewünschten Zeitpunkt präsentieren soll und React kümmert sich um alle Benutzeroberflächen-Änderungen sobald sich die zugrundeliegenden Daten ändern.
13 -
14 -## Deklarativ
15 -
16 -Bei Datenveränderungen drückt React bildlich die "Aktualisieren"-Taste und versteht sich darauf, nur die veränderten Elemente zu erneuern.
17 -
18 -## Baue zusammensetzbare Komponenten
19 -
20 -React unterstützt die Entwicklung wiederverwendbarer Komponenten. Tatsächlich machst Du in React nichts anderes, als Komponenten zu bauen. Dank ihrer Kapselung erleichtern Komponenten die Wiederverwendung und das Testen von Code sowie die Trennung der Belange.
21 -
22 -## Gib' ihnen fünf Minuten
23 -
24 -React hinterfragt eine ganze Reihe konventioneller Standpunkte. Auf den ersten Blick mögen einige Ideen verrückt klingen. [Gib' ihnen fünf Minuten](https://signalvnoise.com/posts/3124-give-it-five-minutes) während Du diese Anleitung liest; diese verrückten Ideen halfen dabei, tausende von Komponenten innerhalb und außerhalb von Facebook und Instagram zu entwickeln.
25 -
26 -## Erfahre mehr
27 -
28 -Erfahre mehr über unsere Motivation zur Entwicklung von React in [diesem Blogeintrag](/react/blog/2013/06/05/why-react.html).
docs/docs/01-why-react.it-IT.md deleted
-29
@@ -1,29 +0,0 @@
1 ----
2 -id: why-react-it-IT
3 -title: Perché React?
4 -permalink: docs/why-react-it-IT.html
5 -next: displaying-data-it-IT.html
6 ----
7 -React è una libreria JavaScript per creare interfacce utente scritta da Facebook e Instagram. A molti piace pensare a React come alla **V** di **[MVC](https://it.wikipedia.org/wiki/Model-View-Controller)**.
8 -
9 -Abbiamo costruito React per risolvere un problema: **costruire applicazioni di grandi dimensioni con dati che cambiano nel tempo**.
10 -
11 -## Semplice
12 -
13 -Dichiara semplicemente come la tua app debba apparire in ogni istante, e React gestirà automaticamente tutti gli aggiornamenti della UI quando i dati sottostanti cambiano.
14 -
15 -## Dichiarativo
16 -
17 -Quando i dati cambiano, React preme idealmente il bottone "aggiorna", e sa come aggiornare soltanto le parti che sono cambiate.
18 -
19 -## Costruisci Componenti Componibili
20 -
21 -React è basato interamente sulla costruzione di componenti riutilizzabili. Infatti, con React l'*unica* cosa che fai è costruire componenti. Dal momento che sono così incapsulati, i componenti facilitano il riutilizzo del codice, la verifica e la separazione dei concetti.
22 -
23 -## Dagli Cinque Minuti
24 -
25 -React sfida molte convenzioni, e a prima vista alcune delle idee potrebbero sembrare folli. [Dagli cinque minuti](https://signalvnoise.com/posts/3124-give-it-five-minutes) mentre leggi questa guida; quelle idee folli hanno funzionato per costruire migliaia di componenti sia dentro che fuori da Facebook e Instagram.
26 -
27 -## Per Approfondire
28 -
29 -Puoi approfondire le nostre motivazioni per la costruzione di React leggendo [questo articolo del blog](/react/blog/2013/06/05/why-react.html).
docs/docs/01-why-react.ja-JP.md deleted
-29
@@ -1,29 +0,0 @@
1 ----
2 -id: why-react-ja-JP
3 -title: なぜReactを使うのでしょうか?
4 -permalink: docs/why-react-ja-JP.html
5 -next: displaying-data-ja-JP.html
6 -
7 ----
8 -ReactはFacebookとInstagramによって作られたユーザーインターフェイスを構築するためのJavaScriptのライブラリです。
9 -多くの人がReactを **[MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)** の **V** だと考えています。
10 -私たちはReactをある1つの問題を解決するために使います。それは、 **絶えず変化していくデータとともに大きなアプリケーションを構築する** ことです。それを行うために、Reactは2つの主要な考えを持っています。
11 -
12 -## 単純さ
13 -
14 -どのタイミングにおいても、アプリケーションがどのように見えるべきかを単純に表現し、Reactは根底にあるデータの変更があった場合に自動的に全てのUIを管理します。
15 -
16 -## 叙述的
17 -
18 -データが変わった時、Reactは概念的に「リフレッシュ」ボタンを押し、変わった箇所のみを検知します。
19 -
20 -## コンポーザブルなコンポーネントの構築
21 -Reactは再利用可能なコンポーネントを構築するものです。実際、Reactを用いてあなたがする *ただ1つの* ことは、コンポーネントを構築することです。Reactは無駄な部分を省いてあるので、コンポーネントはコードの再利用、テスト、関心の分離を可能にします。
22 -
23 -## 5分ください
24 -
25 -Reactは型にはまった知識にも挑戦し、ちらっと見ただけではおかしく見えるアイディアもあるでしょう。このガイドを読むのに[5分ください](https://signalvnoise.com/posts/3124-give-it-five-minutes) 。それらのおかしく見えるアイディアはFacebookやInstagramの中と外の両方で何千ものコンポーネントを構築するために動いています。
26 -
27 -## 更なる学習
28 -
29 -[このブログの投稿](/react/blog/2013/06/05/why-react.html)で、私たちがReactを構築するモチベーションについて更に学習することができます。
docs/docs/01-why-react.ko-KR.md deleted
-30
@@ -1,30 +0,0 @@
1 ----
2 -id: why-react-ko-KR
3 -title: 왜 React인가?
4 -permalink: docs/why-react-ko-KR.html
5 -next: displaying-data-ko-KR.html
6 ----
7 -
8 -React는 페이스북과 인스타그램에서 사용자 인터페이스를 구성하기 위해 만들어진 라이브러리입니다. 많은 사람들은 React를 **[MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)** 에서의 **V** 로 생각하는 경향이 있습니다.
9 -
10 -우리는 단 하나의 문제를 해결하기 위해 React를 만들었습니다: **지속해서 데이터가 변화하는 대규모 애플리케이션을 구축하기.** 이 문제를 해결하기 위해, React는 두가지 컨셉을 도입했습니다.
11 -
12 -## 단순함
13 -
14 -당신의 애플리케이션이 특정 시점에 어떻게 보여야 할지를 단순히 표현하는 것만으로, 데이터가 변할 때 React는 자동으로 모든 UI 업데이트를 관리해줍니다.
15 -
16 -## 선언적 문법
17 -
18 -데이터가 변할 때 React는 "새로 고침" 버튼을 누르듯이 작동하며, 데이터의 바뀐 부분만을 업데이트할 수 있습니다.
19 -
20 -## 구성적인 컴포넌트를 만드세요
21 -
22 -React는 재사용 가능한 컴포넌트들을 만드는 데에 도움이 됩니다. 사실, React를 사용하면 *단지* 컴포넌트를 만드는 일만 하게 됩니다. 컴포넌트들은 잘 캡슐화되어 되어 있기 때문에, 컴포넌트들은 코드의 재사용성을 높이고, 테스트를 쉽게 해 주며, 관심 분리의 원칙(separation of concerns)을 지키게 해 줍니다.
23 -
24 -## 5분만 투자하세요
25 -
26 -React는 많은 관습적인 사고에 도전하며, 첫눈에 볼 때는 이상한 아이디어들의 모음이라고 생각할 수도 있습니다. 이 가이드를 읽기 위해 [5분만 투자하세요](https://signalvnoise.com/posts/3124-give-it-five-minutes); 그 이상한 아이디어들은 페이스북과 인스타그램 안팎의 수천 개의 컴포넌트들을 만드는 데에 사용되었기 때문입니다.
27 -
28 -## 더 알아보기
29 -
30 -[이 블로그 포스트](/react/blog/2013/06/05/why-react.html)에서 React를 만든 우리의 동기에 대해 알아볼 수 있습니다.
docs/docs/01-why-react.md deleted
-29
@@ -1,29 +0,0 @@
1 ----
2 -id: why-react
3 -title: Why React?
4 -permalink: docs/why-react.html
5 -next: displaying-data.html
6 ----
7 -React is a JavaScript library for creating user interfaces by Facebook and Instagram. Many people choose to think of React as the **V** in **[MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)**.
8 -
9 -We built React to solve one problem: **building large applications with data that changes over time**.
10 -
11 -## Simple
12 -
13 -Simply express how your app should look at any given point in time, and React will automatically manage all UI updates when your underlying data changes.
14 -
15 -## Declarative
16 -
17 -When the data changes, React conceptually hits the "refresh" button, and knows to only update the changed parts.
18 -
19 -## Build Composable Components
20 -
21 -React is all about building reusable components. In fact, with React the *only* thing you do is build components. Since they're so encapsulated, components make code reuse, testing, and separation of concerns easy.
22 -
23 -## Give It Five Minutes
24 -
25 -React challenges a lot of conventional wisdom, and at first glance some of the ideas may seem crazy. [Give it five minutes](https://signalvnoise.com/posts/3124-give-it-five-minutes) while reading this guide; those crazy ideas have worked for building thousands of components both inside and outside of Facebook and Instagram.
26 -
27 -## Learn More
28 -
29 -You can learn more about our motivations behind building React in [this blog post](/react/blog/2013/06/05/why-react.html).
docs/docs/01-why-react.ru-RU.md deleted
-29
@@ -1,29 +0,0 @@
1 ----
2 -id: why-react-ru-RU
3 -title: Почему именно React?
4 -permalink: docs/why-react-ru-RU.html
5 -next: displaying-data-ru-RU.html
6 ----
7 -React — библиотека JavaScript для создания интерфейсов от команд Facebook и Instagram. Многие ассоциируют React с понятием **View** в паттерне **[MVC](https://ru.wikipedia.org/wiki/Model-View-Controller)**.
8 -
9 -Мы делали React, чтобы решить одну важную задачу: **создавать действительно большие приложения с постоянно меняющимися данными**.
10 -
11 -## Простота
12 -
13 -С React вы всегда точно знаете как будет выглядеть ваше приложение, ведь как только изменятся данные, он мгновенно отобразит эти изменения в интерфейсе.
14 -
15 -## Декларативность
16 -
17 -Как только состояние приложения изменится, React будто нажимает кнопку "обновить" и точно знает, какие части интерфейса надо поменять, а какие нет. Никаких дополнительных инструкций и команд, React сам отслеживает изменения данных и реагирует на них.
18 -
19 -## Создание компонентов, как строительных блоков приложения
20 -
21 -По сути, разработка на React целиком состоит в создании таких компонентов. С React вы *только* тем и занимаетесь, что пишете новые компоненты, те самые строительные блоки, из которых будет строиться приложение. А поскольку они хорошо инскапсулированы, их удобно использовать повторно даже в других проектах, плюс такой код проще тестировать.
22 -
23 -## Уделите этому 5 минут
24 -
25 -React бросает вызов многим устоявшимся идеям и правилам, и на первый взгляд, некоторые из его идей выглядят по меньшей мере странными. [Уделите этому 5 минут](https://signalvnoise.com/posts/3124-give-it-five-minutes) пока читаете эту статью; эти безумные идеи нашли свое применение при создании тысяч компонентов не только для Facebook и Instagram, но и в других крупных проектах.
26 -
27 -## Узнай больше
28 -
29 -Вы можете больше узнать о причинах создания React [отсюда](/react/blog/2013/06/05/why-react.html).
docs/docs/01-why-react.zh-CN.md deleted
-29
@@ -1,29 +0,0 @@
1 ----
2 -id: why-react-zh-CN
3 -title: 为什么使用 React?
4 -permalink: docs/why-react-zh-CN.html
5 -next: displaying-data-zh-CN.html
6 ----
7 -React 是一个 Facebook 和 Instagram 用来创建用户界面的 JavaScript 库。很多人选择将 React 认为是 **[MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)** 中的 **V**(视图)。
8 -
9 -我们创造 React 是为了解决一个问题:**构建随着时间数据不断变化的大规模应用程序**。
10 -
11 -### 简单
12 -
13 -仅仅只要表达出你的应用程序在任一个时间点应该呈现的样子,然后当底层的数据变了,React 会自动处理所有用户界面的更新。
14 -
15 -### 声明式 (Declarative)
16 -
17 -数据变化后,React 概念上与点击“刷新”按钮类似,但仅会更新变化的部分。
18 -
19 -## 构建可组合的组件
20 -
21 -React 都是关于构建可复用的组件。事实上,通过 React 你*唯一*要做的事情就是构建组件。得益于其良好的封装性,组件使代码复用、测试和关注分离(separation of concerns)更加简单。
22 -
23 -## 给它5分钟的时间
24 -
25 -React挑战了很多传统的知识,第一眼看上去可能很多想法有点疯狂。当你阅读这篇指南,请[给它5分钟的时间](https://signalvnoise.com/posts/3124-give-it-five-minutes);那些疯狂的想法已经帮助 Facebook 和 Instagram 从里到外创建了上千的组件了。
26 -
27 -## 了解更多
28 -
29 -你可以从这篇[博客](/react/blog/2013/06/05/why-react.html)了解更多我们创造 React 的动机。
docs/docs/01-why-react.zh-TW.md deleted
-29
@@ -1,29 +0,0 @@
1 ----
2 -id: why-react-zh-TW
3 -title: Why React?
4 -permalink: docs/why-react-zh-TW.html
5 -next: displaying-data.html
6 ----
7 -React是Facebook和Instagram用來建立使用者介面的JavaScript函式庫. 很多人認為React就是處理 **[MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)**架構中 **V** 的部份.
8 -
9 -我們建造React用來解決一個問題: **開發資料能隨時間頻繁更新的大型應用程式**.
10 -
11 -## 簡單(Simple)
12 -
13 -簡單意味著你所開發的應用程式外觀任何一部分都要能即時呈現, 並且當資料有所變動時React能自動管理所有UI的更新.
14 -
15 -## 陳述(Declarative)
16 -
17 -當資料改變時, React概念上就像是點擊了 "刷新" 的按鈕, 並且知道只需更新有改變的部份.
18 -
19 -## 建立可組合的元件(Composable Components)
20 -
21 -React就是在建造可重用的元件(Components). 事實上, 當你使用React時 *唯一* 在做的事就是建立元件(Components). 由於它們封裝性高,元件使得程式碼能夠易於重複使用, 測試, 並且容易做到讓關注點分離(separation of concerns easy).
22 -
23 -## 指引(Give It Five Minutes)
24 -
25 -React挑戰了許多傳統的觀念, 第一次乍看之下這些構想可能看起來有點瘋狂. [Give it five minutes](https://signalvnoise.com/posts/3124-give-it-five-minutes) 而當閱讀完這篇指引; 這些瘋狂的構想在Facebook和Instagram裡裡外外建立了數以千計的元件(components)之後被證明是可實行的.
26 -
27 -## 更多學習資源
28 -
29 -從這裡你能學習到更多建造React背後的動機 [this blog post](/react/blog/2013/06/05/why-react.html).
docs/docs/02-displaying-data.it-IT.md deleted
-129
@@ -1,129 +0,0 @@
1 ----
2 -id: displaying-data-it-IT
3 -title: Visualizzare Dati
4 -permalink: docs/displaying-data-it-IT.html
5 -prev: why-react-it-IT.html
6 -next: jsx-in-depth-it-IT.html
7 ----
8 -
9 -L'attività più basilare che puoi effettuare con una UI è mostrare dei dati. React rende visualizzare dati semplice e mantiene automaticamente l'interfaccia aggiornata quando i dati cambiano.
10 -
11 -
12 -## Per Cominciare
13 -
14 -Diamo un'occhiata ad un esempio davvero semplice. Creiamo un file dal nome `hello-react.html` con il codice seguente:
15 -
16 -```html
17 -<!DOCTYPE html>
18 -<html>
19 - <head>
20 - <meta charset="UTF-8" />
21 - <title>Hello React</title>
22 - <script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script>
23 - <script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
24 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
25 - </head>
26 - <body>
27 - <div id="example"></div>
28 - <script type="text/babel">
29 -
30 - // ** Il tuo codice va qui! **
31 -
32 - </script>
33 - </body>
34 -</html>
35 -```
36 -
37 -Nel resto della documentazione, ci concentreremo soltanto sul codice JavaScript e assumeremo che sia inserito in un modello come quello qui sopra. Sostituisci il commento segnaposto qui sopra con il seguente codice JSX:
38 -
39 -```javascript
40 -var HelloWorld = React.createClass({
41 - render: function() {
42 - return (
43 - <p>
44 - Ciao, <input type="text" placeholder="Scrivi il tuo nome" />!
45 - È il {this.props.date.toTimeString()}
46 - </p>
47 - );
48 - }
49 -});
50 -
51 -setInterval(function() {
52 - ReactDOM.render(
53 - <HelloWorld date={new Date()} />,
54 - document.getElementById('example')
55 - );
56 -}, 500);
57 -```
58 -
59 -
60 -## Aggiornamenti Reattivi
61 -
62 -Apri `hello-react.html` in un browser web e scrivi il tuo nome nel campo di testo. Osserva che React cambia soltanto la stringa di testo dell'ora nella UI — ogni input che inserisci nel campo di testo rimane, anche se non hai scritto alcun codice che gestisce questo comportamento. React lo capisce da solo al tuo posto e fa la cosa giusta.
63 -
64 -La maniera in cui siamo in grado di capirlo è che React non manipola il DOM a meno che non sia necessario. **Utilizza un DOM interno fittizio e veloce per effettuare confronti ed effettuare le mutazioni del DOM più efficienti al tuo posto.**
65 -
66 -Gli input di questo componente sono chiamati `props` — breve per "properties". Sono passati come attributi nella sintassi JSX. Puoi pensare ad essi come immutabili nel contesto del componente, ovvero, **non assegnare mai `this.props`**.
67 -
68 -
69 -## I Componenti Sono Come Funzioni
70 -
71 -I componenti React sono molto semplici. Puoi immaginarli come semplici funzioni che ricevono in ingresso `props` e `state` (discusso in seguito) e rendono HTML. Fatta questa premessa, i componenti sono molto semplici da descrivere.
72 -
73 -> Nota:
74 ->
75 -> **Una limitazione**: i componenti React possono rendere soltanto un singolo nodo radice. Se desideri restituire nodi multipli, essi *devono* essere avvolti in un singolo nodo radice.
76 -
77 -
78 -## Sintassi JSX
79 -
80 -Crediamo fermamente che i componenti sono la maniera corretta di separare i concetti anziché i "modelli" e la "logica di presentazione." Pensiamo che il markup e il codice che lo genera siano intimamente collegati. Inoltre, la logica di presentazione è solitamente molto complessa e usare un linguaggio di modello per esprimerla risulta dispendioso.
81 -
82 -Abbiamo scoperto che la migliore soluzione a questo problema è generare HTML e un albero di componenti direttamente dal codice JavaScript in maniera da poter utilizzare tutta la potenza espressiva di un vero linguaggio di programmazione per costruire UI.
83 -
84 -Per rendere il compito più facile, abbiamo aggiunto una semplice e **opzionale** sintassi simile all'HTML per creare questi nodi di albero React.
85 -
86 -**JSX ti permette di creare oggetti JavaScript usando una sintassi HTML.** Per generare un collegamento in React usando puro JavaScript puoi scrivere:
87 -
88 -`React.createElement('a', {href: 'https://facebook.github.io/react/'}, 'Ciao!')`
89 -
90 -Con JSX ciò diventa:
91 -
92 -`<a href="https://facebook.github.io/react/">Ciao!</a>`
93 -
94 -Abbiamo scoperto che questo ha reso la costruzione di applicazioni React più semplice e i designer tendono a preferire la sintassi, ma ciascuno ha un diverso flusso di lavoro, quindi **JSX non è richiesto per utilizzare React.**
95 -
96 -JSX è di dimensioni contenute. Per maggiori informazioni, consulta [JSX in profondità](/react/docs/jsx-in-depth-it-IT.html). Oppure osserva la trasformazione in tempo reale sulla [REPL di Babel](https://babeljs.io/repl/).
97 -
98 -JSX è simile all'HTML, ma non proprio identico. Consulta la guida [JSX gotchas](/react/docs/jsx-gotchas-it-IT.html) per alcune differenze fondamentali.
99 -
100 -[Babel offre una varietà di strumenti per cominciare a usare JSX](http://babeljs.io/docs/setup/), dagli strumenti a riga di comando alle integrazioni in Ruby on Rails. Scegli lo strumento che funziona meglio per te.
101 -
102 -
103 -## React senza JSX
104 -
105 -JSX è completamente opzionale; non è necessario utilizzare JSX con React. Puoi creare elementi React in puro JavaScript usando `React.createElement`, che richiede un nome di tag o di componente, un oggetto di proprietà e un numero variabile di argomenti che rappresentano nodi figli opzionali.
106 -
107 -```javascript
108 -var child1 = React.createElement('li', null, 'Primo Contenuto di Testo');
109 -var child2 = React.createElement('li', null, 'Secondo Contenuto di Testo');
110 -var root = React.createElement('ul', { className: 'my-list' }, child1, child2);
111 -ReactDOM.render(root, document.getElementById('example'));
112 -```
113 -
114 -Per comodità, puoi creare funzioni factory scorciatoia per costruire elementi da componenti personalizzati.
115 -
116 -```javascript
117 -var Factory = React.createFactory(ComponentClass);
118 -...
119 -var root = Factory({ custom: 'prop' });
120 -ReactDOM.render(root, document.getElementById('example'));
121 -```
122 -
123 -React possiede già delle factory predefinite per i tag HTML comuni:
124 -
125 -```javascript
126 -var root = React.DOM.ul({ className: 'my-list' },
127 - React.DOM.li(null, 'Contenuto di Testo')
128 - );
129 -```
docs/docs/02-displaying-data.ja-JP.md deleted
-125
@@ -1,125 +0,0 @@
1 ----
2 -id: displaying-data-ja-JP
3 -title: データを表示する
4 -permalink: docs/displaying-data-ja-JP.html
5 -prev: why-react-ja-JP.html
6 -next: jsx-in-depth-ja-JP.html
7 -
8 ----
9 -
10 -UIについて、最も基本的なことは、いくつかのデータを表示することです。Reactはデータを表示し、変更された時にはインターフェースを最新の状態に自動的に保つことが簡単にできるようになっています。
11 -
12 -## はじめに
13 -
14 -本当に単純な例を見てみましょう。`hello-react.html` ファイルを以下のようなコードで作成してください。
15 -
16 -```html
17 -<!DOCTYPE html>
18 -<html>
19 - <head>
20 - <meta charset="UTF-8" />
21 - <title>Hello React</title>
22 - <script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script>
23 - <script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
24 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
25 - </head>
26 - <body>
27 - <div id="example"></div>
28 - <script type="text/babel">
29 -
30 - // ** コードをここに書きます! **
31 -
32 - </script>
33 - </body>
34 -</html>
35 -```
36 -
37 -このドキュメントの中では、JavaScriptのコードにのみフォーカスします。そして、それが上のようなテンプレートに挿入されていると考えます。
38 -
39 -```javascript
40 -var HelloWorld = React.createClass({
41 - render: function() {
42 - return (
43 - <p>
44 - Hello, <input type="text" placeholder="Your name here" />!
45 - It is {this.props.date.toTimeString()}
46 - </p>
47 - );
48 - }
49 -});
50 -
51 -setInterval(function() {
52 - ReactDOM.render(
53 - <HelloWorld date={new Date()} />,
54 - document.getElementById('example')
55 - );
56 -}, 500);
57 -```
58 -
59 -
60 -## リアクティブなアップデート
61 -
62 -`hello-react.html` をウェブブラウザで開き、テキストフィールドにあなたの名前を入力してください。ReactはUIのうち、時間の文字列しか変更しないことに注意してください。あなたがテキストフィールドに入力したものは残っています。あなたはそういったコードを書いていないのにも関わらずです。Reactはあなたのことを理解しており、正しいことを行います。
63 -
64 -このことについて私たちが理解できる方法は、Reactは必要になるまで、DOMの操作を行わないということです。 **Reactは、DOMの変化を表現し、あなたにもっとも効率的なDOMの変化を見積もるために早い、内部のモックのDOMを使っています。**
65 -
66 -このコンポーネントのインプットは `props` と呼ばれるものです。"properties" の省略形です。それらはJSXシンタックスの中でアトリビュートとして渡されます。それらはコンポーネントの中で不変と考えるべきで、 **`this.props` には書き込まないようにしてください**
67 -
68 -## コンポーネントは関数のようなものです。
69 -
70 -Reactのコンポーネントはとても単純です。それらは `props` や `state` (後述します)を取り、HTMLをレンダリングする単純な関数だと考えることができます。この考えの元、コンポーネントは簡単に理解することができます。
71 -
72 -> 注意:
73 ->
74 -> **1つの制限**: Reactのコンポーネントは単一の最上位のノードだけをレンダリングします。複数のノードをリターンしたい場合は、単一の最上位のもので *ラップする必要があります* 。
75 -
76 -## JSXシンタックス
77 -
78 -私たちは関心を分離する正しい方法は「テンプレート」と「ディスプレイロジック」ではなくコンポーネントであると強く考えています。ビューを生成するマークアップとコードは密接につながっていると考えています。加えて、ディスプレイロジックはとても複雑になりえますし、ビューを表現するのにテンプレート言語を使うことはとてもややこしくなりえます。
79 -
80 -私たちは、この問題の最適解は、UIを構築するのにリアルなプログラミング言語の表現力の全てを使うことができるように、JavaScriptのコードからHTMLやコンポーネントのツリーを直接生成することだと発見しました。
81 -
82 -上記のことを簡単に行うために、私たちはReactのツリーノードを構築するためのとても単純で、 **オプショナルな** HTMLに似たシンタックスを加えました。
83 -
84 -**JSXはHTMLのシンタックスを使ってJavaScriptのオブジェクトを構築するのを可能にします。** 純粋にJavaScriptを使ってReactでリンクを構築するには、以下のように書きます。
85 -
86 -`React.createElement('a', {href: 'https://facebook.github.io/react/'}, 'Hello!')`
87 -
88 -JSXでは、以下のように変換されます。
89 -
90 -`<a href="https://facebook.github.io/react/">Hello!</a>`
91 -
92 -以上のようなことで、Reactのアプリを作成するのは簡単になりましたし、デザイナーはこのシンタックスを好むようになると発見しました。しかし、人は自分自身のワークフローを持っているものです。 **JSXはReactを使う際に必ずしも必要ではありません。**
93 -
94 -JSXはとても小さいです。さらに学ぶためには、[JSXの深層](/react/docs/jsx-in-depth-ja-JP.html)を参照ください。または、[ライブJSXコンパイラー](/react/jsx-compiler.html)で変換の動作を確認してください。
95 -
96 -JSXはHTMLに似ていますが、正確に同じではありません。いくつかのキーの違いについては[JSXの理解](/react/docs/jsx-gotchas.html) をご覧ください。
97 -
98 -JSXを初めて使う際に最も簡単なのは、ブラウザで `JSXTransformer` を使う方法です。これはプロダクションでは使わないことを強くお勧めします。コードは、コマンドラインの[react-tools](https://www.npmjs.com/package/react-tools)パッケージを使うことでプリコンパイルできます。
99 -
100 -## JSXを使わないReact
101 -
102 -JSXは完全にオプションです。Reactと一緒にJSXを使う必要はありません。`React.createElement` を使って、ただのJavaScriptでReactの要素を作ることもできます。それは、タグの名前やコンポーネント、プロパティのオブジェクト、いくつかのオプションの子要素をとります。
103 -
104 -```javascript
105 -var child1 = React.createElement('li', null, 'First Text Content');
106 -var child2 = React.createElement('li', null, 'Second Text Content');
107 -var root = React.createElement('ul', { className: 'my-list' }, child1, child2);
108 -ReactDOM.render(root, document.getElementById('example'));
109 -```
110 -便利に書くために、カスタムコンポーネントで要素を作るために簡略した記法でファクトリー関数を作ることができます。
111 -
112 -```javascript
113 -var Factory = React.createFactory(ComponentClass);
114 -...
115 -var root = Factory({ custom: 'prop' });
116 -ReactDOM.render(root, document.getElementById('example'));
117 -```
118 -
119 -Reactはすでに、共通なHTMLのタグについてはビルトインの関数を持っています。
120 -
121 -```javascript
122 -var root = React.DOM.ul({ className: 'my-list' },
123 - React.DOM.li(null, 'Text Content')
124 - );
125 -```
docs/docs/02-displaying-data.ko-KR.md deleted
-124
@@ -1,124 +0,0 @@
1 ----
2 -id: displaying-data-ko-KR
3 -title: 데이터를 표시하기
4 -permalink: docs/displaying-data-ko-KR.html
5 -prev: why-react-ko-KR.html
6 -next: jsx-in-depth-ko-KR.html
7 ----
8 -
9 -UI를 가지고 할 수 있는 가장 기초적인 것은 데이터를 표시하는 것입니다. React는 데이터를 표시하고 데이터가 변할 때마다 인터페이스를 최신의 상태로 자동으로 유지하기 쉽게 해 줍니다.
10 -
11 -## 시작하기
12 -
13 -정말 간단한 예제를 보도록 하죠. 다음과 같은 코드의 `hello-react.html` 파일을 만듭시다.
14 -
15 -```html
16 -<!DOCTYPE html>
17 -<html>
18 - <head>
19 - <meta charset="UTF-8" />
20 - <title>Hello React</title>
21 - <script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script>
22 - <script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
23 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
24 - </head>
25 - <body>
26 - <div id="example"></div>
27 - <script type="text/babel">
28 -
29 - // ** 코드는 여기에 작성하면 됩니다! **
30 -
31 - </script>
32 - </body>
33 -</html>
34 -```
35 -
36 -문서의 나머지에서, 코드가 위와 같은 HTML 템플릿에 들어갔다고 가정하고 JavaScript 코드에만 집중할 것입니다. 위의 주석 부분을 다음과 같은 JSX 코드로 바꿔 보세요:
37 -
38 -```javascript
39 -var HelloWorld = React.createClass({
40 - render: function() {
41 - return (
42 - <p>
43 - 안녕, <input type="text" placeholder="이름을 여기에 작성하세요" />!
44 - 지금 시간은 {this.props.date.toTimeString()} 입니다.
45 - </p>
46 - );
47 - }
48 -});
49 -
50 -setInterval(function() {
51 - ReactDOM.render(
52 - <HelloWorld date={new Date()} />,
53 - document.getElementById('example')
54 - );
55 -}, 500);
56 -```
57 -
58 -## 반응 적(Reactive) 업데이트
59 -
60 -`hello-react.html` 파일을 웹 브라우저에서 열어 당신의 이름을 텍스트 필드에 써 보세요. React는 단지 시간을 표시하는 부분만을 바꿉니다 — 텍스트 필드 안에 입력한 것은 그대로 남아 있구요, 당신이 이 동작을 관리하는 그 어떤 코드도 쓰지 않았음에도 불구하고 말이죠. React는 그걸 올바른 방법으로 알아서 해줍니다.
61 -
62 -우리가 이걸 할 수 있었던 건, React는 필요한 경우에만 DOM을 조작하기 때문입니다. **React는 빠른 React 내부의 DOM 모형을 이용하여 변경된 부분을 측정하고, 가장 효율적인 DOM 조작 방법을 계산해 줍니다.**
63 -
64 -이 컴포넌트에 대한 입력은 `props` 라고 불립니다 — "properties" 를 줄인 것이죠. 그들은 JSX 문법에서는 어트리뷰트로서 전달됩니다. 당신은 `props` 를 컴포넌트 안에서 불변의(immutable) 엘리먼트로서 생각해야 하고, `this.props` 를 덮어씌우려고 해서는 안됩니다.
65 -
66 -## 컴포넌트들은 함수와 같습니다
67 -
68 -React 컴포넌트들은 매우 단순합니다. 당신은 그것들을 `props` 와 `state` (이것들은 나중에 언급할 것입니다) 를 받고 HTML을 렌더링하는 단순한 함수들로 생각해도 됩니다. 이걸 염두하면, 컴포넌트의 작동을 이해하는 것도 쉽습니다.
69 -
70 -> 주의:
71 ->
72 -> **한가지 제약이 있습니다**: React 컴포넌트들은 단 하나의 루트 노드(root node)만을 렌더할 수 있습니다. 만약 여러개의 노드들을 리턴하고 싶다면, 그것들은 단 하나의 루트 노드로 싸여져 있어야만 합니다.
73 -
74 -## JSX 문법
75 -
76 -우리는 컴포넌트를 사용하는 것이 "템플릿"과 "디스플레이 로직(display logic)"을 이용하는 것보다 관심을 분리(separate concerns)하는 데에 올바른 방법이라고 강하게 믿고 있습니다. 우리는 마크업과 그것을 만들어내는 코드는 친밀하게 함께 결합되어있다고 생각합니다. 또한, 디스플레이 로직은 종종 매우 복잡하고, 그것을 템플릿 언어를 이용해 표현하는 것은 점점 사용하기 어렵게 됩니다.
77 -
78 -우리는 이 문제를 해결하는 최고의 해결책은, UI를 만드는 진짜 프로그래밍 언어의 표현력을 모두 사용할 수 있는 JavaScript 코드로부터 HTML과 컴포넌트 트리들을 생성하는 것임을 발견했습니다.
79 -
80 -이것을 더 쉽게 하기 위해서, 우리는 매우 간단하고, **선택적인** HTML과 비슷한 문법을 추가하여 이 React 트리 노드들을 만들 수 있게 했습니다.
81 -
82 -**JSX는 당신으로 하여금 HTML 문법을 이용해 JavaScript 객체를 만들게 해줍니다.** React를 이용해 순수한 JavaScript 문법으로 링크를 만드려고 한다면, 코드는 다음과 같습니다:
83 -
84 -`React.createElement('a', {href: 'https://facebook.github.io/react/'}, '안녕하세요!')`
85 -
86 -JSX를 이용하면:
87 -
88 -`<a href="https://facebook.github.io/react/">안녕하세요!</a>`
89 -
90 -우리는 이것이 React 앱들을 만들기 쉽게 하고, 디자이너들이 이 문법을 더 선호하는 것을 발견했습니다, 하지만 모든 사람은 그들만의 선호하는 워크플로우가 있기 마련이므로, **JSX는 React를 사용하기 위해 필수적이지는 않습니다.**
91 -
92 -JSX는 매우 작은 언어입니다. 그것을 배우고 싶다면, [JSX 깊게 살펴보기](/react/docs/jsx-in-depth-ko-KR.html)를 살펴 보시기 바랍니다. 또는, [바벨 REPL](https://babeljs.io/repl/)를 통해 문법이 변환되는 것을 살펴 보시기 바랍니다.
93 -
94 -JSX는 HTML과 비슷하지만, 완전히 똑같지는 않습니다. [JSX의 실수하기 쉬운 부분들](/react/docs/jsx-gotchas-ko-KR.html)에 중요한 차이점들에 대해 설명되어 있습니다.
95 -
96 -[바벨에서 JSX를 시작하는 여러 방법을 제공합니다](http://babeljs.io/docs/setup/). 여기에는 커맨드 라인 툴부터 루비 온 레일스 연동까지 다양한 방법이 있습니다. 가장 편한 툴을 사용하세요.
97 -
98 -## JSX 없이 React 사용하기
99 -
100 -JSX는 완전히 선택적입니다. 당신은 React와 JSX를 함께 사용하지 않아도 상관없습니다. 그냥 JavaScript에서 React 엘리먼트를 `React.createElement`로 만들 수 있습니다. 여기에 태그 이름이나 컴포넌트, 속성 객체, 자식 엘리먼트들을 전달하면 됩니다.
101 -
102 -```javascript
103 -var child1 = React.createElement('li', null, 'First Text Content');
104 -var child2 = React.createElement('li', null, 'Second Text Content');
105 -var root = React.createElement('ul', { className: 'my-list' }, child1, child2);
106 -ReactDOM.render(root, document.getElementById('example'));
107 -```
108 -
109 -편의를 위하여, 당신은 팩토리 함수 헬퍼들을 이용해 커스텀 컴포넌트로부터 엘리먼트들을 만들 수 있습니다.
110 -
111 -```javascript
112 -var Factory = React.createFactory(ComponentClass);
113 -...
114 -var root = Factory({ custom: 'prop' });
115 -ReactDOM.render(root, document.getElementById('example'));
116 -```
117 -
118 -React는 이미 일반적인 HTML 태그에 대한 빌트인 팩토리를 가지고 있습니다.
119 -
120 -```javascript
121 -var root = React.DOM.ul({ className: 'my-list' },
122 - React.DOM.li(null, '텍스트')
123 - );
124 -```
docs/docs/02-displaying-data.md deleted
-126
@@ -1,126 +0,0 @@
1 ----
2 -id: displaying-data
3 -title: Displaying Data
4 -permalink: docs/displaying-data.html
5 -prev: why-react.html
6 -next: jsx-in-depth.html
7 ----
8 -
9 -The most basic thing you can do with a UI is display some data. React makes it easy to display data and automatically keeps the interface up-to-date when the data changes.
10 -
11 -## Getting Started
12 -
13 -Let's look at a really simple example. Create a `hello-react.html` file with the following code:
14 -
15 -```html
16 -<!DOCTYPE html>
17 -<html>
18 - <head>
19 - <meta charset="UTF-8" />
20 - <title>Hello React</title>
21 - <script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script>
22 - <script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
23 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
24 - </head>
25 - <body>
26 - <div id="example"></div>
27 - <script type="text/babel">
28 -
29 - // ** Your code goes here! **
30 -
31 - </script>
32 - </body>
33 -</html>
34 -```
35 -
36 -For the rest of the documentation, we'll just focus on the JavaScript code and assume it's inserted into a template like the one above. Replace the placeholder comment above with the following JSX:
37 -
38 -```javascript
39 -class HelloWorld extends React.Component {
40 - render() {
41 - return (
42 - <p>
43 - Hello, <input type="text" placeholder="Your name here" />!
44 - It is {this.props.date.toTimeString()}
45 - </p>
46 - );
47 - }
48 -}
49 -
50 -function tick() {
51 - ReactDOM.render(
52 - <HelloWorld date={new Date()} />,
53 - document.getElementById('example')
54 - );
55 -}
56 -
57 -setInterval(tick, 500);
58 -```
59 -
60 -## Reactive Updates
61 -
62 -Open `hello-react.html` in a web browser and type your name into the text field. Notice that React is only changing the time string in the UI — any input you put in the text field remains, even though you haven't written any code to manage this behavior. React figures it out for you and does the right thing.
63 -
64 -The way we are able to figure this out is that React does not manipulate the DOM unless it needs to. **It uses a fast, internal mock DOM to perform diffs and computes the most efficient DOM mutation for you.**
65 -
66 -The inputs to this component are called `props` — short for "properties". They're passed as attributes in JSX syntax. You should think of these as immutable within the component, that is, **never write to `this.props`**.
67 -
68 -## Components are Just Like Functions
69 -
70 -React components are very simple. You can think of them as simple functions that take in `props` and `state` (discussed later) and render HTML. With this in mind, components are easy to reason about.
71 -
72 -> Note:
73 ->
74 -> **One limitation**: React components can only render a single root node. If you want to return multiple nodes they *must* be wrapped in a single root.
75 -
76 -## JSX Syntax
77 -
78 -We strongly believe that components are the right way to separate concerns rather than "templates" and "display logic." We think that markup and the code that generates it are intimately tied together. Additionally, display logic is often very complex and using template languages to express it becomes cumbersome.
79 -
80 -We've found that the best solution for this problem is to generate HTML and component trees directly from the JavaScript code such that you can use all of the expressive power of a real programming language to build UIs.
81 -
82 -In order to make this easier, we've added a very simple, **optional** HTML-like syntax to create these React tree nodes.
83 -
84 -**JSX lets you create JavaScript objects using HTML syntax.** To generate a link in React using pure JavaScript you'd write:
85 -
86 -`React.createElement('a', {href: 'https://facebook.github.io/react/'}, 'Hello!')`
87 -
88 -With JSX this becomes:
89 -
90 -`<a href="https://facebook.github.io/react/">Hello!</a>`
91 -
92 -We've found this has made building React apps easier and designers tend to prefer the syntax, but everyone has their own workflow, so **JSX is not required to use React.**
93 -
94 -JSX is very small. To learn more about it, see [JSX in depth](/react/docs/jsx-in-depth.html). Or see the transform in action in [the Babel REPL](https://babeljs.io/repl/).
95 -
96 -JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences.
97 -
98 -[Babel exposes a number of ways to get started using JSX](http://babeljs.io/docs/setup/), ranging from command line tools to Ruby on Rails integrations. Choose the tool that works best for you.
99 -
100 -## React without JSX
101 -
102 -JSX is completely optional; you don't have to use JSX with React. You can create React elements in plain JavaScript using `React.createElement`, which takes a tag name or component, a properties object, and variable number of optional child arguments.
103 -
104 -```javascript
105 -var child1 = React.createElement('li', null, 'First Text Content');
106 -var child2 = React.createElement('li', null, 'Second Text Content');
107 -var root = React.createElement('ul', { className: 'my-list' }, child1, child2);
108 -ReactDOM.render(root, document.getElementById('example'));
109 -```
110 -
111 -For convenience, you can create short-hand factory functions to create elements from custom components.
112 -
113 -```javascript
114 -var Factory = React.createFactory(ComponentClass);
115 -...
116 -var root = Factory({ custom: 'prop' });
117 -ReactDOM.render(root, document.getElementById('example'));
118 -```
119 -
120 -React already has built-in factories for common HTML tags:
121 -
122 -```javascript
123 -var root = React.DOM.ul({ className: 'my-list' },
124 - React.DOM.li(null, 'Text Content')
125 - );
126 -```
docs/docs/02-displaying-data.ru-RU.md deleted
-124
@@ -1,124 +0,0 @@
1 ----
2 -id: displaying-data-ru-RU
3 -title: Отображение данных
4 -permalink: docs/displaying-data-ru-RU.html
5 -prev: why-react-ru-RU.html
6 -next: jsx-in-depth.html
7 ----
8 -
9 -Главная задача интерфейса — это отображать данные. React делает это легко и обновляет интерфейс сразу, как только изменятся данные.
10 -
11 -## Начало
12 -
13 -Давайте рассмотрим простой пример. Создайте файл `hello-react.html` со следующим текстом:
14 -
15 -```html
16 -<!DOCTYPE html>
17 -<html>
18 - <head>
19 - <meta charset="UTF-8" />
20 - <title>Hello React</title>
21 - <script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script>
22 - <script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
23 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
24 - </head>
25 - <body>
26 - <div id="example"></div>
27 - <script type="text/babel">
28 -
29 - // ** Ваш код будет здесь! **
30 -
31 - </script>
32 - </body>
33 -</html>
34 -```
35 -
36 -Добавим в этот шаблон немного JavaScript. Замените комментарий на следующий JSX-код:
37 -
38 -```javascript
39 -var HelloWorld = React.createClass({
40 - render: function() {
41 - return (
42 - <p>
43 - Hello, <input type="text" placeholder="Your name here" />!
44 - It is {this.props.date.toTimeString()}
45 - </p>
46 - );
47 - }
48 -});
49 -
50 -setInterval(function() {
51 - ReactDOM.render(
52 - <HelloWorld date={new Date()} />,
53 - document.getElementById('example')
54 - );
55 -}, 500);
56 -```
57 -
58 -## Реактивные обновления
59 -
60 -Откройте `hello-react.html` в браузере и введите в текстовое поле свое имя. Что происходит со страницей? Каждые полсекунды обновляется время, остальные же части страницы остаются без изменений. Обратите внимание, что мы не написали ни строчки кода, чтобы управлять этим поведением. React сам отлично понимает что надо делать и обновляет элементы на странице по мере необходимости.
61 -
62 -Суть в том, что React не меняет DOM-дерево до тех пор, пока это не потребуется. **Чтобы отразить изменения, React использует быстрое внутреннее представление DOM-дерева и просчитывает как его изменить наиболее эффективно**.
63 -
64 -Передаваемые в компонент данные называются `props` — сокращенно от "properties". В JSX коде они передаются как атрибуты компонента. Считайте, что компонент получает `props` только для чтения. **Никогда не перезаписывайте значения `this.props` внутри компонента.**
65 -
66 -## Компоненты как функции
67 -
68 -Компоненты React — довольно простые сущности. Можно считать их обыкновенными функциями, которые принимают на входе `props` и `state` (см. далее) и возвращают HTML. Если помнить об этом, то компоненты становятся простыми для понимания.
69 -
70 -> Замечание:
71 ->
72 -> **Есть одно ограничение**: Компоненты React умеют возвращать только один узел. Если вам надо вернуть сразу несколько, они *должны* быть обернуты в один корневой узел.
73 -
74 -## Синтаксис JSX
75 -
76 -Мы убеждены, что компоненты — самый подходящий способ разделения ответственностей, гораздо более удобный чем "шаблоны" и "вынесение логики на страницу". Мы считаем, что разметка и код, который её генерирует, неотделимы друг от друга. Плюс, логика на странице часто бывает запутанной, и использование шаблонизаторов, чтобы описать её, только затрудняет работу.
77 -
78 -Мы решили, что лучшим вариантом будет генерировать HTML и деревья компонентов прямо из JS кода. Так вы сможете зайдействовать всю выразительную мощь современного языка программирования для создания интерфейсов.
79 -
80 -А чтобы упростить создание узлов дерева, мы ввели **опциональный** HTML-подобный синтаксис.
81 -
82 -**JSX позволяет вам создавать JavaScript объекты используя синтаксис HTML**. Для генерации ссылки в React вы напишете на чистом JavaScript:
83 -
84 -`React.createElement('a', {href: 'https://facebook.github.io/react/'}, 'Hello!')`
85 -
86 -С JSX это станет:
87 -
88 -`<a href="https://facebook.github.io/react/">Hello!</a>`
89 -
90 -Мы установили, что с JSX создавать React приложения проще, и дизайнеров как правило устраивает его синтаксис. Но у разных людей разные предпочтения, поэтому стоит сказать, что **JSX необязателен при работе с React.**
91 -
92 -JSX сам по себе очень прост. Чтобы узнать о нем больше, почитайте [подробно про JSX](/react/docs/jsx-in-depth.html). Или можете попробовать его в [Babel REPL](https://babeljs.io/repl/).
93 -
94 -JSX похож на HTML, но но имеет существенные отличия. Почитайте про [подводные камни JSX](/react/docs/jsx-gotchas.html), чтобы понять их ключевые различия.
95 -
96 -[Babel предлагает несколько способов начать работу с JSX](http://babeljs.io/docs/setup/), от консольных утилит до интеграций с Ruby on Rails. Выберите тот инструмент, который лучше всего вам подходит.
97 -
98 -## React без использования JSX
99 -
100 -JSX полностью опционален; вам совсем необязательно использовать его вместе с React. Вы можете создавать React-элементы на чистом JavaScript используя функцию `React.createElement`, которая принимает имя тега или компонента, объект со свойствами, и набор необязательных дочерних элементов.
101 -
102 -```javascript
103 -var child1 = React.createElement('li', null, 'First Text Content');
104 -var child2 = React.createElement('li', null, 'Second Text Content');
105 -var root = React.createElement('ul', { className: 'my-list' }, child1, child2);
106 -ReactDOM.render(root, document.getElementById('example'));
107 -```
108 -
109 -Для удобства, вы можете создать сокращенные фабричные функции, чтобы создавать React-элементы из ваших собственных компонентов.
110 -
111 -```javascript
112 -var Factory = React.createFactory(ComponentClass);
113 -...
114 -var root = Factory({ custom: 'prop' });
115 -ReactDOM.render(root, document.getElementById('example'));
116 -```
117 -
118 -А для базовых HTML тегов в React уже есть встроенные фабрики:
119 -
120 -```javascript
121 -var root = React.DOM.ul({ className: 'my-list' },
122 - React.DOM.li(null, 'Text Content')
123 - );
124 -```
docs/docs/02-displaying-data.zh-CN.md deleted
-124
@@ -1,124 +0,0 @@
1 ----
2 -id: displaying-data-zh-CN
3 -title: 显示数据
4 -permalink: docs/displaying-data-zh-CN.html
5 -prev: why-react-zh-CN.html
6 -next: jsx-in-depth-zh-CN.html
7 ----
8 -
9 -用户界面能做的最基础的事就是显示一些数据。React 让显示数据变得简单,当数据变化的时候,用户界面会自动同步更新。
10 -
11 -## 开始
12 -
13 -让我们看一个非常简单的例子。新建一个名为 `hello-react.html` 的文件,代码内容如下:
14 -
15 -```html
16 -<!DOCTYPE html>
17 -<html>
18 - <head>
19 - <meta charset="UTF-8" />
20 - <title>Hello React</title>
21 - <script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script>
22 - <script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
23 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
24 - </head>
25 - <body>
26 - <div id="example"></div>
27 - <script type="text/babel">
28 -
29 - // ** 在这里替换成你的代码 **
30 -
31 - </script>
32 - </body>
33 -</html>
34 -```
35 -
36 -在接下去的文档中,我们只关注 JavaScript 代码,假设我们把代码插入到上面那个模板中。用下面的代码替换掉上面用来占位的注释。
37 -
38 -```javascript
39 -var HelloWorld = React.createClass({
40 - render: function() {
41 - return (
42 - <p>
43 - Hello, <input type="text" placeholder="Your name here" />!
44 - It is {this.props.date.toTimeString()}
45 - </p>
46 - );
47 - }
48 -});
49 -
50 -setInterval(function() {
51 - ReactDOM.render(
52 - <HelloWorld date={new Date()} />,
53 - document.getElementById('example')
54 - );
55 -}, 500);
56 -```
57 -
58 -## 被动更新 (Reactive Updates)
59 -
60 -在浏览器中打开 `hello-react.html` ,在输入框输入你的名字。你会发现 React 在用户界面中只改变了时间, 任何你在输入框输入的内容一直保留着,即使你没有写任何代码来完成这个功能。React 为你解决了这个问题,做了正确的事。
61 -
62 -我们想到的方法是除非不得不操作 DOM ,React 是不会去操作 DOM 的。**它用一种更快的内置仿造的 DOM 来操作差异,为你计算出出效率最高的 DOM 改变**。
63 -
64 -对这个组件的输入称为 `props` - "properties"的缩写。得益于 JSX 语法,它们通过参数传递。你必须知道在组件里,这些属性是不可改变的,也就是说 **`this.props` 是只读的**。
65 -
66 -## 组件就像是函数
67 -
68 -React 组件非常简单。你可以认为它们就是简单的函数,接受 `props` 和 `state` (后面会讨论) 作为参数,然后渲染出 HTML。正是应为它们是这么的简单,这使得它们非常容易理解。
69 -
70 -> 注意:
71 ->
72 -> **只有一个限制**: React 组件只能渲染单个根节点。如果你想要返回多个节点,它们*必须*被包含在同一个节点里。
73 -
74 -## JSX 语法
75 -
76 -我们坚信组件是正确方法去做关注分离,而不是通过“模板”和“展示逻辑”。我们认为标签和生成它的代码是紧密相连的。此外,展示逻辑通常是很复杂的,通过模板语言实现这些逻辑会产生大量代码。
77 -
78 -我们得出解决这个问题最好的方案是通过 JavaScript 直接生成模板,这样你就可以用一个真正语言的所有表达能力去构建用户界面。
79 -
80 -为了使这变得更简单,我们做了一个非常简单、**可选**类似 HTML 语法 ,通过函数调用即可生成模板的编译器,称为 JSX。
81 -
82 -**JSX 让你可以用 HTML 语法去写 JavaScript 函数调用** 为了在 React 生成一个链接,通过纯 JavaScript 你可以这么写:
83 -
84 -`React.createElement('a', {href: 'https://facebook.github.io/react/'}, 'Hello React!')`。
85 -
86 -通过 JSX 这就变成了
87 -
88 -`<a href="https://facebook.github.io/react/">Hello React!</a>`。
89 -
90 -我们发现这会使搭建 React 应用更加简单,设计师也偏向用这用语法,但是每个人可以有它们自己的工作流,所以**JSX 不是必须用的。**
91 -
92 -JSX 非常小;上面“hello, world”的例子使用了 JSX 所有的特性。想要了解更多,请看 [深入理解 JSX](/react/docs/jsx-in-depth-zh-CN.html)。或者直接使用[在线 JSX 编译器](/react/jsx-compiler.html)观察变化过程。
93 -
94 -JSX 类似于 HTML,但不是完全一样。参考 [JSX 陷阱](/react/docs/jsx-gotchas-zh-CN.html) 学习关键区别。
95 -
96 -[Babel 公开了一些使用 JSX 的方式],从命令行工具到 Ruby on Rails 集成。选择一个对你来说最合适的工具。
97 -
98 -## 没有 JSX 的 React
99 -
100 -JSX完全是可选的;你无需在 React 中必须使用 JSX。你可以通过 `React.createElement` 来创建一个树。第一个参数是标签,第二个参数是一个属性对象,第三个是子节点。
101 -
102 -```javascript
103 -var child1 = React.createElement('li', null, 'First Text Content');
104 -var child2 = React.createElement('li', null, 'Second Text Content');
105 -var root = React.createElement('ul', { className: 'my-list' }, child1, child2);
106 -ReactDOM.render(root, document.getElementById('example'));
107 -```
108 -
109 -方便起见,你可以创建基于自定义组件的速记工厂方法。
110 -
111 -```javascript
112 -var Factory = React.createFactory(ComponentClass);
113 -...
114 -var root = Factory({ custom: 'prop' });
115 -ReactDOM.render(root, document.getElementById('example'));
116 -```
117 -
118 -React 已经为 HTML 标签提供内置工厂方法。
119 -
120 -```javascript
121 -var root = React.DOM.ul({ className: 'my-list' },
122 - React.DOM.li(null, 'Text Content')
123 - );
124 -```
docs/docs/02-displaying-data.zh-TW.md deleted
-125
@@ -1,125 +0,0 @@
1 ----
2 -id: displaying-data-zh-TW
3 -title: Displaying Data
4 -permalink: docs/displaying-data-zh-TW.html
5 -prev: why-react-zh-TW.html
6 -next: jsx-in-depth-zh-TW.html
7 ----
8 -
9 -在使用者介面所能做最基本的事情就是呈現資料. React讓呈現資料變得更加容易並且當資料有所變動時也能自動地讓使用者介面保持呈現最新的資料.
10 -
11 -## 入門(Getting Started)
12 -
13 -我們從一個相當簡單的範例開始. 建立一個名為 `hello-react.html` 的檔案裡面包含下列程式碼:
14 -
15 -```html
16 -<!DOCTYPE html>
17 -<html>
18 - <head>
19 - <meta charset="UTF-8" />
20 - <title>Hello React</title>
21 - <script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script>
22 - <script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
23 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
24 - </head>
25 - <body>
26 - <div id="example"></div>
27 - <script type="text/babel">
28 -
29 - // ** 將你的程式碼放在這裡! **
30 -
31 - </script>
32 - </body>
33 -</html>
34 -```
35 -
36 -這份文件其他部份,我們將只會專注在JavaScript程式碼解說上,並且假設程式碼會被放置在如上述模板的註解區塊內. 用下列的JSX程式碼取代上述註解區塊:
37 -
38 -```javascript
39 -var HelloWorld = React.createClass({
40 - render: function() {
41 - return (
42 - <p>
43 - Hello, <input type="text" placeholder="Your name here" />!
44 - It is {this.props.date.toTimeString()}
45 - </p>
46 - );
47 - }
48 -});
49 -
50 -setInterval(function() {
51 - ReactDOM.render(
52 - <HelloWorld date={new Date()} />,
53 - document.getElementById('example')
54 - );
55 -}, 500);
56 -```
57 -
58 -## 反應性更新(Reactive Updates)
59 -
60 -在一個瀏覽器上開啟檔案 `hello-react.html` 並且在文字區塊填入你的名字. 請注意React僅僅改變UI上的時間字串 — 你在文字區塊輸入的任何文字依舊存在, 即使你並沒有寫任何程式碼來管理這個行為.React可以為你分辨出這樣的行為並且做出正確的回應.
61 -
62 -之所以能夠分辨出這樣的行為是因為React除非在真正有必要的情況下,否則不會對DOM做任何操作. **它使用一個快速的, 內部虛擬的DOM(internal mock DOM)來為你施行比較和計算最有效率的DOM變動(DOM mutation)**
63 -
64 -輸入到元件(component)的內容我們稱為`props` — 是屬性("properties")的簡稱. 他們在JSX語法中作為傳遞屬性之用. 你應該把這些屬性當做元件中不可被改變的, 也就是說, **永遠不要對 `this.props` 做寫入的行為**.
65 -
66 -## 元件就是函數(Components are Just Like Functions)
67 -
68 -React元件(components)是非常簡單的. 你能把它們想成是簡單的函數帶入`props`和`state`(後面會討論這部份)並且呈送給HTML(render HTML). 在心中保持住這個想法, 就能容易理解元件(components).
69 -React components are very simple. You can think of them as simple functions that take in `props` and `state` (discussed later) and render HTML. With this in mind, components are easy to reason about.
70 -
71 -> 注意(Note):
72 ->
73 -> **一個局限性**: React元件(components)只能呈送(render)給一個單一根節點(root node). 如果你想要回傳多個節點(multiple nodes)他們*必須*被包裹在單一根節點內.
74 -
75 -## JSX語法
76 -
77 -我們深信元件(components)才是分離關注點(separate concerns)的正確方法, 而並非傳統的模板("templates")和顯示邏輯("display logic")觀念. 我們認為標記(markup)和產生它的程式碼應當緊密的綁在一起. 另外, 顯示邏輯(display logic)常常是非常複雜的, 若使用模板語言(template languages)來詮釋它就顯得笨重或累贅.
78 -
79 -我們找到解決這個問題的最佳解答就是直接在JavaScript程式內產生HTML和元件樹(component trees)如此一來你就能使用真正的程式語言的表達能力(expressive power)來建立使用者介面(UIs).
80 -
81 -為了能更輕鬆實現, 我們增加了一個非常簡單, **可選擇性使用的** 類似HTML的語法(HTML-like syntax) 來創建這些React樹節點(React tree nodes).
82 -
83 -**JSX能讓你使用HTML語法來創建JavaScript物件.** 在React裡使用純JavaScript來產生一個鏈接(link)你可以這樣寫:
84 -
85 -`React.createElement('a', {href: 'https://facebook.github.io/react/'}, 'Hello!')`
86 -
87 -使用JSX語法則變成:
88 -
89 -`<a href="https://facebook.github.io/react/">Hello!</a>`
90 -
91 -我們發現這麼做能讓建立React apps更加容易並且設計師往往喜歡語法, 但是每個人都有他們自己的工作流程, 所以**在使用React時JSX並非必要.**
92 -
93 -JSX非常簡單易懂. 若想要學習更多關於JSX, 請參閱 [JSX in depth](/react/docs/jsx-in-depth.html). 或是可以使用線上及時轉換工具 [the Babel REPL](https://babeljs.io/repl/).
94 -
95 -JSX類似於HTML, 但不盡然完全相同. 參閱 [JSX gotchas](/react/docs/jsx-gotchas.html) 來比較一些主要的差異點.
96 -
97 -[Babel exposes a number of ways to get started using JSX](http://babeljs.io/docs/setup/), 涵蓋從命令列工具到Ruby on Rails整合. 可以從中選擇最適合你的工具.
98 -
99 -## React不使用JSX的範例(React without JSX)
100 -
101 -JSX完全是可選擇性使用的; 你可以不拿JSX跟React一起使用. 你能在純粹的JavaScript環境中使用`React.createElement`來創建React元素(React elements), 它搭配一個標籤名(tag name)或是元件(component), 一個屬性物件(properties object), 和數個選擇性子參數(child arguments).
102 -
103 -```javascript
104 -var child1 = React.createElement('li', null, 'First Text Content');
105 -var child2 = React.createElement('li', null, 'Second Text Content');
106 -var root = React.createElement('ul', { className: 'my-list' }, child1, child2);
107 -ReactDOM.render(root, document.getElementById('example'));
108 -```
109 -
110 -為了方便起見, 你能創建速記factory函式(short-hand factory functions)然後從自訂元件(custom components)建立元素(elements).
111 -
112 -```javascript
113 -var Factory = React.createFactory(ComponentClass);
114 -...
115 -var root = Factory({ custom: 'prop' });
116 -ReactDOM.render(root, document.getElementById('example'));
117 -```
118 -
119 -針對一般的HTML標籤React已經有內建的factories函式:
120 -
121 -```javascript
122 -var root = React.DOM.ul({ className: 'my-list' },
123 - React.DOM.li(null, 'Text Content')
124 - );
125 -```
docs/docs/02.1-jsx-in-depth.it-IT.md deleted
-228
@@ -1,228 +0,0 @@
1 ----
2 -id: jsx-in-depth-it-IT
3 -title: JSX in Profondità
4 -permalink: docs/jsx-in-depth-it-IT.html
5 -prev: displaying-data-it-IT.html
6 -next: jsx-spread-it-IT.html
7 ----
8 -
9 -[JSX](https://facebook.github.io/jsx/) è un'estensione della sintassi JavaScript che somiglia all'XML. Puoi usare una semplice trasformazione sintattica di JSX con React.
10 -
11 -## Perché JSX?
12 -
13 -Non devi per forza utilizzare JSX con React. Puoi anche usare semplice JS. Tuttavia, raccomandiamo di utilizzare JSX perché usa una sintassi concisa e familiare per definire strutture ad albero dotate di attributi.
14 -
15 -È più familiare a sviluppatori occasionali come i designer.
16 -
17 -L'XML ha i benefici di tag di apertura e chiusura bilanciati. Ciò rende la lettura di grandi strutture ad albero più semplice di chiamate a funzione o oggetti letterali.
18 -
19 -Non altera la semantica di JavaScript.
20 -
21 -## Tag HTML o Componenti React
22 -
23 -React può sia rendere tag HTML (stringhe) che componenti React (classi).
24 -
25 -Per rendere untag HTML, usa nomi di tag minuscoli in JSX:
26 -
27 -```javascript
28 -var myDivElement = <div className="foo" />;
29 -ReactDOM.render(myDivElement, document.getElementById('example'));
30 -```
31 -
32 -Per rendere un componente React, definisci una variabile locale che comincia con una lettera maiuscola:
33 -
34 -```javascript
35 -var MyComponent = React.createClass({/*...*/});
36 -var myElement = <MyComponent someProperty={true} />;
37 -ReactDOM.render(myElement, document.getElementById('example'));
38 -```
39 -
40 -Il JSX di React utilizza la convenzione maiuscolo o minuscolo per distinguere tra classi di componenti locali e tag HTML.
41 -
42 -> Nota:
43 ->
44 -> Poiché JSX è JavaScript, gli identificatori come `class` e `for` sono sconsigliati
45 -> come nomi di attributi XML. Invece, i componenti DOM React si aspettano nomi di proprietà
46 -> come `className` e `htmlFor` rispettivamente.
47 -
48 -## La Trasformazione
49 -
50 -Il JSX di React viene trasformato da una sintassi XML a JavaScript nativo. Gli elementi XML, gli attributi e i figli sono trasformati in argomenti passati a `React.createElement`.
51 -
52 -```javascript
53 -var Nav;
54 -// Input (JSX):
55 -var app = <Nav color="blue" />;
56 -// Output (JS):
57 -var app = React.createElement(Nav, {color:"blue"});
58 -```
59 -
60 -Osserva che per utilizzare `<Nav />`, la variabile `Nav` deve essere visibile.
61 -
62 -JSX permette anche di specificare i figli usando una sintassi XML:
63 -
64 -```javascript
65 -var Nav, Profile;
66 -// Input (JSX):
67 -var app = <Nav color="blue"><Profile>click</Profile></Nav>;
68 -// Output (JS):
69 -var app = React.createElement(
70 - Nav,
71 - {color:"blue"},
72 - React.createElement(Profile, null, "click")
73 -);
74 -```
75 -
76 -JSX inferirà il [displayName](/react/docs/component-specs-it-IT.html#displayname) della classe dall'assegnazione delle variabile, quando il valore di displayName è indefinito:
77 -
78 -```javascript
79 -// Input (JSX):
80 -var Nav = React.createClass({ });
81 -// Output (JS):
82 -var Nav = React.createClass({displayName: "Nav", });
83 -```
84 -
85 -Usa la [REPL di Babel](https://babeljs.io/repl/) per provare il JSX e vedere come viene trasformato
86 -in JavaScript nativo, e il
87 -[convertitore da HTML a JSX](http://magic.reactjs.net/htmltojsx.htm) per convertire il tuo HTML esistente a
88 -JSX.
89 -
90 -Se desideri utilizzare JSX, la guida [Primi Passi](/react/docs/getting-started-it-IT.html) ti mostra come impostare la compilazione.
91 -
92 -> Nota:
93 ->
94 -> L'espressione JSX viene sempre valutata come un ReactElement. Le implementazioni
95 -> attuali potrebbero differire. Un modo ottimizzato potrebbe porre il
96 -> ReactElement in linea come un oggetto letterale per evitare il codice di validazione in
97 -> `React.createElement`.
98 -
99 -## Namespace dei Componenti
100 -
101 -Se stai costruendo un componente che ha parecchi figli, come ad esempio un modulo, potresti facilmente trovarti con una quantità di dichiarazioni di variabili:
102 -
103 -```javascript
104 -// Imbarazzante blocco di dichiarazioni di variabili
105 -var Form = MyFormComponent;
106 -var FormRow = Form.Row;
107 -var FormLabel = Form.Label;
108 -var FormInput = Form.Input;
109 -
110 -var App = (
111 - <Form>
112 - <FormRow>
113 - <FormLabel />
114 - <FormInput />
115 - </FormRow>
116 - </Form>
117 -);
118 -```
119 -
120 -Per rendere tutto ciò più semplice e leggibile, *i componenti con un namespace* ti permettono di usare un componente che dispone di altri componenti come proprietà:
121 -
122 -```javascript
123 -var Form = MyFormComponent;
124 -
125 -var App = (
126 - <Form>
127 - <Form.Row>
128 - <Form.Label />
129 - <Form.Input />
130 - </Form.Row>
131 - </Form>
132 -);
133 -```
134 -
135 -Per fare ciò, devi semplicemente creare i tuoi *"sub-componenti"* come proprietà del componente principale:
136 -
137 -```javascript
138 -var MyFormComponent = React.createClass({ ... });
139 -
140 -MyFormComponent.Row = React.createClass({ ... });
141 -MyFormComponent.Label = React.createClass({ ... });
142 -MyFormComponent.Input = React.createClass({ ... });
143 -```
144 -
145 -JSX gestirà il tutto correttamente al momento di compilare il tuo codice.
146 -
147 -```javascript
148 -var App = (
149 - React.createElement(Form, null,
150 - React.createElement(Form.Row, null,
151 - React.createElement(Form.Label, null),
152 - React.createElement(Form.Input, null)
153 - )
154 - )
155 -);
156 -```
157 -
158 -> Nota:
159 ->
160 -> Questa funzionalità è disponibile nella [v0.11](/react/blog/2014/07/17/react-v0.11.html#jsx) e successive.
161 -
162 -## Espressioni JavaScript
163 -
164 -### Expressioni come Attributi
165 -
166 -Per usare un'espressione JavaScript come valore di un attributo, racchiudi l'espressione in un paio
167 -di parentesi graffe (`{}`) anziché doppi apici (`""`).
168 -
169 -```javascript
170 -// Input (JSX):
171 -var person = <Person name={window.isLoggedIn ? window.name : ''} />;
172 -// Output (JS):
173 -var person = React.createElement(
174 - Person,
175 - {name: window.isLoggedIn ? window.name : ''}
176 -);
177 -```
178 -
179 -### Attributi Booleani
180 -
181 -Omettere il valore di un attributo fa in modo che JSX lo tratti come `true`. Per passare `false` occorre utilizzare un'espressione come attributo. Ciò capita spesso quando si usano elementi di moduli HTML, con attributi come `disabled`, `required`, `checked` e `readOnly`.
182 -
183 -```javascript
184 -// Queste due forme sono equivalenti in JSX per disabilitare un bottone
185 -<input type="button" disabled />;
186 -<input type="button" disabled={true} />;
187 -
188 -// E queste due forme sono equivalenti in JSX per non disabilitare un bottone
189 -<input type="button" />;
190 -<input type="button" disabled={false} />;
191 -```
192 -
193 -### Expressioni per Figli
194 -
195 -Similmente, espressioni JavaScript possono essere utilizzate per rappresentare figli:
196 -
197 -```javascript
198 -// Input (JSX):
199 -var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>;
200 -// Output (JS):
201 -var content = React.createElement(
202 - Container,
203 - null,
204 - window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login)
205 -);
206 -```
207 -
208 -### Commenti
209 -
210 -È facile aggiungere commenti al tuo codice JSX; sono semplici espressioni JS. Devi soltanto prestare attenzione a porre `{}` attorno ai commenti quando ti trovi dentro la sezione figli di un tag.
211 -
212 -```javascript
213 -var content = (
214 - <Nav>
215 - {/* commento figlio, racchiuso in {} */}
216 - <Person
217 - /* commento
218 - su più
219 - righe */
220 - name={window.isLoggedIn ? window.name : ''} // fine del commento su una riga
221 - />
222 - </Nav>
223 -);
224 -```
225 -
226 -> NOTA:
227 ->
228 -> JSX è simile all'HTML, ma non esattamente identico. Consulta la guida [JSX gotchas](/react/docs/jsx-gotchas-it-IT.html) per le differenze fondamentali.
docs/docs/02.1-jsx-in-depth.ja-JP.md deleted
-219
@@ -1,219 +0,0 @@
1 ----
2 -id: jsx-in-depth
3 -title: JSXの深層
4 -permalink: docs/jsx-in-depth-ja-JP.html
5 -prev: displaying-data-ja-JP.html
6 -next: jsx-spread-ja_JP.html
7 ----
8 -
9 -[JSX](https://facebook.github.io/jsx/)はXMLに似たJavaScriptのシンタックスの拡張です。Reactでは、単純なJSXのシンタックスの変換を使うことができます。
10 -
11 -## なぜJSXを使うのでしょうか?
12 -
13 -ReactでJSXの使用を強制されるわけではありません。生のJSを使うこともできます。しかし、JSXは簡潔で、木構造とReactの特性を定義しやすいシンタックスであるため、JSXを使うことをお勧めします。
14 -
15 -デザイナーのようなカジュアルな開発者にとってはさらに馴染みやすいでしょう。
16 -
17 -XMLにはバランスの取れた開始タグと終了タグという利益があります。このことで、関数がオブジェクトリテラルを呼んでいるのを読むよりも簡単に大きな木構造を作ることができます。
18 -
19 -これはJavaScriptのセマンティックスを代替するものではありません。
20 -
21 -## HTMLタグ対Reactコンポーネント
22 -
23 -ReactはHTMLタグ(文字列)とReactコンポーネント(クラス)の両方をレンダリングすることができます。
24 -
25 -以下のようにJSXで小文字のタグ名を使用するだけで、HTMLタグをレンダリングできます。
26 -
27 -```javascript
28 -var myDivElement = <div className="foo" />;
29 -ReactDOM.render(myDivElement, document.getElementById('example'));
30 -```
31 -
32 -以下のように大文字から始まるローカル変数を作成するだけで、Reactのコンポーネントをレンダリングできます。
33 -
34 -```javascript
35 -var MyComponent = React.createClass({/*...*/});
36 -var myElement = <MyComponent someProperty={true} />;
37 -ReactDOM.render(myElement, document.getElementById('example'));
38 -```
39 -
40 -ReactのJSXは大文字と小文字を使うことで、ローカルのコンポーネントクラスとHTMLタグを識別する習慣があります。
41 -
42 -> 注意:
43 ->
44 -> JSXはJavaScriptなので、 `class` や `for` といった識別子はXMLの属性名としては使用しません。代わりに、 ReactのDOMコンポーネントはDOMのプロパティ名がそれぞれ `className` や `htmlFor` といったものであることを期待します。
45 -
46 -## The Transform
47 -
48 -ReactのJSXはXMLに似たシンタックスをネイティブなJavaScriptに変換します。XML要素や属性や子要素は `React.createElement` で渡される引数に変換されます。
49 -
50 -```javascript
51 -var Nav;
52 -// 入力 (JSX):
53 -var app = <Nav color="blue" />;
54 -// 出力 (JS):
55 -var app = React.createElement(Nav, {color:"blue"});
56 -```
57 -
58 -`<Nav />` を使うためには、 `Nav` 変数がスコープの中にないといけないことに注意してください。
59 -
60 -以下のように、JSXはXMLシンタックスを使うことで、細かな子要素の使用も許可します。
61 -
62 -```javascript
63 -var Nav, Profile;
64 -// 入力 (JSX):
65 -var app = <Nav color="blue"><Profile>click</Profile></Nav>;
66 -// 出力 (JS):
67 -var app = React.createElement(
68 - Nav,
69 - {color:"blue"},
70 - React.createElement(Profile, null, "click")
71 -);
72 -```
73 -
74 -以下のように、displayNameがundefinedの時には、JSXはクラスの[displayName](/react/docs/component-specs.html#displayname)を変数の割り当てから予測します。
75 -
76 -```javascript
77 -// 入力 (JSX):
78 -var Nav = React.createClass({ });
79 -// 出力 (JS):
80 -var Nav = React.createClass({displayName: "Nav", });
81 -```
82 -
83 -JSXを試し、どのようにネイティブなJavaScriptに変換されるか見るには、[JSX Compiler](/react/jsx-compiler.html)を、すでに存在するHTMLをJSXに変換するには[HTMLからJSXへのコンバーター](http://magic.reactjs.net/htmltojsx.htm)を使ってください。
84 -
85 -JSXを使いたい場合は、[始めてみましょう](/react/docs/getting-started-ja-JP.html)というガイドがどのようにコンパイルを設定するか示してくれます。
86 -
87 -> 注意:
88 ->
89 -> JSXという表現は常にReactElementを評価します。実際に実行する際の詳細はおそらく異なっているでしょう。最適化されたモードでは `React.createElement` のコードのバリデーションを避けるためにReactElementをオブジェクトリテラルとして配置するでしょう。
90 -
91 -
92 -## ネームスペース化されたコンポーネント
93 -
94 -formのように、たくさんの子要素を持つコンポーネントを構築する際には、以下のように多くの変数を宣言しなければいけないでしょう。
95 -
96 -```javascript
97 -// 変数宣言のあまりよくない部分
98 -var Form = MyFormComponent;
99 -var FormRow = Form.Row;
100 -var FormLabel = Form.Label;
101 -var FormInput = Form.Input;
102 -
103 -var App = (
104 - <Form>
105 - <FormRow>
106 - <FormLabel />
107 - <FormInput />
108 - </FormRow>
109 - </Form>
110 -);
111 -```
112 -
113 -これを単純で簡単にするために、 *ネームスペース化されたコンポーネント* では、以下のように他のコンポーネントを付属物として持つ1つのコンポーネントを使うことができます。
114 -
115 -```javascript
116 -var Form = MyFormComponent;
117 -
118 -var App = (
119 - <Form>
120 - <Form.Row>
121 - <Form.Label />
122 - <Form.Input />
123 - </Form.Row>
124 - </Form>
125 -);
126 -```
127 -
128 -これを行うためには、以下のようにメインコンポーネントの付属物として、「サブコンポーネント」を作るだけで大丈夫です。
129 -
130 -```javascript
131 -var MyFormComponent = React.createClass({ ... });
132 -
133 -MyFormComponent.Row = React.createClass({ ... });
134 -MyFormComponent.Label = React.createClass({ ... });
135 -MyFormComponent.Input = React.createClass({ ... });
136 -```
137 -
138 -JSXはコードをコンパイルする際にこのプロパティをハンドルします。
139 -
140 -```javascript
141 -var App = (
142 - React.createElement(Form, null,
143 - React.createElement(Form.Row, null,
144 - React.createElement(Form.Label, null),
145 - React.createElement(Form.Input, null)
146 - )
147 - )
148 -);
149 -```
150 -
151 -> 注意:
152 -> この特徴は [v0.11](/react/blog/2014/07/17/react-v0.11.html#jsx) 以上で使用できます。
153 -
154 -## JavaScriptの表現
155 -
156 -### アトリビュートの表現
157 -
158 -JavaScriptで書いたものをアトリビュートの値として使うためには、その表現を引用(`""`)ではなく波括弧(`{}`)で囲ってください。
159 -
160 -```javascript
161 -// 入力 (JSX):
162 -var person = <Person name={window.isLoggedIn ? window.name : ''} />;
163 -// 出力 (JS):
164 -var person = React.createElement(
165 - Person,
166 - {name: window.isLoggedIn ? window.name : ''}
167 -);
168 -```
169 -
170 -### Booleanのアトリビュート
171 -
172 -アトリビュートの値を記述しないと、JSXはそれを `true` として扱ってしまいます。`false` を渡すためには、アトリビュートが使われる必要があります。これらはHTMLのform要素の `disabled` 、 `required` 、 `checked` 、 `readOnly` といったアトリビュートを使う際によく見かけられます。
173 -
174 -
175 -```javascript
176 -// 以下の2つはボタンを使用不能にするという意味でJSXでは同義です。
177 -<input type="button" disabled />;
178 -<input type="button" disabled={true} />;
179 -
180 -// 以下の2つはボタンを使用不能にしないという意味でJSXでは同義です。
181 -<input type="button" />;
182 -<input type="button" disabled={false} />;
183 -```
184 -
185 -### 子要素の表現
186 -
187 -同様に、JavaScriptは子要素を表現するのに使われることもあります。
188 -
189 -```javascript
190 -// 入力 (JSX):
191 -var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>;
192 -// 出力 (JS):
193 -var content = React.createElement(
194 - Container,
195 - null,
196 - window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login)
197 -);
198 -```
199 -
200 -### コメント
201 -
202 -JSXにコメントを加えるのは簡単です。ただのJSの書き方です。タグの内側にコメントを書く時には、 `{}` で囲うことに注意してください。
203 -
204 -```javascript
205 -var content = (
206 - <Nav>
207 - {/* 子要素にコメントを書く時には、 {} で囲う */}
208 - <Person
209 - /* 複数
210 - 行
211 - コメント */
212 - name={window.isLoggedIn ? window.name : ''} // 行末コメント
213 - />
214 - </Nav>
215 -);
216 -```
217 -
218 -> 注意:
219 -> JSXはHTMLに似ていますが、全く同じではありません。いくつかのキーの違いについては[JSXの理解](/react/docs/jsx-gotchas.html) をご覧ください。
docs/docs/02.1-jsx-in-depth.ko-KR.md deleted
-223
@@ -1,223 +0,0 @@
1 ----
2 -id: jsx-in-depth-ko-KR
3 -title: JSX 깊이보기
4 -permalink: docs/jsx-in-depth-ko-KR.html
5 -prev: displaying-data-ko-KR.html
6 -next: jsx-spread-ko-KR.html
7 ----
8 -
9 -[JSX](https://facebook.github.io/jsx/)는 XML과 비슷한 JavaScript문법 확장입니다. React에서 변환되는 간단한 JSX 구문을 사용하실 수 있습니다.
10 -
11 -## 왜 JSX인가?
12 -
13 -React를 위해 꼭 JSX를 사용할 필요는 없고, 그냥 일반 JS를 사용할 수도 있습니만 JSX를 사용하기를 추천합니다. 왜냐하면, 어트리뷰트를 가진 트리 구조로 정의할 수 있는 간결하고 익숙한 문법이기 때문입니다.
14 -
15 -이것은 디자이너 같은 케쥬얼 개발자에게 더 익숙합니다.
16 -
17 -XML에는 여닫는 태그의 장점이 있습니다. 태그는 큰 트리일 때 함수 호출이나 객체 리터럴보다 읽기 쉬워 집니다.
18 -
19 -JSX는 JavaScript의 시맨틱을 변경하지 않습니다.
20 -
21 -## HTML 태그 vs. React 컴포넌트
22 -
23 -React는 렌더 HTML 태그(문자열)이나 React 컴포넌트(클래스)일 수 있습니다.
24 -
25 -HTML 태그를 렌더하려면, 그냥 JSX에 소문자 태그를 사용하세요.
26 -
27 -```javascript
28 -var myDivElement = <div className="foo" />;
29 -ReactDOM.render(myDivElement, document.getElementById('example'));
30 -```
31 -
32 -React 컴포넌트를 렌더하려면, 대문자로 시작하는 로컬 변수를 만드세요.
33 -
34 -```javascript
35 -var MyComponent = React.createClass({/*...*/});
36 -var myElement = <MyComponent someProperty={true} />;
37 -ReactDOM.render(myElement, document.getElementById('example'));
38 -```
39 -
40 -React JSX는 대소문자를 로컬 컴포넌트 클래스와 HTML 태그를 구별하는 컨벤션으로 사용합니다.
41 -
42 -> 주의:
43 ->
44 -> JSX가 JavaScript기 때문에, `class`, `for`같은 식별자는 XML 어트리뷰트 이름으로
45 -> 권장하지 않습니다. 대신, React DOM 컴포넌트는 각각 `className`, `htmlFor`같은
46 -> DOM 프로퍼티 이름을 기대합니다.
47 -
48 -## 변환
49 -
50 -React JSX는 XML같은 문법에서 네이티브 JavaScript로 변환됩니다. XML 엘리먼트, 어트리뷰트, 자식은 `React.createElement`에 넘겨지는 인자로 변환됩니다.
51 -
52 -```javascript
53 -var Nav;
54 -// 입력 (JSX):
55 -var app = <Nav color="blue" />;
56 -// 출력 (JS):
57 -var app = React.createElement(Nav, {color:"blue"});
58 -```
59 -
60 -`<Nav />`를 사용하려면, `Nav`변수는 스코프에 있어야 합니다.
61 -
62 -JSX에서는 XML 구문으로 자식을 지정할 수도 있습니다.
63 -
64 -```javascript
65 -var Nav, Profile;
66 -// 입력 (JSX):
67 -var app = <Nav color="blue"><Profile>click</Profile></Nav>;
68 -// 출력 (JS):
69 -var app = React.createElement(
70 - Nav,
71 - {color:"blue"},
72 - React.createElement(Profile, null, "click")
73 -);
74 -```
75 -
76 -클래스에 [displayName](/react/docs/component-specs-ko-KR.html#displayname)이 정의되어 있지 않으면 JSX는 변수명을 displayName으로 간주할 것입니다:
77 -
78 -```javascript
79 -// 입력 (JSX):
80 -var Nav = React.createClass({ });
81 -// 출력 (JS):
82 -var Nav = React.createClass({displayName: "Nav", });
83 -```
84 -
85 -[바벨 REPL](https://babeljs.io/repl/)를 보면 JSX에서 어떻게 네이티브 JavaScript로 변환(desugars)하는지 볼 수 있고, [HTML-JSX 변환기](http://magic.reactjs.net/htmltojsx.htm)는 이미 있는 HTML을 JSX로 변환해 줍니다.
86 -
87 -JSX를 사용 하시려면, [시작하기](/react/docs/getting-started-ko-KR.html) 가이드에서 어떻게 컴파일을 하기 위해 설정하는지 보실 수 있습니다.
88 -
89 -> 주의:
90 ->
91 -> JSX 표현식은 언제나 ReactElement로 변환됩니다. 실제 구현의 세부사항은 많이
92 -> 다를 수 있습니다. 최적화 모드는 ReactElement를 `React.createElement`에서 검증
93 -> 코드를 우회하는 객체 리터럴로 ReactElement를 인라인으로 만들 수 있습니다.
94 -
95 -## 네임스페이스를 사용한 컴포넌트
96 -
97 -폼같은 자식을 많이 가지는 컴포넌트를 만든다면, 많은 변수 선언을 하게 될 것입니다.
98 -
99 -```javascript
100 -// 변수 선언의 어색한 블록
101 -var Form = MyFormComponent;
102 -var FormRow = Form.Row;
103 -var FormLabel = Form.Label;
104 -var FormInput = Form.Input;
105 -
106 -var App = (
107 - <Form>
108 - <FormRow>
109 - <FormLabel />
110 - <FormInput />
111 - </FormRow>
112 - </Form>
113 -);
114 -```
115 -
116 -더 간단하고 쉽게 *네임스페이스를 사용한 컴포넌트*를 사용해서, 다른 컴포넌트를 어트리뷰트로 가지는 하나의 컴포넌트만 쓸 수 있습니다.
117 -
118 -```javascript
119 -var Form = MyFormComponent;
120 -
121 -var App = (
122 - <Form>
123 - <Form.Row>
124 - <Form.Label />
125 - <Form.Input />
126 - </Form.Row>
127 - </Form>
128 -);
129 -```
130 -
131 -이렇게 하려면, *"sub-components"*를 메인 컴포넌트의 어트리뷰트로 만들 필요가 있습니다.
132 -
133 -```javascript
134 -var MyFormComponent = React.createClass({ ... });
135 -
136 -MyFormComponent.Row = React.createClass({ ... });
137 -MyFormComponent.Label = React.createClass({ ... });
138 -MyFormComponent.Input = React.createClass({ ... });
139 -```
140 -
141 -코드를 컴파일할 때 JSX는 이것을 제대로 처리해 줍니다.
142 -
143 -```javascript
144 -var App = (
145 - React.createElement(Form, null,
146 - React.createElement(Form.Row, null,
147 - React.createElement(Form.Label, null),
148 - React.createElement(Form.Input, null)
149 - )
150 - )
151 -);
152 -```
153 -
154 -> 주의:
155 ->
156 -> 이 기능은 [v0.11](/react/blog/2014/07/17/react-v0.11.html#jsx) 이상에만 있습니다.
157 -
158 -## JavaScript 표현식
159 -
160 -### 어트리뷰트 표현식
161 -
162 -JavaScript 표현식을 어트리뷰트 값으로 사용하려면, 표현식을 쌍따옴표(`""`)대신 중괄호(`{}`)로 감싸야 합니다.
163 -
164 -```javascript
165 -// 입력 (JSX):
166 -var person = <Person name={window.isLoggedIn ? window.name : ''} />;
167 -// 출력 (JS):
168 -var person = React.createElement(
169 - Person,
170 - {name: window.isLoggedIn ? window.name : ''}
171 -);
172 -```
173 -
174 -### 불린 어트리뷰트
175 -
176 -어트리뷰트의 값을 생략하면 JSX는 값을 `true`로 취급합니다. 어트리뷰트 표현식에 `false`를 넘기려면 사용해야만 합니다. HTML 폼 엘리먼트에 `disabled`, `required`, `checked`, `readOnly`같은 어트리뷰트를 사용할 일이 자주 있습니다.
177 -
178 -```javascript
179 -// JSX에서 이 두 줄은 똑같이 버튼을 비활성화합니다.
180 -<input type="button" disabled />;
181 -<input type="button" disabled={true} />;
182 -
183 -// 그리고 JSX에서 이 두 줄은 똑같이 버튼을 비활성화하지 않습니다.
184 -<input type="button" />;
185 -<input type="button" disabled={false} />;
186 -```
187 -
188 -### 자식 표현식
189 -
190 -비슷하게, JavaScript 표현식을 자식을 표현하는 데 사용할 수 있습니다.
191 -
192 -```javascript
193 -// 입력 (JSX):
194 -var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>;
195 -// 출력 (JS):
196 -var content = React.createElement(
197 - Container,
198 - null,
199 - window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login)
200 -);
201 -```
202 -
203 -### 주석
204 -
205 -JSX에 주석을 넣기는 쉽습니다. 그냥 JS 표현식과 같습니다. 그냥 태그의 자식 섹션에서만 조심하시면 됩니다. 이럴 땐 주석 주변에 `{}`를 감싸야 합니다.
206 -
207 -```javascript
208 -var content = (
209 - <Nav>
210 - {/* 자식 주석, {}로 감싼다 */}
211 - <Person
212 - /* 여러
213 - 줄
214 - 주석 */
215 - name={window.isLoggedIn ? window.name : ''} // 줄 끝부분 주석
216 - />
217 - </Nav>
218 -);
219 -```
220 -
221 -> 주의:
222 ->
223 -> JSX 는 HTML과 비슷하지만 완전히 같지는 않습니다. 중요한 차이점을 보시려면 [JSX gotchas](/react/docs/jsx-gotchas-ko-KR.html)를 보세요.
docs/docs/02.1-jsx-in-depth.md deleted
-224
@@ -1,224 +0,0 @@
1 ----
2 -id: jsx-in-depth
3 -title: JSX in Depth
4 -permalink: docs/jsx-in-depth.html
5 -prev: displaying-data.html
6 -next: jsx-spread.html
7 ----
8 -
9 -[JSX](https://facebook.github.io/jsx/) is a JavaScript syntax extension that looks similar to XML. You can use a simple JSX syntactic transform with React.
10 -
11 -## Why JSX?
12 -
13 -You don't have to use JSX with React. You can just use plain JS. However, we recommend using JSX because it is a concise and familiar syntax for defining tree structures with attributes.
14 -
15 -It's more familiar for casual developers such as designers.
16 -
17 -XML has the benefit of balanced opening and closing tags. This helps make large trees easier to read than function calls or object literals.
18 -
19 -It doesn't alter the semantics of JavaScript.
20 -
21 -## HTML Tags vs. React Components
22 -
23 -React can either render HTML tags (strings) or React components (classes).
24 -
25 -To render an HTML tag, just use lower-case tag names in JSX:
26 -
27 -```javascript
28 -var myDivElement = <div className="foo" />;
29 -ReactDOM.render(myDivElement, document.getElementById('example'));
30 -```
31 -
32 -To render a React Component, just create a local variable that starts with an upper-case letter:
33 -
34 -```javascript
35 -var MyComponent = React.createClass({/*...*/});
36 -var myElement = <MyComponent someProperty={true} />;
37 -ReactDOM.render(myElement, document.getElementById('example'));
38 -```
39 -
40 -React's JSX uses the upper vs. lower case convention to distinguish between local component classes and HTML tags.
41 -
42 -> Note:
43 ->
44 -> Since JSX is JavaScript, identifiers such as `class` and `for` are discouraged
45 -> as XML attribute names. Instead, React DOM components expect DOM property
46 -> names like `className` and `htmlFor`, respectively.
47 -
48 -## The Transform
49 -
50 -React JSX transforms from an XML-like syntax into native JavaScript. XML elements, attributes and children are transformed into arguments that are passed to `React.createElement`.
51 -
52 -```javascript
53 -var Nav;
54 -// Input (JSX):
55 -var app = <Nav color="blue" />;
56 -// Output (JS):
57 -var app = React.createElement(Nav, {color:"blue"});
58 -```
59 -
60 -Notice that in order to use `<Nav />`, the `Nav` variable must be in scope.
61 -
62 -JSX also allows specifying children using XML syntax:
63 -
64 -```javascript
65 -var Nav, Profile;
66 -// Input (JSX):
67 -var app = <Nav color="blue"><Profile>click</Profile></Nav>;
68 -// Output (JS):
69 -var app = React.createElement(
70 - Nav,
71 - {color:"blue"},
72 - React.createElement(Profile, null, "click")
73 -);
74 -```
75 -
76 -JSX will infer the class's [displayName](/react/docs/component-specs.html#displayname) from the variable assignment when the displayName is undefined:
77 -
78 -```javascript
79 -// Input (JSX):
80 -var Nav = React.createClass({ });
81 -// Output (JS):
82 -var Nav = React.createClass({displayName: "Nav", });
83 -```
84 -
85 -Use the [Babel REPL](https://babeljs.io/repl/) to try out JSX and see how it desugars into native JavaScript, and the [HTML to JSX converter](http://magic.reactjs.net/htmltojsx.htm) to convert your existing HTML to JSX.
86 -
87 -If you want to use JSX, the [Getting Started](/react/docs/getting-started.html) guide shows how to set up compilation.
88 -
89 -> Note:
90 ->
91 -> The JSX expression always evaluates to a ReactElement. The actual
92 -> implementation details may vary. An optimized mode could inline the
93 -> ReactElement as an object literal to bypass the validation code in
94 -> `React.createElement`.
95 -
96 -## Namespaced Components
97 -
98 -If you are building a component that has many children, like a form, you might end up with something with a lot of variable declarations:
99 -
100 -```javascript
101 -// Awkward block of variable declarations
102 -var Form = MyFormComponent;
103 -var FormRow = Form.Row;
104 -var FormLabel = Form.Label;
105 -var FormInput = Form.Input;
106 -
107 -var App = (
108 - <Form>
109 - <FormRow>
110 - <FormLabel />
111 - <FormInput />
112 - </FormRow>
113 - </Form>
114 -);
115 -```
116 -
117 -To make it simpler and easier, *namespaced components* let you use one component that has other components as attributes:
118 -
119 -```javascript
120 -var Form = MyFormComponent;
121 -
122 -var App = (
123 - <Form>
124 - <Form.Row>
125 - <Form.Label />
126 - <Form.Input />
127 - </Form.Row>
128 - </Form>
129 -);
130 -```
131 -
132 -To do this, you just need to create your *"sub-components"* as attributes of the main component:
133 -
134 -```javascript
135 -var MyFormComponent = React.createClass({ ... });
136 -
137 -MyFormComponent.Row = React.createClass({ ... });
138 -MyFormComponent.Label = React.createClass({ ... });
139 -MyFormComponent.Input = React.createClass({ ... });
140 -```
141 -
142 -JSX will handle this properly when compiling your code.
143 -
144 -```javascript
145 -var App = (
146 - React.createElement(Form, null,
147 - React.createElement(Form.Row, null,
148 - React.createElement(Form.Label, null),
149 - React.createElement(Form.Input, null)
150 - )
151 - )
152 -);
153 -```
154 -
155 -> Note:
156 ->
157 -> This feature is available in [v0.11](/react/blog/2014/07/17/react-v0.11.html#jsx) and above.
158 -
159 -## JavaScript Expressions
160 -
161 -### Attribute Expressions
162 -
163 -To use a JavaScript expression as an attribute value, wrap the expression in a pair of curly braces (`{}`) instead of quotes (`""`).
164 -
165 -```javascript
166 -// Input (JSX):
167 -var person = <Person name={window.isLoggedIn ? window.name : ''} />;
168 -// Output (JS):
169 -var person = React.createElement(
170 - Person,
171 - {name: window.isLoggedIn ? window.name : ''}
172 -);
173 -```
174 -
175 -### Boolean Attributes
176 -
177 -Omitting the value of an attribute causes JSX to treat it as `true`. To pass `false` an attribute expression must be used. This often comes up when using HTML form elements, with attributes like `disabled`, `required`, `checked` and `readOnly`.
178 -
179 -```javascript
180 -// These two are equivalent in JSX for disabling a button
181 -<input type="button" disabled />;
182 -<input type="button" disabled={true} />;
183 -
184 -// And these two are equivalent in JSX for not disabling a button
185 -<input type="button" />;
186 -<input type="button" disabled={false} />;
187 -```
188 -
189 -### Child Expressions
190 -
191 -Likewise, JavaScript expressions may be used to express children:
192 -
193 -```javascript
194 -// Input (JSX):
195 -var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>;
196 -// Output (JS):
197 -var content = React.createElement(
198 - Container,
199 - null,
200 - window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login)
201 -);
202 -```
203 -
204 -### Comments
205 -
206 -It's easy to add comments within your JSX; they're just JS expressions. You just need to be careful to put `{}` around the comments when you are within the children section of a tag.
207 -
208 -```javascript
209 -var content = (
210 - <Nav>
211 - {/* child comment, put {} around */}
212 - <Person
213 - /* multi
214 - line
215 - comment */
216 - name={window.isLoggedIn ? window.name : ''} // end of line comment
217 - />
218 - </Nav>
219 -);
220 -```
221 -
222 -> NOTE:
223 ->
224 -> JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences.
docs/docs/02.1-jsx-in-depth.zh-CN.md deleted
-224
@@ -1,224 +0,0 @@
1 ----
2 -id: jsx-in-depth-zh-CN
3 -title: 深入 JSX
4 -permalink: docs/jsx-in-depth-zh-CN.html
5 -prev: displaying-data-zh-CN.html
6 -next: jsx-spread-zh-CN.html
7 ----
8 -
9 -[JSX](https://facebook.github.io/jsx/) 是一个看起来很像 XML 的 JavaScript 语法扩展。React 可以用来做简单的 JSX 句法转换。
10 -
11 -## 为什么要用 JSX?
12 -
13 -你不需要为了 React 使用 JSX,可以直接使用原生 JS。但是,我们建议使用 JSX 是因为它能精确,也是常用的定义包含属性的树状结构的语法。
14 -
15 -它对于非专职开发者比如设计师也比较熟悉。
16 -
17 -XML 有固定的标签开启和闭合的优点。这能让复杂的树更易于阅读,优于方法调用和对象字面量的形式。
18 -
19 -它没有修改 JavaScript 语义。
20 -
21 -
22 -## HTML 标签对比 React 组件
23 -
24 -React 可以渲染 HTML 标签 (strings) 或 React 组件 (classes)。
25 -
26 -要渲染 HTML 标签,只需在 JSX 里使用小写字母的标签名。
27 -
28 -```javascript
29 -var myDivElement = <div className="foo" />;
30 -ReactDOM.render(myDivElement, document.getElementById('example'));
31 -```
32 -
33 -要渲染 React 组件,只需创建一个大写字母开头的本地变量。
34 -
35 -```javascript
36 -var MyComponent = React.createClass({/*...*/});
37 -var myElement = <MyComponent someProperty={true} />;
38 -ReactDOM.render(myElement, document.getElementById('example'));
39 -```
40 -
41 -React 的 JSX 使用大、小写的约定来区分本地组件的类和 HTML 标签。
42 -
43 -> 注意:
44 ->
45 -> 由于 JSX 就是 JavaScript,一些标识符像 `class` 和 `for` 不建议作为 XML
46 -> 属性名。作为替代,React DOM 使用 `className` 和 `htmlFor` 来做对应的属性。
47 -
48 -## 转换(Transform)
49 -
50 -JSX 把类 XML 的语法转成原生 JavaScript,XML 元素、属性和子节点被转换成 `React.createElement` 的参数。
51 -
52 -```javascript
53 -var Nav;
54 -// 输入 (JSX):
55 -var app = <Nav color="blue" />;
56 -// 输出 (JS):
57 -var app = React.createElement(Nav, {color:"blue"});
58 -```
59 -
60 -注意,要想使用 `<Nav />`,`Nav` 变量一定要在作用区间内。
61 -
62 -JSX 也支持使用 XML 语法定义子结点:
63 -
64 -```javascript
65 -var Nav, Profile;
66 -// 输入 (JSX):
67 -var app = <Nav color="blue"><Profile>click</Profile></Nav>;
68 -// 输出 (JS):
69 -var app = React.createElement(
70 - Nav,
71 - {color:"blue"},
72 - React.createElement(Profile, null, "click")
73 -);
74 -```
75 -
76 -当显示名称没有定义时,JSX 会根据变量赋值来推断类的 [显示名称](/react/docs/component-specs.html#displayname) :
77 -
78 -```javascript
79 -// 输入 (JSX):
80 -var Nav = React.createClass({ });
81 -// 输出 (JS):
82 -var Nav = React.createClass({displayName: "Nav", });
83 -```
84 -
85 -使用 [JSX 编译器](/react/jsx-compiler.html) 来试用 JSX 并理解它是如何转换到原生 JavaScript,还有 [HTML 到 JSX 转换器](http://magic.reactjs.net/htmltojsx.htm) 来把现有 HTML 转成 JSX。
86 -
87 -如果你要使用 JSX,这篇 [新手入门](/react/docs/getting-started.html) 教程来教你如何搭建环境。
88 -
89 -> 注意:
90 ->
91 ->
92 -> JSX 表达式总是会当作 ReactElement 执行。具体的实际细节可能不同。一种优化
93 -> 的模式是把 ReactElement 当作一个行内的对象字面量形式来绕过
94 -> `React.createElement` 里的校验代码。
95 -
96 -## 命名组件(Namespaced Components)
97 -
98 -如果你正在构建一个有很多子组件的组件,比如表单,你也许会最终得到许多的变量声明。
99 -
100 -```javascript
101 -// 尴尬的变量声明块
102 -var Form = MyFormComponent;
103 -var FormRow = Form.Row;
104 -var FormLabel = Form.Label;
105 -var FormInput = Form.Input;
106 -
107 -var App = (
108 - <Form>
109 - <FormRow>
110 - <FormLabel />
111 - <FormInput />
112 - </FormRow>
113 - </Form>
114 -);
115 -```
116 -
117 -为了使其更简单和容易,*命名组件*令你使用包含其他组件作为属性的单一的组件。
118 -
119 -```javascript
120 -var Form = MyFormComponent;
121 -
122 -var App = (
123 - <Form>
124 - <Form.Row>
125 - <Form.Label />
126 - <Form.Input />
127 - </Form.Row>
128 - </Form>
129 -);
130 -```
131 -
132 -要做到这一点,你只需要把你的*"子组件"*创建为主组件的属性。
133 -
134 -```javascript
135 -var MyFormComponent = React.createClass({ ... });
136 -
137 -MyFormComponent.Row = React.createClass({ ... });
138 -MyFormComponent.Label = React.createClass({ ... });
139 -MyFormComponent.Input = React.createClass({ ... });
140 -```
141 -
142 -当编译你的代码时,JSX会恰当的进行处理。
143 -
144 -```javascript
145 -var App = (
146 - React.createElement(Form, null,
147 - React.createElement(Form.Row, null,
148 - React.createElement(Form.Label, null),
149 - React.createElement(Form.Input, null)
150 - )
151 - )
152 -);
153 -```
154 -
155 -> 注意:
156 ->
157 -> 此特性在 [v0.11](/react/blog/2014/07/17/react-v0.11.html#jsx) 及以上可用.
158 -
159 -## JavaScript 表达式
160 -
161 -### 属性表达式
162 -
163 -要使用 JavaScript 表达式作为属性值,只需把这个表达式用一对大括号 (`{}`) 包起来,不要用引号 (`""`)。
164 -
165 -```javascript
166 -// 输入 (JSX):
167 -var person = <Person name={window.isLoggedIn ? window.name : ''} />;
168 -// 输出 (JS):
169 -var person = React.createElement(
170 - Person,
171 - {name: window.isLoggedIn ? window.name : ''}
172 -);
173 -```
174 -
175 -### Boolean 属性
176 -
177 -省略一个属性的值会导致JSX把它当做 `true`。要传值 `false`必须使用属性表达式。这常出现于使用HTML表单元素,含有属性如`disabled`, `required`, `checked` 和 `readOnly`。
178 -
179 -```javascript
180 -// 在JSX中,对于禁用按钮这二者是相同的。
181 -<input type="button" disabled />;
182 -<input type="button" disabled={true} />;
183 -
184 -// 在JSX中,对于不禁用按钮这二者是相同的。
185 -<input type="button" />;
186 -<input type="button" disabled={false} />;
187 -```
188 -
189 -### 子节点表达式
190 -
191 -同样地,JavaScript 表达式可用于描述子结点:
192 -
193 -```javascript
194 -// 输入 (JSX):
195 -var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>;
196 -// 输出 (JS):
197 -var content = React.createElement(
198 - Container,
199 - null,
200 - window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login)
201 -);
202 -```
203 -
204 -### 注释
205 -
206 -JSX 里添加注释很容易;它们只是 JS 表达式而已。你仅仅需要小心的是当你在一个标签的子节点块时,要用 `{}` 包围要注释的部分。
207 -
208 -```javascript
209 -var content = (
210 - <Nav>
211 - {/* child comment, 用 {} 包围 */}
212 - <Person
213 - /* 多
214 - 行
215 - 注释 */
216 - name={window.isLoggedIn ? window.name : ''} // 行尾注释
217 - />
218 - </Nav>
219 -);
220 -```
221 -
222 -> 注意:
223 ->
224 -> JSX 类似于 HTML,但不完全一样。参考 [JSX 陷阱](/react/docs/jsx-gotchas-zh-CN.html) 了解主要不同。
docs/docs/02.2-jsx-spread.it-IT.md deleted
-52
@@ -1,52 +0,0 @@
1 ----
2 -id: jsx-spread-it-IT
3 -title: Attributi Spread JSX
4 -permalink: docs/jsx-spread-it-IT.html
5 -prev: jsx-in-depth-it-IT.html
6 -next: jsx-gotchas-it-IT.html
7 ----
8 -
9 -Se sai in anticipo che tutte le proprietà che desideri assegnare ad un componente, usare JSX è facile:
10 -
11 -```javascript
12 - var component = <Component foo={x} bar={y} />;
13 -```
14 -
15 -## Le Props Mutevoli sono il Male
16 -
17 -Se non sai quali proprietà desideri impostare, potresti essere tentato di aggiungerle all'oggetto in seguito:
18 -
19 -```javascript
20 - var component = <Component />;
21 - component.props.foo = x; // male
22 - component.props.bar = y; // altrettanto male
23 -```
24 -
25 -Questo è un anti-pattern perché significa che non possiamo aiutarti a verificare i propTypes per tempo. Ciò significa che i tuoi errori di propTypes finiscono per avere uno stack trace indecifrabile.
26 -
27 -Le props dovrebbero essere considerate immutabili. Mutare l'oggetto props altrove potrebbe causare conseguenze inattese, quindi a questo punto dovrebbe essere idealmente considerato un oggetto congelato.
28 -
29 -## Attributi Spread
30 -
31 -Adesso puoi utilizzare una nuova caratteristica di JSX chiamata attributi spread:
32 -
33 -```javascript
34 - var props = {};
35 - props.foo = x;
36 - props.bar = y;
37 - var component = <Component {...props} />;
38 -```
39 -
40 -Le proprietà dell'oggetto che passi al componente sono copiate nelle sue props.
41 -
42 -Puoi usarlo più volte o combinarlo con altri attributi. L'ordine in cui sono specificati è rilevante. Attributi successivi ridefiniscono quelli precedentemente impostati.
43 -
44 -```javascript
45 - var props = { foo: 'default' };
46 - var component = <Component {...props} foo={'override'} />;
47 - console.log(component.props.foo); // 'override'
48 -```
49 -
50 -## Cos'è la strana notazione `...`?
51 -
52 -L'operatore `...` (o operatore spread) è già supportato per gli [array in ES6](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). Esiste anche una proposta per ES7 per le proprietà [Spread e Rest di Object](https://github.com/sebmarkbage/ecmascript-rest-spread). Stiamo prendendo spunto da questi standard supportati o in corso di sviluppo per fornire una sintassi più pulita a JSX.
docs/docs/02.2-jsx-spread.ja-JP.md deleted
-52
@@ -1,52 +0,0 @@
1 ----
2 -id: jsx-spread
3 -title: JSXの拡張属性
4 -permalink: docs/jsx-spread-ja-JP.html
5 -prev: jsx-in-depth-ja-JP.html
6 -next: jsx-gotchas-ja-JP.html
7 ----
8 -
9 -以下のように、コンポーネントにどのようなプロパティを配置したいか前もって全て分かっている場合は、JSXを使うことは簡単です。
10 -
11 -```javascript
12 - var component = <Component foo={x} bar={y} />;
13 -```
14 -
15 -## Propsを変更してはいけない
16 -
17 -セットしたいプロパティが分からない場合は、以下のように後からオブジェクトに追加したいと思うでしょう。
18 -
19 -```javascript
20 - var component = <Component />;
21 - component.props.foo = x; // だめ
22 - component.props.bar = y; // 同様にだめ
23 -```
24 -
25 -これはアンチパターンです。なぜなら、後々まで正しいpropTypesであるかどうかチェックすることを助けることができないことを意味するからです。これは、propTypesのエラーが隠されたスタックトレースに出力されて終わってしまうことを意味します。
26 -
27 -propsは変更不可と考えられるべきです。propsのオブジェクトをどこかで変更することは予期せぬ結果を発生させる可能性があるので、理想的には、この時点ではpropsは固定のオブジェクトであるべきです。
28 -
29 -## 拡張属性
30 -
31 -以下のように、拡張属性というJSXの新しい特徴を使うことができます。
32 -
33 -```javascript
34 - var props = {};
35 - props.foo = x;
36 - props.bar = y;
37 - var component = <Component {...props} />;
38 -```
39 -
40 -あなたが渡したオブジェクトのプロパティはコンポーネントのpropsにコピーされます。
41 -
42 -これを複数回使用したり、他の属性と組み合わせたりすることもできます。仕様書では、順序が重要となっています。後の属性は前の属性をオーバーライドします。
43 -
44 -```javascript
45 - var props = { foo: 'default' };
46 - var component = <Component {...props} foo={'override'} />;
47 - console.log(component.props.foo); // 'override'
48 -```
49 -
50 -## 奇妙な `...` という表現は何でしょうか?
51 -
52 -`...` 操作(拡張操作)は既に[ES6のarrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)でサポートされています。[Object Rest と Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread)のES7のプロポーザルもあります。JSXのきれいなシンタックスを供給するために、それらのサポートや開発中の標準使用を利用しています。
docs/docs/02.2-jsx-spread.ko-KR.md deleted
-52
@@ -1,52 +0,0 @@
1 ----
2 -id: jsx-spread-ko-KR
3 -title: JSX 스프레드 어트리뷰트
4 -permalink: docs/jsx-spread-ko-KR.html
5 -prev: jsx-in-depth-ko-KR.html
6 -next: jsx-gotchas-ko-KR.html
7 ----
8 -
9 -미리 컴포넌트에 넣을 모든 프로퍼티를 알게 된다면, JSX를 사용하기 쉬워집니다.
10 -
11 -```javascript
12 - var component = <Component foo={x} bar={y} />;
13 -```
14 -
15 -## Props의 변경은 나빠요
16 -
17 -하지만 어떤 프로퍼티를 설정하고 싶은지 모른다면, 객체 레이어에 넣고 싶어질 수도 있습니다.
18 -
19 -```javascript
20 - var component = <Component />;
21 - component.props.foo = x; // 나쁨
22 - component.props.bar = y; // 역시 나쁨
23 -```
24 -
25 -이것은 안티 패턴입니다. 왜냐하면 한참 뒤까지 정확한 propTypes을 체크할 수 없다는 뜻이기 때문입니다. 이것은 propTypes 에러는 알기 힘든 스택 트레이스로 끝난다는 의미입니다.
26 -
27 -props는 변하지 않는 것으로 간주해야 합니다. props 객체를 변경하는 것은 다른 곳에서 예기치 못한 결과가 생길 수 있기 때문에 이상적으로는 이 시점에서 frozen 객체가 되어야 합니다.
28 -
29 -## 스프레드 어트리뷰트
30 -
31 -이제 JSX의 새로운 기능인 스프레드 어트리뷰트를 사용하실 수 있습니다.
32 -
33 -```javascript
34 - var props = {};
35 - props.foo = x;
36 - props.bar = y;
37 - var component = <Component {...props} />;
38 -```
39 -
40 -전달한 객체의 프로퍼티가 컴포넌트의 props에 복사됩니다.
41 -
42 -이렇게 여러 번 사용하거나 다른 어트리뷰트와 조합해서 사용할 수 있습니다. 명세의 순서는 중요합니다. 나중의 어트리뷰트가 이전 것보다 우선되기 때문입니다.
43 -
44 -```javascript
45 - var props = { foo: 'default' };
46 - var component = <Component {...props} foo={'override'} />;
47 - console.log(component.props.foo); // 'override'
48 -```
49 -
50 -## 이상한 `...` 표기법은 무엇인가요?
51 -
52 -`...` 연산자(스프레드 연산자)는 이미 [ES6의 배열](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)에서 지원합니다. [객체 rest와 스프레드 프로퍼티](https://github.com/sebmarkbage/ecmascript-rest-spread)에 대한 ES7의 제안도 있습니다. JSX의 구문을 더 깔끔하게 하기 위해 지원되고 개발중인 표준을 활용하고 있습니다.
docs/docs/02.2-jsx-spread.md deleted
-52
@@ -1,52 +0,0 @@
1 ----
2 -id: jsx-spread
3 -title: JSX Spread Attributes
4 -permalink: docs/jsx-spread.html
5 -prev: jsx-in-depth.html
6 -next: jsx-gotchas.html
7 ----
8 -
9 -If you know all the properties that you want to place on a component ahead of time, it is easy to use JSX:
10 -
11 -```javascript
12 - var component = <Component foo={x} bar={y} />;
13 -```
14 -
15 -## Mutating Props is Bad
16 -
17 -If you don't know which properties you want to set, you might be tempted to add them onto the object later:
18 -
19 -```javascript
20 - var component = <Component />;
21 - component.props.foo = x; // bad
22 - component.props.bar = y; // also bad
23 -```
24 -
25 -This is an anti-pattern because it means that we can't help you check the right propTypes until way later. This means that your propTypes errors end up with a cryptic stack trace.
26 -
27 -The props should be considered immutable. Mutating the props object somewhere else could cause unexpected consequences so ideally it would be a frozen object at this point.
28 -
29 -## Spread Attributes
30 -
31 -Now you can use a new feature of JSX called spread attributes:
32 -
33 -```javascript
34 - var props = {};
35 - props.foo = x;
36 - props.bar = y;
37 - var component = <Component {...props} />;
38 -```
39 -
40 -The properties of the object that you pass in are copied onto the component's props.
41 -
42 -You can use this multiple times or combine it with other attributes. The specification order is important. Later attributes override previous ones.
43 -
44 -```javascript
45 - var props = { foo: 'default' };
46 - var component = <Component {...props} foo={'override'} />;
47 - console.log(component.props.foo); // 'override'
48 -```
49 -
50 -## What's with the weird `...` notation?
51 -
52 -The `...` operator (or spread operator) is already supported for [arrays in ES6](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). There is also an ECMAScript proposal for [Object Rest and Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread). We're taking advantage of these supported and developing standards in order to provide a cleaner syntax in JSX.
docs/docs/02.2-jsx-spread.zh-CN.md deleted
-52
@@ -1,52 +0,0 @@
1 ----
2 -id: jsx-spread-zh-CN
3 -title: JSX 展开属性
4 -permalink: docs/jsx-spread-zh-CN.html
5 -prev: jsx-in-depth-zh-CN.html
6 -next: jsx-gotchas-zh-CN.html
7 ----
8 -
9 -如果你事先知道组件需要的全部 Props(属性),JSX 很容易地这样写:
10 -
11 -```javascript
12 - var component = <Component foo={x} bar={y} />;
13 -```
14 -
15 -## 修改 Props 是不好的,明白吗
16 -
17 -如果你不知道要设置哪些 Props,那么现在最好不要设置它:
18 -
19 -```javascript
20 - var component = <Component />;
21 - component.props.foo = x; // 不好
22 - component.props.bar = y; // 同样不好
23 -```
24 -
25 -这样是反模式,因为 React 不能帮你检查属性类型(propTypes)。这样即使你的 属性类型有错误也不能得到清晰的错误提示。
26 -
27 -Props 应该被认为是不可变的。在别处修改 props 对象可能会导致预料之外的结果,所以原则上这将是一个冻结的对象。
28 -
29 -## 展开属性(Spread Attributes)
30 -
31 -现在你可以使用 JSX 的新特性 - 展开属性:
32 -
33 -```javascript
34 - var props = {};
35 - props.foo = x;
36 - props.bar = y;
37 - var component = <Component {...props} />;
38 -```
39 -
40 -传入对象的属性会被复制到组件内。
41 -
42 -它能被多次使用,也可以和其它属性一起用。注意顺序很重要,后面的会覆盖掉前面的。
43 -
44 -```javascript
45 - var props = { foo: 'default' };
46 - var component = <Component {...props} foo={'override'} />;
47 - console.log(component.props.foo); // 'override'
48 -```
49 -
50 -## 这个奇怪的 `...` 标记是什么?
51 -
52 -这个 `...` 操作符(增强的操作符)已经被 [ES6 数组](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator) 支持。相关的还有 ECMAScript 规范草案中的 [Object 剩余和展开属性(Rest and Spread Properties)](https://github.com/sebmarkbage/ecmascript-rest-spread)。我们利用了这些还在制定中标准中已经被支持的特性来使 JSX 拥有更优雅的语法。
docs/docs/02.3-jsx-gotchas.it-IT.md deleted
-68
@@ -1,68 +0,0 @@
1 ----
2 -id: jsx-gotchas-it-IT
3 -title: JSX Gotchas
4 -permalink: docs/jsx-gotchas-it-IT.html
5 -prev: jsx-spread-it-IT.html
6 -next: interactivity-and-dynamic-uis-it-IT.html
7 ----
8 -
9 -JSX somiglia all'HTML ma ci sono delle differenze importanti da tenere in considerazione.
10 -
11 -> Nota:
12 ->
13 -> Per le differenze del DOM, come l'attributo `style` in linea, consulta [here](/react/docs/dom-differences-it-IT.html).
14 -
15 -## Entità HTML
16 -
17 -Puoi inserire entità HTML nel testo letterale in JSX:
18 -
19 -```javascript
20 -<div>Primo &middot; Secondo</div>
21 -```
22 -
23 -Se desideri visualizzare un'entità HTML all'interno di un contenuto dinamico, avrai problemi con il doppio escape, poiché React effettua in maniera predefinita l'escape di tutte le stringhe visualizzate per prevenire un'ampia gamma di attacchi XSS.
24 -
25 -```javascript
26 -// Male: Mostra "Primo &middot; Secondo"
27 -<div>{'Primo &middot; Secondo'}</div>
28 -```
29 -
30 -Esistono molte maniere di aggirare questo problema. La più facile è scrivere i caratteri Unicode direttamente in JavaScript. Dovrai assicurarti che il file sia salvato come UTF-8 e che le appropriate direttive UTF-8 siano impostate in modo che il browser li visualizzi correttamente.
31 -
32 -```javascript
33 -<div>{'Primo · Secondo'}</div>
34 -```
35 -
36 -Un'alternativa più sicura consiste nel trovare il [codice Unicode corrispondente all'entità](http://www.fileformat.info/info/unicode/char/b7/index.htm) e usarlo all'interno di una stringa JavaScript.
37 -
38 -```javascript
39 -<div>{'Primo \u00b7 Secondo'}</div>
40 -<div>{'Primo ' + String.fromCharCode(183) + ' Secondo'}</div>
41 -```
42 -
43 -Puoi usare array misti con stringhe ed elementi JSX.
44 -
45 -```javascript
46 -<div>{['Primo ', <span>&middot;</span>, ' Secondo']}</div>
47 -```
48 -
49 -Come ultima risorsa, puoi sempre [inserire HTML nativo](/react/tips/dangerously-set-inner-html.html).
50 -
51 -```javascript
52 -<div dangerouslySetInnerHTML={{'{{'}}__html: 'Primo &middot; Secondo'}} />
53 -```
54 -
55 -
56 -## Attributi HTML Personalizzati
57 -
58 -Se passi proprietà che non esistono nella specifica HTML ad elementi HTML nativi, React li ignorerà. Se vuoi usare un attributo personalizzato, devi prefiggerlo con `data-`.
59 -
60 -```javascript
61 -<div data-custom-attribute="foo" />
62 -```
63 -
64 -Gli attributi per [l'Accessibilità del Web](http://www.w3.org/WAI/intro/aria) che iniziano per `aria-` saranno gestiti correttamente.
65 -
66 -```javascript
67 -<div aria-hidden={true} />
68 -```
docs/docs/02.3-jsx-gotchas.ja-JP.md deleted
-68
@@ -1,68 +0,0 @@
1 ----
2 -id: jsx-gotchas
3 -title: JSXの理解
4 -permalink: docs/jsx-gotchas-ja-JP.html
5 -prev: jsx-spread-ja-JP.html
6 -next: interactivity-and-dynamic-uis-ja-JP.html
7 -
8 ----
9 -
10 -JSXはHTMLに似ていますが、重要な違いがいくつかあります。
11 -
12 -> 注意:
13 -> インラインの `style` 属性のようなDOMの違いについては、[こちら](/react/docs/dom-differences.html)を確認してください。
14 -
15 -## HTMLのエンティティ
16 -
17 -以下のように、JSXの文字のテキストの中にHTMLのエンティティを挿入することができます。
18 -
19 -```javascript
20 -<div>First &middot; Second</div>
21 -```
22 -
23 -動的なコンテンツとしてHTMLのエンティティを表示する際に、ダブルエスケープを書いてしまうことがあるかと思いますが、Reactはデフォルトで広い範囲のXSS攻撃を防ぐために表示しようとしている全ての文字列をエスケープします。
24 -
25 -```javascript
26 -// 悪い例: 以下は "First &middot; Second" を表示します。
27 -<div>{'First &middot; Second'}</div>
28 -```
29 -
30 -この問題を防止するためにはいくつかの方法があります。最も簡単な方法は、unicodeの文字を直でJavaScriptに記述する方法です。その際には、ファイルがUTF-8で保存されていることと、ブラウザが正しく表示できるように、UTF-8で表示する命令が正しくセットされていることを確認してください。
31 -
32 -```javascript
33 -<div>{'First · Second'}</div>
34 -```
35 -
36 -さらに安全な代替の方法は、[エンティティに対応するunicodeの数値](http://www.fileformat.info/info/unicode/char/b7/index.htm)を見つけて、JavaScriptの文字列の中でそれを使うことです。
37 -
38 -```javascript
39 -<div>{'First \u00b7 Second'}</div>
40 -<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>
41 -```
42 -
43 -配列と文字列とJSXの要素を混ぜて使うこともできます。
44 -
45 -```javascript
46 -<div>{['First ', <span>&middot;</span>, ' Second']}</div>
47 -```
48 -
49 -最後の手段として、常に[生のHTMLを挿入](/react/tips/dangerously-set-inner-html.html)することもできます。
50 -
51 -```javascript
52 -<div dangerouslySetInnerHTML={{'{{'}}__html: 'First &middot; Second'}} />
53 -```
54 -
55 -
56 -## カスタムされたHTMLの属性
57 -
58 -HTMLの仕様書に存在しない要素をネイティブなHTML要素に渡した場合は、Reactはそれらをレンダリングしません。カスタムした属性を使う場合は、 `data-` を頭につけてください。
59 -
60 -```javascript
61 -<div data-custom-attribute="foo" />
62 -```
63 -
64 -`aria-` から始まる[Webアクセシビリティ](http://www.w3.org/WAI/intro/aria)属性はプロパティをレンダリングします。
65 -
66 -```javascript
67 -<div aria-hidden={true} />
68 -```
docs/docs/02.3-jsx-gotchas.ko-KR.md deleted
-68
@@ -1,68 +0,0 @@
1 ----
2 -id: jsx-gotchas-ko-KR
3 -title: JSX Gotchas
4 -permalink: docs/jsx-gotchas-ko-KR.html
5 -prev: jsx-spread-ko-KR.html
6 -next: interactivity-and-dynamic-uis-ko-KR.html
7 ----
8 -
9 -JSX는 HTML처럼 보이지만, 작업하다 보면 마주치게 될 몇 가지 중요한 차이점이 있습니다.
10 -
11 -> 주의:
12 ->
13 -> 인라인 `style` 어트리뷰트 같은 DOM과의 차이점은 [여기](/react/tips/dangerously-set-inner-html-ko-KR.html)를 보세요.
14 -
15 -## HTML 엔티티
16 -
17 -JSX의 리터럴 텍스트에 HTML 엔티티를 넣을 수 있습니다.
18 -
19 -```javascript
20 -<div>First &middot; Second</div>
21 -```
22 -
23 -동적 콘텐츠 안에 HTML 엔티티를 표시하려 할 때, React에서는 XSS 공격을 광범위하게 막기 위해서 기본적으로 모든 표시하는 문자열을 이스케이프 하기 때문에 더블 이스케이프 문제에 부딪히게 됩니다.
24 -
25 -```javascript
26 -// 나쁨: "First &middot; Second"를 표시
27 -<div>{'First &middot; Second'}</div>
28 -```
29 -
30 -이 이슈를 피해 갈 방법은 여럿 있지만, 가장 쉬운 방법은 유니코드 문자를 JavaScript에 직접 쓰는 것입니다. 브라우저가 올바르게 표시하도록 파일이 UTF-8으로 저장되어 있고 올바른 UTF-8 지시자를 사용하고 있는지 확인해야 합니다.
31 -
32 -```javascript
33 -<div>{'First · Second'}</div>
34 -```
35 -
36 -더 안전한 대안으로 [엔티티에 대응하는 유니코드 숫자](http://www.fileformat.info/info/unicode/char/b7/index.htm)를 찾아 JavaScript 문자열 안에서 사용하는 방법도 있습니다.
37 -
38 -```javascript
39 -<div>{'First \u00b7 Second'}</div>
40 -<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>
41 -```
42 -
43 -문자열과 JSX 엘리먼트를 혼합한 배열을 사용할 수도 있습니다.
44 -
45 -```javascript
46 -<div>{['First ', <span>&middot;</span>, ' Second']}</div>
47 -```
48 -
49 -최후의 수단으로, 항상 [생 HTML을 삽입](/react/docs/dom-differences-ko-KR.html)할 수 있습니다.
50 -
51 -```javascript
52 -<div dangerouslySetInnerHTML={{'{{'}}__html: 'First &middot; Second'}} />
53 -```
54 -
55 -
56 -## 커스텀 HTML 어트리뷰트
57 -
58 -프로퍼티를 HTML 사양에는 없는 네이티브 HTML 엘리먼트에 넘기면, React는 그 프로퍼티를 렌더하지 않습니다. 커스텀 어트리뷰트를 사용하고 싶다면, 접두사로 `data-`를 붙이셔야 합니다.
59 -
60 -```javascript
61 -<div data-custom-attribute="foo" />
62 -```
63 -
64 -`aria-`로 시작하는 [Web 접근성](http://www.w3.org/WAI/intro/aria) 어트리뷰트는 제대로 렌더될 것입니다.
65 -
66 -```javascript
67 -<div aria-hidden={true} />
68 -```
docs/docs/02.3-jsx-gotchas.md deleted
-74
@@ -1,74 +0,0 @@
1 ----
2 -id: jsx-gotchas
3 -title: JSX Gotchas
4 -permalink: docs/jsx-gotchas.html
5 -prev: jsx-spread.html
6 -next: interactivity-and-dynamic-uis.html
7 ----
8 -
9 -JSX looks like HTML but there are some important differences you may run into.
10 -
11 -> Note:
12 ->
13 -> For DOM differences, such as the inline `style` attribute, check [here](/react/docs/dom-differences.html).
14 -
15 -## HTML Entities
16 -
17 -You can insert HTML entities within literal text in JSX:
18 -
19 -```javascript
20 -<div>First &middot; Second</div>
21 -```
22 -
23 -If you want to display an HTML entity within dynamic content, you will run into double escaping issues as React escapes all the strings you are displaying in order to prevent a wide range of XSS attacks by default.
24 -
25 -```javascript
26 -// Bad: It displays "First &middot; Second"
27 -<div>{'First &middot; Second'}</div>
28 -```
29 -
30 -There are various ways to work-around this issue. The easiest one is to write Unicode characters directly in JavaScript. You need to make sure that the file is saved as UTF-8 and that the proper UTF-8 directives are set so the browser will display it correctly.
31 -
32 -```javascript
33 -<div>{'First · Second'}</div>
34 -```
35 -
36 -A safer alternative is to find the [unicode number corresponding to the entity](http://www.fileformat.info/info/unicode/char/b7/index.htm) and use it inside of a JavaScript string.
37 -
38 -```javascript
39 -<div>{'First \u00b7 Second'}</div>
40 -<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>
41 -```
42 -
43 -You can use mixed arrays with strings and JSX elements. Each JSX element in the array needs a unique key.
44 -
45 -```javascript
46 -<div>{['First ', <span key="middot">&middot;</span>, ' Second']}</div>
47 -```
48 -
49 -As a last resort, you always have the ability to [insert raw HTML](/react/tips/dangerously-set-inner-html.html).
50 -
51 -```javascript
52 -<div dangerouslySetInnerHTML={{'{{'}}__html: 'First &middot; Second'}} />
53 -```
54 -
55 -
56 -## Custom HTML Attributes
57 -
58 -If you pass properties to native HTML elements that do not exist in the HTML specification, React will not render them. If you want to use a custom attribute, you should prefix it with `data-`.
59 -
60 -```javascript
61 -<div data-custom-attribute="foo" />
62 -```
63 -
64 -However, arbitrary attributes are supported on custom elements (those with a hyphen in the tag name or an `is="..."` attribute).
65 -
66 -```javascript
67 -<x-my-component custom-attribute="foo" />
68 -```
69 -
70 -[Web Accessibility](http://www.w3.org/WAI/intro/aria) attributes starting with `aria-` will be rendered properly.
71 -
72 -```javascript
73 -<div aria-hidden={true} />
74 -```
docs/docs/02.3-jsx-gotchas.zh-CN.md deleted
-74
@@ -1,74 +0,0 @@
1 ----
2 -id: jsx-gotchas-zh-CN
3 -title: JSX 陷阱
4 -permalink: docs/jsx-gotchas-zh-CN.html
5 -prev: jsx-spread-zh-CN.html
6 -next: interactivity-and-dynamic-uis-zh-CN.html
7 ----
8 -
9 -JSX 与 HTML 非常相似,但是有些关键区别要注意。
10 -
11 -> 注意:
12 ->
13 -> 关于 DOM 的区别,如行内样式属性 `style`,参考 [DOM 区别](/react/docs/dom-differences.html)
14 -
15 -## HTML 实体
16 -
17 -HTML 实体可以插入到 JSX 的文本中。
18 -
19 -```javascript
20 -<div>First &middot; Second</div>
21 -```
22 -
23 -如果想在 JSX 表达式中显示 HTML 实体,可以会遇到二次转义的问题,因为 React 默认会转义所有字符串,为了防止各种 XSS 攻击。
24 -
25 -```javascript
26 -// 错误: 会显示 “First &middot; Second”
27 -<div>{'First &middot; Second'}</div>
28 -```
29 -
30 -有多种绕过的方法。最简单的是直接用 Unicode 字符。这时要确保文件是 UTF-8 编码且网页也指定为 UTF-8 编码。
31 -
32 -```javascript
33 -<div>{'First · Second'}</div>
34 -```
35 -
36 -安全的做法是先找到 [实体的 Unicode 编号](http://www.fileformat.info/info/unicode/char/b7/index.htm) ,然后在 JavaScript 字符串里使用。
37 -
38 -```javascript
39 -<div>{'First \u00b7 Second'}</div>
40 -<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>
41 -```
42 -
43 -可以在数组里混合使用字符串和 JSX 元素。
44 -
45 -```javascript
46 -<div>{['First ', <span>&middot;</span>, ' Second']}</div>
47 -```
48 -
49 -万不得已,可以直接[插入原始HTML](/react/tips/dangerously-set-inner-html.html)。
50 -
51 -```javascript
52 -<div dangerouslySetInnerHTML={{'{{'}}__html: 'First &middot; Second'}} />
53 -```
54 -
55 -
56 -## 自定义 HTML 属性
57 -
58 -如果往原生 HTML 元素里传入 HTML 规范里不存在的属性,React 不会显示它们。如果需要使用自定义属性,要加 `data-` 前缀。
59 -
60 -```javascript
61 -<div data-custom-attribute="foo" />
62 -```
63 -
64 -然而,在自定义元素中任意的属性都是被支持的 (那些在tag名里带有连接符或者 `is="..."` 属性的)
65 -
66 -```javascript
67 -<x-my-component custom-attribute="foo" />
68 -```
69 -
70 -以 `aria-` 开头的 [网络无障碍](http://www.w3.org/WAI/intro/aria) 属性可以正常使用。
71 -
72 -```javascript
73 -<div aria-hidden={true} />
74 -```
docs/docs/03-interactivity-and-dynamic-uis.it-IT.md deleted
-84
@@ -1,84 +0,0 @@
1 ----
2 -id: interactivity-and-dynamic-uis-it-IT
3 -title: Interattività e UI Dinamiche
4 -permalink: docs/interactivity-and-dynamic-uis-it-IT.html
5 -prev: jsx-gotchas-it-IT.html
6 -next: multiple-components-it-IT.html
7 ----
8 -
9 -Hai già [imparato a mostrare dati](/react/docs/displaying-data-it-IT.html) con React. Adesso vediamo come rendere le nostre UI interattive.
10 -
11 -
12 -## Un Esempio Semplice
13 -
14 -```javascript
15 -var LikeButton = React.createClass({
16 - getInitialState: function() {
17 - return {liked: false};
18 - },
19 - handleClick: function(event) {
20 - this.setState({liked: !this.state.liked});
21 - },
22 - render: function() {
23 - var text = this.state.liked ? 'mi piace' : 'non mi piace';
24 - return (
25 - <p onClick={this.handleClick}>
26 - You {text} this. Click to toggle.
27 - </p>
28 - );
29 - }
30 -});
31 -
32 -ReactDOM.render(
33 - <LikeButton />,
34 - document.getElementById('example')
35 -);
36 -```
37 -
38 -
39 -## Gestione degli Eventi ed Eventi Sintetici
40 -
41 -Con React devi semplicemente passare il tuo gestore di eventi come una proprietà camelCased in modo simile a come faresti nel normale HTML. React si assicura che tutti gli eventi si comportano in maniera identica in IE8 e successivi implementando un sistema di eventi sintetici. Ovvero, React sa come propagare e catturare eventi secondo la specifica, e garantisce che gli eventi passati ai tuoi gestori di eventi siano consistenti con la [specifica W3C](http://www.w3.org/TR/DOM-Level-3-Events/), qualunque browser tu stia utilizzando.
42 -
43 -
44 -## Dietro le Quinte: Binding Automatico e Delega degli Eventi
45 -
46 -Dietro le quinte, React esegue alcune operazioni per mantenere il tuo codice ad alte prestazioni e facile da comprendere.
47 -
48 -**Binding automatico:** Quando crei le callback in JavaScript, solitamente devi fare il binding esplicito del metodo alla sua istanza, in modo che il valore di `this` sia corretto. Con React, ogni metodo è automaticamente legato alla propria istanza del componente (eccetto quando si usa la sintassi delle classi ES6). React immagazzina il metodo legato in maniera tale da essere estremamente efficiente in termini di CPU e memoria. Ti permette anche di scrivere meno codice!
49 -
50 -**Delega degli eventi:** React non associa realmente i gestori di eventi ai nodi stessi. Quando React si avvia, comincia ad ascoltare tutti gli eventi a livello globale usando un singolo event listener. Quando un componente viene montato o smontato, i gestori di eventi sono semplicemente aggiunti o rimossi da un mapping interno. Quando si verifica un evento, React sa come inoltrarlo utilizzando questo mapping. Quando non ci sono più gestori di eventi rimasti nel mapping, i gestori di eventi di React sono semplici operazioni fittizie. Per saperne di più sul perché questo approccio è veloce, leggi [l'eccellente articolo sul blog di David Walsh](http://davidwalsh.name/event-delegate).
51 -
52 -
53 -## I Componenti Sono Macchine a Stati Finiti
54 -
55 -React considera le UI come semplici macchine a stati finiti. Pensando alla UI come in uno di tanti stati diversi e visualizzando questi stati, è facile mantenere la UI consistente.
56 -
57 -In React, aggiorni semplicemente lo stato di un componente, e quindi visualizzi una nuova UI basata su questo nuovo stato. React si occupa di aggiornare il DOM al tuo posto nella maniera più efficiente.
58 -
59 -
60 -## Come Funziona lo Stato
61 -
62 -Una maniera comune di informare React di un cambiamento nei dati è chiamare `setState(data, callback)`. Questo metodo effettua il merge di `data` in `this.state` e ridisegna il componente. Quando il componente ha terminato la fase di ri-rendering, la `callback` opzionale viene invocata. Nella maggior parte dei casi non avrai bisogno di fornire una `callback` dal momento che React si occuperà di mantenere la UI aggiornata per te.
63 -
64 -
65 -## Quali Componenti Devono Avere uno Stato?
66 -
67 -La maggior parte dei tuoi componenti dovrebbero semplicemente ricevere dei dati da `props` e visualizzarli. Tuttavia, a volte hai bisogno di reagire all'input dell'utente, una richiesta al server o il trascorrere del tempo. In questi casi utilizzi lo stato.
68 -
69 -**Prova a mantenere il maggior numero possibile dei tuoi componenti privi di stato.** Facendo ciò, isolerai lo stato nel suo luogo logicamente corretto e minimizzerai la ridondanza, rendendo più semplice ragionare sulla tua applicazione.
70 -
71 -Un pattern comune è quello di creare diversi componenti privi di stato che mostrano semplicemente dati, e di avere un componente dotato di stato al di sopra di essi nella gerarchia, che passa il proprio stato ai suoi figli tramite le `props`. Il componente dotato di stato incapsula tutta la logica di interazione, mentre i componenti privi di stato si occupano della visualizzazione dei dati in maniera dichiarativa.
72 -
73 -
74 -## Cosa *Dovrebbe* Contenere lo Stato?
75 -
76 -**Lo stato dovrebbe contenere dati che i gestori di eventi del componente possono modificare per scatenare un aggiornamento della UI.** In applicazioni reali, questi dati tendono ad essere molto limitati e serializzabili come JSON. Quando costruisci un componente dotato di stato, pensa alla minima rappresentazione possibile del suo stato, e conserva solo quelle proprietà in `this.state`. All'interno di `render()` calcola quindi ogni altra informazione necessaria basandoti sullo stato. Ti accorgerai che pensare e scrivere applicazioni in questo modo porta alla scrittura dell'applicazione più corretta, dal momento che aggiungere valori ridondanti o calcolati allo stato significherebbe doverli mantenere sincronizzati esplicitamente, anziché affidarti a React perché li calcoli al tuo posto.
77 -
78 -## Cosa *Non Dovrebbe* Contenere lo Stato?
79 -
80 -`this.state` dovrebbe contenere soltanto la quantità minima di dati indispensabile a rappresentare lo stato della tua UI. In quanto tale, non dovrebbe contenere:
81 -
82 -* **Dati calcolati:** Non preoccuparti di precalcolare valori basati sullo stato — è più semplice assicurarti che la tua UI sia consistente se effettui tutti i calcoli all'interno di `render()`. Per esempio, se lo stato contiene un array di elementi di una lista, e vuoi mostrare il numero di elementi come stringa, mostra semplicemente `this.state.listItems.length + ' elementi nella lista'` nel tuo metodo `render()` anziché conservarlo nello stato.
83 -* **Componenti React:** Costruiscili in `render()` basandoti sulle proprietà e sullo stato del componente.
84 -* **Dati duplicati dalle proprietà:** Prova ad utilizzare le proprietà come fonte di verità ove possibile. Un uso valido dello stato per i valori delle proprietà è conservarne il valore precedente quando le proprietà cambiano nel tempo.
docs/docs/03-interactivity-and-dynamic-uis.ja-JP.md deleted
-84
@@ -1,84 +0,0 @@
1 ----
2 -id: interactivity-and-dynamic-uis
3 -title: 相互作用と動的なUI
4 -permalink: docs/interactivity-and-dynamic-uis-ja-JP.html
5 -prev: jsx-gotchas-ja-JP.html
6 -next: multiple-components-ja-JP.html
7 ----
8 -
9 -Reactで[どうやってデータを表示するか](/react/docs/displaying-data-ja-JP.html)については既に学んでいます。これからは、どうやって相互に作用するUIを作成するかを見ていきましょう。
10 -
11 -
12 -## 単純な例
13 -
14 -```javascript
15 -var LikeButton = React.createClass({
16 - getInitialState: function() {
17 - return {liked: false};
18 - },
19 - handleClick: function(event) {
20 - this.setState({liked: !this.state.liked});
21 - },
22 - render: function() {
23 - var text = this.state.liked ? 'liked' : 'haven\'t liked';
24 - return (
25 - <p onClick={this.handleClick}>
26 - You {text} this. Click to toggle.
27 - </p>
28 - );
29 - }
30 -});
31 -
32 -ReactDOM.render(
33 - <LikeButton />,
34 - document.getElementById('example')
35 -);
36 -```
37 -
38 -
39 -## イベントハンドリングとイベントの組み合わせ
40 -
41 -Reactでは、普通のHTMLで行っているように単純にキャメルケースのpropとしてイベントハンドラを渡します。ReactはIE8と同じように全てのイベントが動作することと、組み合わされたイベントシステムが実行されることを保証します。これは、Reactが、イベントがどのように発生して、仕様にそってそれをキャプチャする方法を知っていることと、イベントはイベントハンドラに渡されて、どのブラウザを使っていても、[W3Cの仕様](http://www.w3.org/TR/DOM-Level-3-Events/)と一致することを保証することを意味します。
42 -
43 -## 中身を見る: オートバインディングとイベントの委譲
44 -
45 -中身を見ていくと、Reactはコードの性能と、理解しやすさを保つためにいくつかのことを行っています。
46 -
47 -**オートバインディング:** JavaScriptでコールバックを作成するときには、普通は `this` の値が正しくなるように、インスタンスにメソッドをはっきりとバインドする必要があります。
48 -Reactでは、全てのメソッドが自動でコンポーネントのインスタンスにバインドされます。ReactはCPUとメモリを効率的に使えるように、バインドするメソッドを持っています。これによって、タイピングの量を少なくすることもできます!
49 -
50 -**イベントの委譲:** Reactは実際はノード自体にイベントハンドラをアタッチはしません。Reactを立ち上げる時、1つのイベントリスナを使って最上位で全てのイベントをリスニングし始めます。コンポーネントがマウントされたり、アンマウントされた時は、イベントハンドラは内部のマッピングを単純に加えたり減らしたりします。イベントが起こった時には、Reactはこのマッピングを使ってどのようにディスパッチするかを知っています。マッピングの中にイベントハンドラが無い場合は、Reactのイベントハンドラは何も行いません。なぜこれの速度が速いかについて詳しく知るためには、[David Walshの素晴らしいブログの投稿](http://davidwalsh.name/event-delegate)をご覧ください。
51 -
52 -## コンポーネントは静的なマシーンに過ぎない
53 -
54 -ReactはUIをただの静的なマシーンと考えます。UIがたくさんのstateの中にあり、それらのstateをレンダリングするものだと考えることで、UIの一貫性を保ちやすくなります。
55 -
56 -Reactでは、コンポーネントのstateをアップデートするだけで、新しいstateに基づいた新しいUIをレンダリングします。Reactは最も効率的な方法でDOMをアップデートする面倒を見てくれます。
57 -
58 -
59 -## どのようにStateが働くか
60 -
61 -Reactがデータの変更を通知する共通な方法は `setState(data, callback)` を呼ぶことです。このメソッドは `data` を `this.state` にマージし、コンポーネントを再度レンダリングします。コンポーネントが再度レンダリングし終わったら、オプションの `callback` が呼ばれます。ほとんどの場合、 `callback` を提供する必要はありません。ReactがUIを最新に保ってくれるからです。
62 -
63 -
64 -## どのコンポーネントがStateを持っているべきでしょうか?
65 -
66 -コンポーネントは単純に `props` からデータを取得し、レンダリングすべきです。しかし、時々、ユーザのインプットやサーバのリクエストや、時間の経過に反応する必要が有ります。このような場合にstateを使うのです。
67 -
68 -**コンポーネントの多くを、可能な限りステートレスに保つよう試みてください。** このようにすることで、stateを最もロジックに近い場所から離し、冗長性を減らすことができ、アプリケーションが理解しやすくなります。
69 -
70 -共通なパターンはただデータをレンダリングするいくつかのステートレスなコンポーネントを構築することで、 `props` を通してその子要素にstateを渡す階級でステートフルなコンポーネントを持つことです。ステートフルなコンポーネントは、ステートレスなコンポーネントが叙述的な方法でデータをレンダリングする助けを行う一方で、全ての相互作用のロジックを持ちます。
71 -
72 -## stateで何が行われる *べき* でしょうか?
73 -
74 -**stateはUIのアップデートのトリガーとなるコンポーネントのイベントハンドラとしてのデータを保持するべきです。** 現実のアプリでは、このデータはとても小さく、JSONでシリアライズできるものになります。ステートフルなコンポーネントを構築する時は、このstateの表現をできるだけ小さくなるように、また、 `this.state` の中だけにそれらのプロパティを貯めこむように考えてください。 `render()` の中では、このstateに基づく、他の必要な情報をただ計算してください。このように考えたりアプリケーションを記述したりすることが最も正しいアプリケーションへの道であると発見するでしょう。stateに余剰な値や、計算後の値を加えることはReactがそれらを計算してくれるのに頼るのではなく、同期的にそれらを明白に保つ必要があることを意味します。
75 -
76 -
77 -## stateで何が行われる *べきではない* でしょうか?
78 -
79 -`this.state` UIのstateを表す必要がある最小限の量のデータだけを保持するべきです。このような点で以下のようなものは保持するべきではありません。
80 -
81 -* **計算されたデータ:**
82 -stateに基づく事前に計算された値について心配は要りません。 `render()` を用いて、全ての計算を行って、UIの一貫性を保証するよりも簡単です。例えば、stateにリスト化されたアイテムの配列を持っていて、文字列としてその数をレンダリングしたいとして、それらをstateに保持するよりも `render()` メソッドに `this.state.listItems.length + ' list items'` を単純にレンダリングすれば良いのです。
83 -* **Reactのコンポーネント:** 隠れたpropsとstateに基づいて `render()` でそれらをビルドしてください。
84 -* **propsからコピーしたデータ:** 可能であれば、propsを真のソースとして使ってみてください。propsは時とともに変化し得るので、正しくstateにpropsを保持する使い方は、以前の値を知っていることになり得ます。
docs/docs/03-interactivity-and-dynamic-uis.ko-KR.md deleted
-78
@@ -1,78 +0,0 @@
1 ----
2 -id: interactivity-and-dynamic-uis-ko-KR
3 -title: 상호 작용 및 동적 UI
4 -permalink: docs/interactivity-and-dynamic-uis-ko-KR.html
5 -prev: jsx-gotchas-ko-KR.html
6 -next: multiple-components-ko-KR.html
7 ----
8 -
9 -이미 React에서 [어떻게 데이터를 표시](/react/docs/displaying-data-ko-KR.html)하는지를 배웠습니다. 이제 UI와의 상호작용을 어떻게 만드는지 살펴보죠.
10 -
11 -## 간단한 예제
12 -
13 -```javascript
14 -var LikeButton = React.createClass({
15 - getInitialState: function() {
16 - return {liked: false};
17 - },
18 - handleClick: function(event) {
19 - this.setState({liked: !this.state.liked});
20 - },
21 - render: function() {
22 - var text = this.state.liked ? 'liked' : 'haven\'t liked';
23 - return (
24 - <p onClick={this.handleClick}>
25 - You {text} this. Click to toggle.
26 - </p>
27 - );
28 - }
29 -});
30 -
31 -ReactDOM.render(
32 - <LikeButton />,
33 - document.getElementById('example')
34 -);
35 -```
36 -
37 -## 이벤트 핸들링과 통합적인(Synthetic) 이벤트
38 -
39 -React에서의 이벤트 핸들러는 HTML에서 그러던 것처럼 간단히 카멜케이스 프로퍼티(camelCased prop)로 넘기면 됩니다. React의 모든 이벤트는 통합적인 이벤트 시스템의 구현으로 IE8 이상에서는 같은 행동이 보장됩니다. 즉, React는 사양에 따라 어떻게 이벤트를 일으키고(bubble) 잡는지 알고 있고, 당신이 사용하는 브라우저와 관계없이 이벤트 핸들러에 전달되는 이벤트는 [W3C 사양](http://www.w3.org/TR/DOM-Level-3-Events/)과 같도록 보장됩니다.
40 -
41 -## 기본 구현: 오토바인딩과 이벤트 델리게이션
42 -<a name="under-the-hood-autobinding-and-event-delegation"></a>
43 -
44 -코드를 고성능으로 유지하고 이해하기 쉽게 하기 위해, React는 보이지 않는 곳에서 몇 가지 일을 수행합니다.
45 -
46 -**오토바인딩:** JavaScript에서 콜백을 만들 때, 보통은 `this`의 값이 정확하도록 명시적으로 메소드를 인스턴스에 바인드해야 합니다. React에서는 모든 메소드가 자동으로 React의 컴포넌트 인스턴스에 바인드됩니다.(ES6 클래스 문법을 사용할 때는 재외하고) React가 바인드 메소드를 캐시하기 때문에 매우 CPU와 메모리에 효율적입니다. 타이핑해야 할 것도 줄어들죠!
47 -
48 -**이벤트 델리게이션:** React는 실제로는 노드자신에게 이벤트 핸들러를 붙이지 않습니다. React가 시작되면 React는 탑 레벨의 단일 이벤트 리스너로 모든 이벤트를 리스닝하기 시작합니다. 컴포넌트가 마운트되거나 언마운트 될 때, 이벤트 핸들러는 그냥 내부 매핑에서 넣거나 뺄 뿐입니다. 이벤트가 발생하면, React는 이 매핑을 사용해서 어떻게 디스패치할 지를 알게 됩니다. 매핑에 이벤트 핸들러가 남아있지 않으면, React의 이벤트 핸들러는 그냥 아무것도 하지 않습니다. 왜 이 방식이 빠른지 더 알고 싶으시면, [David Walsh의 멋진 블로그 글](http://davidwalsh.name/event-delegate)을 읽어 보세요.
49 -
50 -## 컴포넌트는 그냥 state 머신일 뿐
51 -
52 -React는 UI를 간단한 state 머신이라 생각합니다. UI를 다양한 state와 그 state의 렌더링으로 생각함으로써 UI를 일관성 있게 관리하기 쉬워집니다.
53 -
54 -React에서는, 간단히 컴포넌트의 state를 업데이트하고, 이 새로운 state의 UI를 렌더링합니다. React는 DOM의 변경을 가장 효율적인 방법으로 관리해줍니다.
55 -
56 -## state의 동작 원리
57 -
58 -React에게 데이터의 변경을 알리는 일반적인 방법은 `setState(data, callback)`을 호출하는 것입니다. 이 메소드는 `this.state`에 `data`를 머지하고 컴포넌트를 다시 렌더링 합니다. 컴포넌트의 재-렌더링이 끝나면, 생략가능한 `callback`이 호출됩니다. 대부분의 경우 React가 UI를 최신상태로 유지해주기 때문에 `callback`을 사용할 필요가 없습니다.
59 -
60 -## 어떤 컴포넌트가 state를 가져야 할까요?
61 -
62 -대부분의 컴포넌트는 `props`로부터 데이터를 받아 렌더할 뿐입니다만, 가끔 유저 인풋, 서버 요청, 시간의 경과에 반응해야 할 필요가 있습니다. 이럴 때 state를 사용합니다.
63 -
64 -**가능한 한 컴포넌트가 상태를 가지지 않도록(stateless) 하세요.** 이렇게 함으로써 가장 논리적인 장소로 state를 격리하게 되고 쉽게 애플리케이션을 추론할 수 있도록 중복을 최소화할 수 있습니다.
65 -
66 -일반적인 패턴은 데이터만 렌더하는 여러 상태를 가지지 않은 컴포넌트를 만들고, 그 위에 상태기반(stateful) 컴포넌트를 만들어 계층 안의 자식 컴포넌트에게 `props`를 통해 state를 전달하는 것입니다. state를 가지지 않은 컴포넌트가 선언적인 방법으로 데이터를 렌더링 하는 동안, 상태기반 컴포넌트는 모든 상호작용 로직을 캡슐화합니다.
67 -
68 -## state를 어떻게 *써야* 할까요?
69 -
70 -**state는 컴포넌트의 이벤트 핸들러에 의해 UI 업데이트를 트리거할때 변경될 가능성이 있어, 그때 사용할 데이터를 가져야 합니다.** 실제 앱에서는 이 데이터는 매우 작고 JSON 직렬화 가능한 경향이 있습니다. 상태기반 컴포넌트를 만들때, 가능한 작게 state를 서술하고 `this.state`에만 저장하도록 해보세요. 그냥 `render()` 안에서 이 state를 기반으로 다른 모든 정보를 계산합니다. 이 방식으로 애플리케이션을 작성하고 생각하면 가장 최적의 애플리케이션으로 발전해가는 경향이 있다는 것을 발견하게 될 것입니다. 꼭 필요하지 않은 값이나 계산된 값을 state에 추가하는 것은 render가 그것을 계산하는 대신에 명시적으로 그것들을 맞춰줘야 하는 것을 의미하기 때문이죠.
71 -
72 -## state를 어떻게 *쓰지 말아야* 할까요?
73 -
74 -`this.state`는 UI의 state를 표현할 최소한의 데이터만을 가져야 합니다. 그래서 이런 것들을 가지지 않게끔 해야 합니다.
75 -
76 -* **계산된 데이터:** state에 따라 값을 미리 계산하는 것에 대해 염려하지 마세요. 계산은 모두 `render()`에서 하는 것이 UI의 일관성을 유지하기 쉽습니다. 예를 들어, state에서 list items 배열을 가지고 있고 문자열으로 카운트를 렌더링 할 경우, state에 저장하기보다는 그냥 `render()` 메소드안에서 `this.state.listItems.length + ' list items'`를 렌더하세요.
77 -* **React 컴포넌트:** 가지고 있는 props와 state로 `render()`안에서 만드세요.
78 -* **props에서 복사한 데이터:** 가능한 한 원래의 소스로 props를 사용하도록 해보세요. props를 state에 저장하는 단 하나의 올바른 사용법은 이전 값을 알고 싶을 때입니다. props는 부모 컴포넌트의 재 렌더링의 결과 변경될 수도 있기 때문이죠.
docs/docs/03-interactivity-and-dynamic-uis.md deleted
-81
@@ -1,81 +0,0 @@
1 ----
2 -id: interactivity-and-dynamic-uis
3 -title: Interactivity and Dynamic UIs
4 -permalink: docs/interactivity-and-dynamic-uis.html
5 -prev: jsx-gotchas.html
6 -next: multiple-components.html
7 ----
8 -
9 -You've already [learned how to display data](/react/docs/displaying-data.html) with React. Now let's look at how to make our UIs interactive.
10 -
11 -## A Simple Example
12 -
13 -```javascript
14 -class LikeButton extends React.Component {
15 - constructor() {
16 - super();
17 - this.state = {
18 - liked: false
19 - };
20 - this.handleClick = this.handleClick.bind(this);
21 - }
22 - handleClick() {
23 - this.setState({liked: !this.state.liked});
24 - }
25 - render() {
26 - const text = this.state.liked ? 'liked' : 'haven\'t liked';
27 - return (
28 - <div onClick={this.handleClick}>
29 - You {text} this. Click to toggle.
30 - </div>
31 - );
32 - }
33 -}
34 -
35 -ReactDOM.render(
36 - <LikeButton />,
37 - document.getElementById('example')
38 -);
39 -```
40 -
41 -## Event Handling and Synthetic Events
42 -
43 -With React you simply pass your event handler as a camelCased prop similar to how you'd do it in normal HTML. React ensures that all events behave similarly in all browsers by implementing a synthetic event system. That is, React knows how to bubble and capture events according to the spec, and the events passed to your event handler are guaranteed to be consistent with [the W3C spec](http://www.w3.org/TR/DOM-Level-3-Events/), regardless of which browser you're using.
44 -
45 -## Under the Hood: Autobinding and Event Delegation
46 -
47 -Under the hood, React does a few things to keep your code performant and easy to understand.
48 -
49 -**Autobinding:** When creating callbacks in JavaScript, you usually need to explicitly bind a method to its instance such that the value of `this` is correct. With React, every method is automatically bound to its component instance ([except when using ES6 class syntax](/react/docs/reusable-components.html#no-autobinding)). React caches the bound method such that it's extremely CPU and memory efficient. It's also less typing!
50 -
51 -**Event delegation:** React doesn't actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping. When an event occurs, React knows how to dispatch it using this mapping. When there are no event handlers left in the mapping, React's event handlers are simple no-ops. To learn more about why this is fast, see [David Walsh's excellent blog post](http://davidwalsh.name/event-delegate).
52 -
53 -## Components are Just State Machines
54 -
55 -React thinks of UIs as simple state machines. By thinking of a UI as being in various states and rendering those states, it's easy to keep your UI consistent.
56 -
57 -In React, you simply update a component's state, and then render a new UI based on this new state. React takes care of updating the DOM for you in the most efficient way.
58 -
59 -## How State Works
60 -
61 -A common way to inform React of a data change is by calling `setState(data, callback)`. This method merges `data` into `this.state` and re-renders the component. When the component finishes re-rendering, the optional `callback` is called. Most of the time you'll never need to provide a `callback` since React will take care of keeping your UI up-to-date for you.
62 -
63 -## What Components Should Have State?
64 -
65 -Most of your components should simply take some data from `props` and render it. However, sometimes you need to respond to user input, a server request or the passage of time. For this you use state.
66 -
67 -**Try to keep as many of your components as possible stateless.** By doing this you'll isolate the state to its most logical place and minimize redundancy, making it easier to reason about your application.
68 -
69 -A common pattern is to create several stateless components that just render data, and have a stateful component above them in the hierarchy that passes its state to its children via `props`. The stateful component encapsulates all of the interaction logic, while the stateless components take care of rendering data in a declarative way.
70 -
71 -## What *Should* Go in State?
72 -
73 -**State should contain data that a component's event handlers may change to trigger a UI update.** In real apps this data tends to be very small and JSON-serializable. When building a stateful component, think about the minimal possible representation of its state, and only store those properties in `this.state`. Inside of `render()` simply compute any other information you need based on this state. You'll find that thinking about and writing applications in this way tends to lead to the most correct application, since adding redundant or computed values to state means that you need to explicitly keep them in sync rather than rely on React computing them for you.
74 -
75 -## What *Shouldn't* Go in State?
76 -
77 -`this.state` should only contain the minimal amount of data needed to represent your UI's state. As such, it should not contain:
78 -
79 -* **Computed data:** Don't worry about precomputing values based on state — it's easier to ensure that your UI is consistent if you do all computation within `render()`. For example, if you have an array of list items in state and you want to render the count as a string, simply render `this.state.listItems.length + ' list items'` in your `render()` method rather than storing it on state.
80 -* **React components:** Build them in `render()` based on underlying props and state.
81 -* **Duplicated data from props:** Try to use props as the source of truth where possible. One valid use to store props in state is to be able to know its previous values, because props may change as the result of a parent component re-rendering.
docs/docs/03-interactivity-and-dynamic-uis.ru-RU.md deleted
-78
@@ -1,78 +0,0 @@
1 ----
2 -id: interactivity-and-dynamic-uis-ru-RU
3 -title: Интерактивные и динамические интерфейсы
4 -permalink: docs/interactivity-and-dynamic-uis-ru-RU.html
5 -prev: jsx-gotchas.html
6 -next: multiple-components.html
7 ----
8 -
9 -Вы уже знаете [как показывать данные](/react/docs/displaying-data.html) с React. Теперь давайте добавим в наши интферфейсы немного интерактивности.
10 -
11 -## Простой пример
12 -
13 -```javascript
14 -var LikeButton = React.createClass({
15 - getInitialState: function() {
16 - return {liked: false};
17 - },
18 - handleClick: function(event) {
19 - this.setState({liked: !this.state.liked});
20 - },
21 - render: function() {
22 - var text = this.state.liked ? 'liked' : 'haven\'t liked';
23 - return (
24 - <p onClick={this.handleClick}>
25 - You {text} this. Click to toggle.
26 - </p>
27 - );
28 - }
29 -});
30 -
31 -ReactDOM.render(
32 - <LikeButton />,
33 - document.getElementById('example')
34 -);
35 -```
36 -
37 -## Обработка событий и синтетические события
38 -
39 -С React вы просто передаете функцию-обработчик нужного события как аргумент, почти так же, как делали это в HTML. Благодаря механизму синтетических событий React гарантирует, что все события будут вести себя одинаково во всех браузерах. Другими словами, React знает, как работает всплытие и перехват событий по спецификации. События, которые он передает в ваши обработчики, будут соответствовать [спецификации W3C](http://www.w3.org/TR/DOM-Level-3-Events/), несмотря на то, каким браузером вы пользуетесь.
40 -
41 -## Как это работает: автоматическое связывание и делегирование событий
42 -
43 -Чтобы ваш код был не только понятным, но и быстрым, React делает следующее:
44 -
45 -**Автоматическое связывание:** Когда в JavaScript создаются функции обратного вызова, вам надо привязать метод к тому объекту, на котором он будет вызываться, чтобы значение `this` было корректным. С React привязка метода к компоненту происходит автоматически ([кроме тех случаев, когда вы используете классы ES6](/react/docs/reusable-components.html#no-autobinding)). И делается это с минимальной нагрузкой на процессор и память.
46 -
47 -**Делегирование событий:** На самом же деле, React добавляет обработчики событий не к узлам дерева. Сразу после запуска, React начинает прослушивать все события с самого верхнего уровня, используя единый слушатель. Когда добавляется новый компонент или удаляется старый, обработчики событий просто добавляются или удаляются из памяти React. И когда событие наступает, React уже заранее знает какому из обработчиков его передать. Когда в памяти больше не остается обработчиков, React перестает обрабатывать события. Если хотите узнать о том, почему эта механика так быстро работает, почитайте [отличный пост в блоге David Walsh](http://davidwalsh.name/event-delegate).
48 -
49 -## Компоненты как конечные автоматы
50 -
51 -React считает интерфейсы обыкновенными конечными автоматами. Работать с интерфейсом становится проще, если представлять его как конечный автомат, который меняет состояния и отрисовывает их.
52 -
53 -В React вы просто обновляете состояние компонента, а потом выводите новый интерфейс уже с новыми данными. Все изменения в DOM-дереве React сделает сам, причем наиболее эффективным способом.
54 -
55 -## Как работает состояние
56 -
57 -Чтобы сообщить React о том, что данные изменились, вы вызываете метод `setState(data, callback)`. В этом методе происходит обновление состояния `this.state` новыми данными из `data`, и компонент отрисуется заново. После этого вызывается функция `callback`. Но вы редко будете ей пользоваться, ведь React сам обновляет интерфейс.
58 -
59 -## В каких компонентах хранить состояние?
60 -
61 -Большинство компонентов должны просто брать данные из `props` и отрисовывать их. Но иногда вам надо реагировать на действия пользователя, делать запросы на сервер или просто сделать что-то по таймеру. В таких случаях используйте состояние.
62 -
63 -**Старайтесь делать компоненты без состояния.** Следуя этому правилу, вы будете выносить работу с состоянием с уровня представления в другие, более подходящие места. Тем самым, вы снизите сложность приложения, упрощая его понимание.
64 -
65 -Основной принцип такой: создаются несколько компонентов без состояния, которые формируют дерево. Они будут заниматься только отрисовкой данных. А все данные для них будут у родительского компонента, который будет на вершине этого дерева компонентов. Он и будет передавать данные дочерним узлам через `props`. Этот компонент с общим состоянием содержит в себе всю логику взаимодействия, а дочерние компоненты будут только отрисовывать данные, которые будут у них в `props`.
66 -
67 -## Какие данные *надо* помещать в состояние?
68 -
69 -**Состояние должно содержать данные, которые нужны для обновления интерфейса.** В реальных приложениях такие данные, как правило, незначительны по объему, и могут быть сериализованы в JSON. Когда вы создаете компонент с состоянием, старайтесь поместить в него минимум данных. А уже внутри метода `render()` вычисляйте остальные данные, используя значения из состояния.
70 -Со временем вы увидите, что такой подход позволяет создавать более стройные и устойчивые к изменениям приложения. Добавление в состояние лишних данных требует от вас дополнительных затрат на их синхронизацию. Но этого можно избежать, если позволить React делать все эти вычисления за вас.
71 -
72 -## Какие данные *не надо* помещать в состояние?
73 -
74 -Состояние `this.state` должно содержать минимум данных, необходимых для отображения интерфейса. Поэтому не стоит хранить в нем:
75 -
76 -* **Вычисляемые данные:** Не волнуйтесь о данных, которые можно вычислить из состояния. Согласованность данных проще обеспечить, если производить все вычисления в методе `render()`. Например, если в состоянии хранится список элементов, и вам надо вывести его размер в виде строки, напишите `this.state.listItems.length + ' элементов'` в методе `render()`. Это будет правильнее, чем хранить размер списка в состоянии.
77 -* **Компоненты React:** Создавайте их в методе `render()`, опираясь на данные из `props` и `state`.
78 -* **Значения, повторяющие `props`:** Старайтесь по мере возможности использовать `props` как единственный источник данных. Хранить значения `props` в состоянии допускается, только если вам надо где-то хранить их прошлые значения, ведь `props` могут измениться после отрисовки родительского компонента.
docs/docs/03-interactivity-and-dynamic-uis.zh-CN.md deleted
-77
@@ -1,77 +0,0 @@
1 ----
2 -id: interactivity-and-dynamic-uis-zh-CN
3 -title: 动态交互式用户界面
4 -permalink: docs/interactivity-and-dynamic-uis-zh-CN.html
5 -prev: jsx-gotchas-zh-CN.html
6 -next: multiple-components-zh-CN.html
7 ----
8 -
9 -我们已经学习如何使用 React [显示数据](/react/docs/displaying-data-zh-CN.html)。现在让我们来学习如何创建交互式界面。
10 -
11 -## 简单例子
12 -
13 -```javascript
14 -var LikeButton = React.createClass({
15 - getInitialState: function() {
16 - return {liked: false};
17 - },
18 - handleClick: function(event) {
19 - this.setState({liked: !this.state.liked});
20 - },
21 - render: function() {
22 - var text = this.state.liked ? 'liked' : 'haven\'t liked';
23 - return (
24 - <p onClick={this.handleClick}>
25 - You {text} this. Click to toggle.
26 - </p>
27 - );
28 - }
29 -});
30 -
31 -ReactDOM.render(
32 - <LikeButton />,
33 - document.getElementById('example')
34 -);
35 -```
36 -
37 -## 事件处理与合成事件(Synthetic Events)
38 -
39 -React 里只需把事件处理器(event handler)以骆峰命名(camelCased)形式当作组件的 props 传入即可,就像使用普通 HTML 那样。React 内部创建一套合成事件系统来使所有事件在 IE8 和以上浏览器表现一致。也就是说,React 知道如何冒泡和捕获事件,而且你的事件处理器接收到的 events 参数与 [W3C 规范](http://www.w3.org/TR/DOM-Level-3-Events/) 一致,无论你使用哪种浏览器。
40 -
41 -## 幕后原理:自动绑定(Autobinding)和事件代理(Event Delegation)
42 -
43 -在幕后,React 做了一些操作来让代码高效运行且易于理解。
44 -
45 -**自动绑定:** 在 JavaScript 里创建回调的时候,为了保证 `this` 的正确性,一般都需要显式地绑定方法到它的实例上。在 React 中,所有方法被自动绑定到了它的组件实例上([除非使用ES6的class符号](/react/docs/reusable-components.html#no-autobinding))。React 还缓存这些绑定方法,所以 CPU 和内存都是非常高效。而且还能减少打字!
46 -
47 -**事件代理:** React 实际并没有把事件处理器绑定到节点本身。当 React 启动的时候,它在最外层使用唯一一个事件监听器处理所有事件。当组件被加载和卸载时,只是在内部映射里添加或删除事件处理器。当事件触发,React 根据映射来决定如何分发。当映射里没有事件处理函数时,会当作空操作处理。参考 [David Walsh 很棒的文章](http://davidwalsh.name/event-delegate) 了解这样做高效的原因。
48 -
49 -## 组件其实是状态机(State Machines)
50 -
51 -React 把用户界面当作简单状态机。把用户界面想像成拥有不同状态然后渲染这些状态,可以轻松让用户界面和数据保持一致。
52 -
53 -React 里,只需更新组件的 state,然后根据新的 state 重新渲染用户界面(不要操作 DOM)。React 来决定如何最高效地更新 DOM。
54 -
55 -## State 工作原理
56 -
57 -常用的通知 React 数据变化的方法是调用 `setState(data, callback)`。这个方法会合并(merge) `data` 到 `this.state`,并重新渲染组件。重新渲染完成后,调用可选的 `callback` 回调。大部分情况下不需要提供 `callback`,因为 React 会负责把界面更新到最新状态。
58 -
59 -## 哪些组件应该有 State?
60 -
61 -大部分组件的工作应该是从 `props` 里取数据并渲染出来。但是,有时需要对用户输入、服务器请求或者时间变化等作出响应,这时才需要使用 State。
62 -
63 -**尝试把尽可能多的组件无状态化。** 这样做能隔离 state,把它放到最合理的地方,也能减少冗余,同时易于解释程序运作过程。
64 -
65 -常用的模式是创建多个只负责渲染数据的无状态(stateless)组件,在它们的上层创建一个有状态(stateful)组件并把它的状态通过 `props` 传给子级。这个有状态的组件封装了所有用户的交互逻辑,而这些无状态组件则负责声明式地渲染数据。
66 -
67 -## 哪些 *应该* 作为 State?
68 -
69 -**State 应该包括那些可能被组件的事件处理器改变并触发用户界面更新的数据。** 真实的应用中这种数据一般都很小且能被 JSON 序列化。当创建一个状态化的组件时,思考一下表示它的状态最少需要哪些数据,并只把这些数据存入 `this.state`。在 `render()` 里再根据 state 来计算你需要的其它数据。你会发现以这种方式思考和开发程序最终往往是正确的,因为如果在 state 里添加冗余数据或计算所得数据,那么你就需要经常手动保持数据同步,而不能让 React 来帮你处理。
70 -
71 -## 哪些 *不应该* 作为 State?
72 -
73 -`this.state` 应该仅包括能表示用户界面状态所需的最少数据。因此,它不应该包括:
74 -
75 -* **计算所得数据:** 不要担心根据 state 来预先计算数据 —— 把所有的计算都放到 `render()` 里更容易保证用户界面和数据的一致性。例如,在 state 里有一个数组(listItems),我们要把数组长度渲染成字符串, 直接在 `render()` 里使用 `this.state.listItems.length + ' list items'` 比把它放到 state 里好的多。
76 -* **React 组件:** 在 `render()` 里使用当前 props 和 state 来创建它。
77 -* **基于 props 的重复数据:** 尽可能使用 props 来作为实际状态的源。把 props 保存到 state 的一个有效的场景是需要知道它以前值的时候,因为 props 可能因为父组件的重绘而变化。
docs/docs/04-multiple-components.it-IT.md deleted
-190
@@ -1,190 +0,0 @@
1 ----
2 -id: multiple-components-it-IT
3 -title: Componenti Multipli
4 -permalink: docs/multiple-components-it-IT.html
5 -prev: interactivity-and-dynamic-uis-it-IT.html
6 -next: reusable-components-it-IT.html
7 ----
8 -
9 -Finora abbiamo visto come scrivere un singolo componente per mostrare dati e gestire l'input dell'itente. Adesso esaminiamo una delle migliori caratteristiche di React: la componibilità.
10 -
11 -
12 -## Motivazione: Separazione dei Concetti
13 -
14 -Costruendo componenti modulari che riutilizzano altri componenti con interfacce ben definite, ottieni gli stessi benefici che otterresti usando funzioni o classi. Nello specifico, puoi *separare i diversi concetti* della tua applicazione nel modo che preferisci semplicemente costruendo nuovi componenti. Costruendo una libreria di componenti personalizzati per la tua applicazione, stai esprimendo la tua UI in una maniera che si adatta meglio al tuo dominio.
15 -
16 -
17 -## Esepmio di Composizione
18 -
19 -Creiamo un semplice componente Avatar che mostra una foto del profilo e un nome utente usando la Graph API di Facebook.
20 -
21 -```javascript
22 -var Avatar = React.createClass({
23 - render: function() {
24 - return (
25 - <div>
26 - <ProfilePic username={this.props.username} />
27 - <ProfileLink username={this.props.username} />
28 - </div>
29 - );
30 - }
31 -});
32 -
33 -var ProfilePic = React.createClass({
34 - render: function() {
35 - return (
36 - <img src={'https://graph.facebook.com/' + this.props.username + '/picture'} />
37 - );
38 - }
39 -});
40 -
41 -var ProfileLink = React.createClass({
42 - render: function() {
43 - return (
44 - <a href={'https://www.facebook.com/' + this.props.username}>
45 - {this.props.username}
46 - </a>
47 - );
48 - }
49 -});
50 -
51 -ReactDOM.render(
52 - <Avatar username="pwh" />,
53 - document.getElementById('example')
54 -);
55 -```
56 -
57 -
58 -## Possesso
59 -
60 -Nell'esempio precedente, le istanze di `Avatar` *posseggono* instanze di `ProfilePic` e `ProfileLink`. In React, **un proprietario è il componente che imposta le `props` di altri componenti**. Più formalmente, se un componente `X` è creato nel metodo `render()` del componente `Y`, si dice che `X` è *di proprietà di* `Y`. Come discusso in precedenza, un componente non può mutare le sue `props` — sono sempre consistenti con il valore che il suo proprietario ha impostato. Questa invariante fondamentale porta a UI la cui consistenza può essere garantita.
61 -
62 -È importante distinguere tra la relazione di proprietario-proprietà e la relazione genitore-figlio. La relazione proprietario-proprietà è specifica di React, mentre la relazione genitore-figlio è semplicemente quella che conosci e ami del DOM. Nell'esempio precedente, `Avatar` possiede il `div`, le istanze di `ProfilePic` e `ProfileLink`, e `div` è il **genitore** (ma non il proprietario) delle istanze di `ProfilePic` e `ProfileLink`.
63 -
64 -
65 -## Figli
66 -
67 -Quando crei un'istanza di un componente React, puoi includere componenti React aggiuntivi o espressioni JavaScript tra i tag di apertura e chiusura come segue:
68 -
69 -```javascript
70 -<Parent><Child /></Parent>
71 -```
72 -
73 -`Parent` può accedere ai propri figli leggendo la speciale proprietà `this.props.children`. **`this.props.children` è una struttura dati opaca:** usa le [utilità React.Children](/react/docs/top-level-api.html#react.children) per manipolare i figli.
74 -
75 -
76 -### Riconciliazione dei Figli
77 -
78 -**La riconciliazione è il processo per il quale React aggiorna il DOM ad ogni passata di rendering.** In generale, i figli sono riconciliati secondo l'ordine in cui sono mostrati. Per esempio, supponiamo che due passate di rendering generino rispettivamente il markup seguente:
79 -
80 -```html
81 -// Prima passata di rendering
82 -<Card>
83 - <p>Paragrafo 1</p>
84 - <p>Paragrafo 2</p>
85 -</Card>
86 -// Seconda passata di rendering
87 -<Card>
88 - <p>Paragrafo 2</p>
89 -</Card>
90 -```
91 -
92 -Intuitivamente, `<p>Paragrafo 1</p>` è stato rimosso. Invece, React riconcilierà il DOM cambiando il testo contenuto nel primo figlio e distruggerà l'ultimo figlio. React reconcilia secondo l'*ordine* dei figli.
93 -
94 -
95 -### Figli Dotati di Stato
96 -
97 -Per molti componenti, questo non è un grande problema. Tuttavia, per i componenti dotati di stato che mantengono dati in `this.state` attraverso le diverse passate di rendering, questo può essere problematico.
98 -
99 -In molti casi, questo problema può essere aggirato nascondendo gli elementi anziché distruggendoli:
100 -
101 -```html
102 -// Prima passata di rendering
103 -<Card>
104 - <p>Paragrafo 1</p>
105 - <p>Paragrafo 2</p>
106 -</Card>
107 -// Seconda passata di rendering
108 -<Card>
109 - <p style={{'{{'}}display: 'none'}}>Paragrafo 1</p>
110 - <p>Paragrafo 2</p>
111 -</Card>
112 -```
113 -
114 -
115 -### Figli Dinamici
116 -
117 -La situazione si complica quando i figli sono rimescolati (come nei risultati della ricerca) o se nuovi componenti sono aggiunti all'inizio della lista (come negli stream). In questi casi quando l'identità e lo stato di ogni figlio deve essere preservato attraverso passate di rendering, puoi unicamente identificare ciascun figlio assegnandogli una proprietà `key`:
118 -
119 -```javascript
120 - render: function() {
121 - var results = this.props.results;
122 - return (
123 - <ol>
124 - {results.map(function(result) {
125 - return <li key={result.id}>{result.text}</li>;
126 - })}
127 - </ol>
128 - );
129 - }
130 -```
131 -
132 -Quando React riconcilia i figli dotati di `key`, si assicurerà che ciascun figlio con la proprietà `key` sia riordinato (anziché clobbered) o distrutto (anziché riutilizzato).
133 -
134 -La proprietà `key` dovrebbe *sempre* essere fornita direttamente all'elemento del componente nell'array, non al contenitore HTML di ciascun componente dell'array:
135 -
136 -```javascript
137 -// SBAGLIATO!
138 -var ListItemWrapper = React.createClass({
139 - render: function() {
140 - return <li key={this.props.data.id}>{this.props.data.text}</li>;
141 - }
142 -});
143 -var MyComponent = React.createClass({
144 - render: function() {
145 - return (
146 - <ul>
147 - {this.props.results.map(function(result) {
148 - return <ListItemWrapper data={result}/>;
149 - })}
150 - </ul>
151 - );
152 - }
153 -});
154 -```
155 -```javascript
156 -// Corretto :)
157 -var ListItemWrapper = React.createClass({
158 - render: function() {
159 - return <li>{this.props.data.text}</li>;
160 - }
161 -});
162 -var MyComponent = React.createClass({
163 - render: function() {
164 - return (
165 - <ul>
166 - {this.props.results.map(function(result) {
167 - return <ListItemWrapper key={result.id} data={result}/>;
168 - })}
169 - </ul>
170 - );
171 - }
172 -});
173 -```
174 -
175 -Puoi anche assegnare chiavi ai figli passandogli un oggetto ReactFragment. Leggi [Frammenti con Chiave](create-fragment.html) per maggiori dettagli.
176 -
177 -## Flusso dei Dati
178 -
179 -In React, i dati fluiscono dal proprietario al componente posseduto attraverso le `props` come discusso in precedenza. Questo è a tutti gli effetti un binding di dati unidirezionale: i proprietari legano le proprietà dei componenti di loro proprietà a dei valori che il proprietario stesso ha calcolato in base ai propri `props` o `state`. Dal momento che questo processo avviene ricorsivamente, i cambiamenti dei dati vengono riflessi automaticamente ovunque vengano usati.
180 -
181 -
182 -## Una Nota sulle Prestazioni
183 -
184 -Ti starai chiedendo che cambiare i dati sia un'operazione costosa in presenza di un gran numero di nodi sotto un proprietario. La buona notizia è che JavaScript è veloce e i metodi `render()` tendono ad essere molto semplici, quindi in molte applicazioni questo è un processo estremamente veloce. Inoltre, il collo di bottiglia è quasi sempre la mutazione del DOM e non l'esecuzione di JS. React ottimizzerà tutto per te usando il raggruppamento e osservando i cambiamenti.
185 -
186 -Tuttavia, a volte vorrai avere un controllo più raffinato sulle tue prestazioni. In tal caso, ridefinisci il metodo `shouldComponentUpdate()` per restituire false quando vuoi che React salti il trattamento di un sottoalbero. Consulta [la documentazione di riferimento di React](/react/docs/component-specs.html) per maggiori informazioni.
187 -
188 -> Nota:
189 ->
190 -> Se `shouldComponentUpdate()` restituisce false quando i dati sono effettivamente cambiati, React non è in grado di mantenere la tua UI in sincronia. Assicurati di usare questa tecnica con cognizione di causa, e soltanto in presenza di problemi percettibili di prestazioni. Non sottovalutare l'estrema velocità di esecuzione di JavaScript se paragonata a quella del DOM.
docs/docs/04-multiple-components.ja-JP.md deleted
-186
@@ -1,186 +0,0 @@
1 ----
2 -id: multiple-components
3 -title: 複数のコンポーネント
4 -permalink: docs/multiple-components-ja-JP.html
5 -prev: interactivity-and-dynamic-uis-ja-JP.html
6 -next: reusable-components-ja-JP.html
7 ----
8 -
9 -今まで、データを表示したりユーザの入力をハンドルするための1つのコンポーネントの書き方を見てきました。次に、 Reactの最も面白い特徴であるコンポーザビリティについて見ていきましょう。
10 -
11 -## 動機: 関心の分離
12 -
13 -うまく定義されたインターフェースとともに他のコンポーネントを再利用するモジュールのコンポーネントを構築することによって、関数やクラスを使う場合と同じ利益を得ることができます。特に、アプリの *異なった関心を分離* できるにも関わらず、新しいコンポーネントを単純に構築することで満足する場合には。アプリケーションにカスタムコンポーネントライブラリを構築することによって、あなたがやりたいことに最も合う方法でUIを表現することができます。
14 -
15 -## 構成例
16 -
17 -FacebookのグラフAPIを使って、プロフィール画像とユーザー名を表示する単純なアバターのコンポーネントを作ってみましょう。
18 -
19 -```javascript
20 -var Avatar = React.createClass({
21 - render: function() {
22 - return (
23 - <div>
24 - <ProfilePic username={this.props.username} />
25 - <ProfileLink username={this.props.username} />
26 - </div>
27 - );
28 - }
29 -});
30 -
31 -var ProfilePic = React.createClass({
32 - render: function() {
33 - return (
34 - <img src={'https://graph.facebook.com/' + this.props.username + '/picture'} />
35 - );
36 - }
37 -});
38 -
39 -var ProfileLink = React.createClass({
40 - render: function() {
41 - return (
42 - <a href={'https://www.facebook.com/' + this.props.username}>
43 - {this.props.username}
44 - </a>
45 - );
46 - }
47 -});
48 -
49 -ReactDOM.render(
50 - <Avatar username="pwh" />,
51 - document.getElementById('example')
52 -);
53 -```
54 -
55 -
56 -## 所有
57 -
58 -上記の例では、 `Avatar` のインスタンスは `ProfilePic` と `ProfileLink` のインスタンスを *所有* しています。Reactでは、 **所有者は、他のコンポーネントの `props` をセットするコンポーネントです。** 正式に言うと、もし `Y` コンポーネントの `render()` メソッドの中に `X` コンポーネントが作られた場合、 `X` は `Y` に所有されていると言います。以前述べたように、コンポーネントはそれ自身の `props` を変化させることはできません。 `props` は常に、所有者が彼らにセットしたものと一貫性があります。このキー要素は一貫性があることを保証するために、UIに反映されます。
59 -
60 -所有者と所有される側の関係と、親子の関係の違いを示すのは重要です。所有者と所有される側の関係はReact独特です。一方で、親子の関係は単純にDOMから分かる、愛すべき関係です。上の例では、 `Avatar` は `div` を所有しますが、 `ProfilePic` と `ProfileLink` インスタンスと、 `div` は `ProfilePic` と `ProfileLink`インスタンスの **親** (しかし、所有者ではありません)です。
61 -
62 -
63 -## 子
64 -
65 -Reactのコンポーネントのインスタンスを作成する時には、以下のように開始タグと終了タグの間に付加的なReactのコンポーネントやJavaScriptの表現を含めることができます。
66 -
67 -```javascript
68 -<Parent><Child /></Parent>
69 -```
70 -
71 -`Parent` は特別な `this.props.children` というプロパティでアクセスすることで、子要素を読み取ることができます。 **`this.props.children` は不透明なデータ構造です。** 操作するには[React.Children utilities](/react/docs/top-level-api.html#react.children)を使用してください。
72 -
73 -
74 -### 子要素の調和
75 -
76 -**調和はReactが新しいレンダリングのパスごとにDOMをアップデートするプロセスです。** 一般的に、子要素はレンダリングされる順序に従って調和します。例えば、2つのレンダリングパスを考えると、以下のそれぞれのマークアップが生成されます。
77 -
78 -```html
79 -// パス1のレンダリング
80 -<Card>
81 - <p>Paragraph 1</p>
82 - <p>Paragraph 2</p>
83 -</Card>
84 -// パス2のレンダリング
85 -<Card>
86 - <p>Paragraph 2</p>
87 -</Card>
88 -```
89 -
90 -直感的には、 `<p>Paragraph 1</p>` が削除されたように思えます。代わりに、Reactは1つ目の子要素のテキストコンテンツを変更し、最後の子要素を削除するという変更を加えることでDOMを調和させます。Reactは子要素の *順序* に従って調和するのです。
91 -
92 -
93 -
94 -### ステートフルな子要素
95 -
96 -多くのコンポーネントにとって、これは大きな処理ではありません。しかし、レンダリングのパスを超えて、 `this.state` にデータを保持しているステートフルなコンポーネントにとっては、これはとても問題になり得ます。
97 -
98 -多くのケースにおいては、以下のように、削除する代わりに要素を隠すことで回避することがあります。
99 -
100 -```html
101 -// パス1のレンダリング
102 -<Card>
103 - <p>Paragraph 1</p>
104 - <p>Paragraph 2</p>
105 -</Card>
106 -// パス2のレンダリング
107 -<Card>
108 - <p style={{'{{'}}display: 'none'}}>Paragraph 1</p>
109 - <p>Paragraph 2</p>
110 -</Card>
111 -```
112 -
113 -
114 -### 動的な子要素
115 -
116 -子要素がシャッフルされているような時(検索結果のように)や、リストの最初に新しいコンポーネントが追加されるような時(ストリームのように)には、状況はさらに複雑になります。そういったケースでは、それぞれの子要素のアイデンティティやstateがレンダリングパスを保持する必要があり、以下のように `key` を認識することでそれぞれの子要素をただ1つに識別できます。
117 -
118 -```javascript
119 - render: function() {
120 - var results = this.props.results;
121 - return (
122 - <ol>
123 - {results.map(function(result) {
124 - return <li key={result.id}>{result.text}</li>;
125 - })}
126 - </ol>
127 - );
128 - }
129 -```
130 -
131 -Reactがキー付けされた子要素を調和させるとき、 `key` と子要素が再び整理される(けんかをする代わりに)か削除されます(再利用される代わりに)。
132 -
133 -`key` は以下のように *常に* 配列の中でコンポーネントに直接提供されるべきで、その配列の中でそれぞれのコンポーネントのHTMLの子要素の入れ物に提供されるべきではありません。
134 -
135 -```javascript
136 -// 間違い!
137 -var ListItemWrapper = React.createClass({
138 - render: function() {
139 - return <li key={this.props.data.id}>{this.props.data.text}</li>;
140 - }
141 -});
142 -var MyComponent = React.createClass({
143 - render: function() {
144 - return (
145 - <ul>
146 - {this.props.results.map(function(result) {
147 - return <ListItemWrapper data={result}/>;
148 - })}
149 - </ul>
150 - );
151 - }
152 -});
153 -
154 -// 正解 :)
155 -var ListItemWrapper = React.createClass({
156 - render: function() {
157 - return <li>{this.props.data.text}</li>;
158 - }
159 -});
160 -var MyComponent = React.createClass({
161 - render: function() {
162 - return (
163 - <ul>
164 - {this.props.results.map(function(result) {
165 - return <ListItemWrapper key={result.id} data={result}/>;
166 - })}
167 - </ul>
168 - );
169 - }
170 -});
171 -```
172 -
173 -Reactのフラグのオブジェクトを渡すことで子要素をキー付けすることもできます。詳細は、[キー付けされたフラグ](create-fragment.html)をご覧ください。
174 -
175 -## データフロー
176 -
177 -Reactの、 `props` を通した所有者から所有されるコンポーネントへのデータフローは今までに記述してきました。これは実際には一方向のデータバインディングです。所有者は所有しているコンポーネントのpropsを、所有者が `props` か `state` に基づいて計算したいくつかの値にバインドします。このプロセスが何度も行われるので、データの変更は彼らが使われるところは自動的にどこでも反映されます。
178 -
179 -## パフォーマンスの注意
180 -
181 -みなさんは所有者の下にたくさんのノードがあるときには、データの変更には多くのコストがかかると考えるでしょう。良いニュースとして、JavaScriptは早く、 `render()` メソッドはとても単純になりやすいので、多くのアプリケーションにおいて、こういったことは非常に早くなります。加えて、ボトルネックとなるものの多くは、JSの実行ではなく、DOMの変更です。Reactは変更の一括処理と検知を使うことによって、それを最適化しています。
182 -
183 -しかし、パフォーマンスについて、よりよい制御を持つことを求める時もあるでしょう。こういったケースで、Reactがサブツリーの処理をスキップすることを求めるなら、 `shouldComponentUpdate()` が単純にfalseを返すようにオーバーライドしてください。更に情報を得たい場合には、[Reactのリファレンス文書](/react/docs/component-specs.html)を読んでください。
184 -
185 -> 注意:
186 -> `shouldComponentUpdate()` がデータが実際に変わった時にfalseを返したならば、ReactはUIを同期的に保つことができません。このメソッドを使う際には、何を行っているか理解してください。そして、顕著なパフォーマンスの問題がある時にだけ、この関数を使ってください。DOMと比較して、JavaScriptが速いことを過小評価しないでください。
docs/docs/04-multiple-components.ko-KR.md deleted
-182
@@ -1,182 +0,0 @@
1 ----
2 -id: multiple-components-ko-KR
3 -title: 복합 컴포넌트
4 -permalink: docs/multiple-components-ko-KR.html
5 -prev: interactivity-and-dynamic-uis-ko-KR.html
6 -next: reusable-components-ko-KR.html
7 ----
8 -
9 -지금까지, 단일 컴포넌트에서 데이터를 표시하고 유저 입력을 다루는 것을 살펴보았습니다. 다음엔 React의 최고의 기능 중 하나인 조합가능성(composability)을 살펴봅시다.
10 -
11 -## 동기: 관심의 분리
12 -
13 -명확히 정의된 인터페이스와 다른 컴포넌트를 재사용해 모듈러 컴포넌트를 구축하면, 함수와 클래스를 이용했을 때 얻을 수 있는 이점 대부분을 얻을 수 있습니다. 특히 앱에서 *다른 관심을 분리*할 수 있습니다.아무리 간단히 새 컴포넌트를 만들었다고 해도 말이죠. 당신의 애플리케이션에서 쓸 커스텀 컴포넌트 라이브러리를 만들어서, 당신의 도메인에 최적화된 방법으로 UI를 표현할 수 있게 됩니다.
14 -
15 -## 조합(Composition) 예제
16 -
17 -간단히 페이스북 그래프 API를 사용해 프로필 사진과 유저이름을 보여주는 아바타 컴포넌트를 만든다고 합시다.
18 -
19 -```javascript
20 -var Avatar = React.createClass({
21 - render: function() {
22 - return (
23 - <div>
24 - <ProfilePic username={this.props.username} />
25 - <ProfileLink username={this.props.username} />
26 - </div>
27 - );
28 - }
29 -});
30 -
31 -var ProfilePic = React.createClass({
32 - render: function() {
33 - return (
34 - <img src={'https://graph.facebook.com/' + this.props.username + '/picture'} />
35 - );
36 - }
37 -});
38 -
39 -var ProfileLink = React.createClass({
40 - render: function() {
41 - return (
42 - <a href={'https://www.facebook.com/' + this.props.username}>
43 - {this.props.username}
44 - </a>
45 - );
46 - }
47 -});
48 -
49 -ReactDOM.render(
50 - <Avatar username="pwh" />,
51 - document.getElementById('example')
52 -);
53 -```
54 -
55 -## 소유권(Ownership)
56 -
57 -위의 예제에서, `Avatar` 인스턴스는 `ProfilePic`과 `ProfileLink`인스턴스를 *가지고* 있습니다. React에서 **소유자는 다른 컴포넌트의 `props`를 설정하는 컴포넌트입니다**. 더 정식으로 말하면, `X` 컴포넌트가 `Y` 컴포넌트의 `render()` 메소드 안에서 만들어졌다면, `Y`가 `X`를 *소유하고* 있다고 합니다. 앞에서 설명한 바와 같이, 컴포넌트는 자신의 `props`를 변경할 수 없습니다. `props`는 언제나 소유자가 설정한 것과 일치합니다. 이와 같은 근본적인 불변성은 UI가 일관성 있도록 해줍니다.
58 -
59 -소유(owner-ownee)관계와 부모·자식 관계를 구별하는 것은 중요합니다. 부모·자식 관계가 DOM에서부터 쓰던 익숙하고 이미 알고있던 단순한 것인 한편, 소유관계는 React 고유의 것입니다. 위의 예제에서, `Avatar`는 `div`, `ProfilePic`, `ProfileLink`인스턴스를 소유하고, `div`는 `ProfilePic`과 `ProfileLink`인스턴스의 (소유자가 아닌) **부모**입니다.
60 -
61 -## 자식
62 -
63 -React 컴포넌트 인스턴스를 만들 때, 추가적인 React 컴포넌트나 JavaScript 표현식을 시작과 끝 태그 사이에 넣을 수 있습니다. 이렇게 말이죠.
64 -
65 -```javascript
66 -<Parent><Child /></Parent>
67 -```
68 -
69 -`Parent`는 `this.props.children`라는 특수 prop으로 자식들을 읽을 수 있습니다. **`this.props.children` 는 불투명한 데이터 구조이며,** [React.Children 유틸리티](/react/docs/top-level-api-ko-KR.html#react.children)를 사용해 자식들을 관리합니다.
70 -
71 -### 자식 Reconciliation (비교조정)
72 -
73 -**Reconciliation은 React가 DOM을 각각 새로운 렌더 패스에 업데이트하는 과정입니다.** 일반적으로, 자식은 렌더하는 순서에 따라 비교조정됩니다. 예를 들어, 각각의 마크업을 생성하는 두 개의 렌더 패스가 있다고 해봅시다.
74 -
75 -```html
76 -// Render Pass 1
77 -<Card>
78 - <p>Paragraph 1</p>
79 - <p>Paragraph 2</p>
80 -</Card>
81 -// Render Pass 2
82 -<Card>
83 - <p>Paragraph 2</p>
84 -</Card>
85 -```
86 -
87 -직관적으로 보면, `<p>Paragraph 1</p>`가 없어졌습니다만 그러는 대신에, React는 첫 번째 자식의 텍스트를 비교조정하고 마지막 자식을 파괴하도록 DOM을 비교조정할 것입니다. React는 자식들의 *순서*에 따라 비교조정합니다.
88 -
89 -### 상태기반(Stateful) 자식
90 -
91 -대부분의 컴포넌트에서는, 이것은 큰 문제가 아닙니다. 하지만 렌더 패스 간에 `this.state`를 유지하는 상태기반의 컴포넌트에서는 매우 문제가 될 수 있습니다.
92 -
93 -대부분의 경우, 이 문제는 엘리먼트를 파괴하지 않고 숨김으로써 피해갈 수 있습니다.
94 -
95 -```html
96 -// Render Pass 1
97 -<Card>
98 - <p>Paragraph 1</p>
99 - <p>Paragraph 2</p>
100 -</Card>
101 -// Render Pass 2
102 -<Card>
103 - <p style={{'{{'}}display: 'none'}}>Paragraph 1</p>
104 - <p>Paragraph 2</p>
105 -</Card>
106 -```
107 -
108 -### 동적 자식
109 -
110 -자식들이 섞이거나(검색의 결과같은 경우) 새로운 컴포넌트가 목록의 앞에 추가(스트림같은 경우)된다면 상황은 점점 더 까다로워집니다. 이런 때에의 동일성과 각 자식의 상태는 반드시 렌더 패스 간에 유지돼야 합니다. 각 자식에 `key`를 할당 함으로써 독자적으로 식별할 수 있습니다.
111 -
112 -```javascript
113 - render: function() {
114 - var results = this.props.results;
115 - return (
116 - <ol>
117 - {results.map(function(result) {
118 - return <li key={result.id}>{result.text}</li>;
119 - })}
120 - </ol>
121 - );
122 - }
123 -```
124 -
125 -React가 키가 있는 자식들을 비교조정할 때, React는 `key`가 있는 자식이 (오염(clobbered)되는 대신) 재배치되고 (재사용되는 대신) 파괴되도록 보장할 것입니다.
126 -
127 -`key`는 *항상* 배열 안의 각 컴포넌트의 컨테이너 HTML 자식이 아닌 컴포넌트에게 직접 주어져야 합니다.
128 -
129 -```javascript
130 -// 틀림!
131 -var ListItemWrapper = React.createClass({
132 - render: function() {
133 - return <li key={this.props.data.id}>{this.props.data.text}</li>;
134 - }
135 -});
136 -var MyComponent = React.createClass({
137 - render: function() {
138 - return (
139 - <ul>
140 - {this.props.results.map(function(result) {
141 - return <ListItemWrapper data={result}/>;
142 - })}
143 - </ul>
144 - );
145 - }
146 -});
147 -```
148 -```javascript
149 -// 맞음 :)
150 -var ListItemWrapper = React.createClass({
151 - render: function() {
152 - return <li>{this.props.data.text}</li>;
153 - }
154 -});
155 -var MyComponent = React.createClass({
156 - render: function() {
157 - return (
158 - <ul>
159 - {this.props.results.map(function(result) {
160 - return <ListItemWrapper key={result.id} data={result}/>;
161 - })}
162 - </ul>
163 - );
164 - }
165 -});
166 -```
167 -
168 -ReactFragment 객체를 넘기는 것으로 자식에 키를 할당할 수도 있습니다. 자세한 내용은 [키가 할당된 프래그먼트](create-fragment-ko-KR.html)를 참고하세요.
169 -
170 -## 데이터 흐름
171 -
172 -React에서 데이터는 위에서 말한 것처럼 `props`를 통해 소유자로부터 소유한 컴포넌트로 흐릅니다. 이것은 사실상 단방향 데이터 바인딩입니다. 소유자는 `props`나 `state`를 기준으로 계산한 어떤 값으로 소유한 컴포넌트의 props를 바인드합니다. 이 과정은 재귀적으로 발생하므로, 데이터의 변경은 자동으로 모든 곳에 반영됩니다.
173 -
174 -## 성능의 주의점
175 -
176 -소유자가 가지고 있는 노드의 수가 많아지면 데이터가 변화하는 비용이 증가할 것으로 생각할 수도 있습니다. 좋은 소식은 JavaScript의 속도는 빠르고 `render()` 메소드는 꽤 간단한 경향이 있어, 대부분 애플리케이션에서 매우 빠르다는 점입니다. 덧붙여, 대부분의 병목 현상은 JS 실행이 아닌 DOM 변경에서 일어나고, React는 배치와 탐지 변경을 이용해 최적화해 줍니다.
177 -
178 -하지만, 가끔 성능을 위해 정교하게 제어해야 할 때도 있습니다. 이런 경우, React가 서브트리의 처리를 건너 뛰도록 간단히 `shouldComponentUpdate()`를 오버라이드해 false를 리턴하게 할 수 있습니다. 좀 더 자세한 정보는 [React 참조 문서](/react/docs/component-specs-ko-KR.html)를 보세요.
179 -
180 -> 주의:
181 ->
182 -> 데이터가 실제로는 변경되었지만 `shouldComponentUpdate()`가 false를 리턴한다면 React는 UI를 싱크시킬수 없습니다. 이 기능을 사용할 때에는 자신이 지금 무엇을 하고 있는지 알고 있고, 눈에 띄는 성능 문제가 있을 경우에만 사용하세요. JavaScript는 DOM에 비해 빠릅니다. 과소평가하지 마세요.
docs/docs/04-multiple-components.md deleted
-181
@@ -1,181 +0,0 @@
1 ----
2 -id: multiple-components
3 -title: Multiple Components
4 -permalink: docs/multiple-components.html
5 -prev: interactivity-and-dynamic-uis.html
6 -next: reusable-components.html
7 ----
8 -
9 -So far, we've looked at how to write a single component to display data and handle user input. Next let's examine one of React's finest features: composability.
10 -
11 -## Motivation: Separation of Concerns
12 -
13 -By building modular components that reuse other components with well-defined interfaces, you get much of the same benefits that you get by using functions or classes. Specifically you can *separate the different concerns* of your app however you please simply by building new components. By building a custom component library for your application, you are expressing your UI in a way that best fits your domain.
14 -
15 -## Composition Example
16 -
17 -Let's create a simple Avatar component which shows a Facebook page picture and name using the Facebook Graph API.
18 -
19 -```javascript
20 -class Avatar extends React.Component {
21 - render() {
22 - return (
23 - <div>
24 - <PagePic pagename={this.props.pagename} />
25 - <PageLink pagename={this.props.pagename} />
26 - </div>
27 - );
28 - }
29 -}
30 -
31 -class PagePic extends React.Component {
32 - render() {
33 - return (
34 - <img src={'https://graph.facebook.com/' + this.props.pagename + '/picture'} />
35 - );
36 - }
37 -}
38 -
39 -class PageLink extends React.Component {
40 - render() {
41 - return (
42 - <a href={'https://www.facebook.com/' + this.props.pagename}>
43 - {this.props.pagename}
44 - </a>
45 - );
46 - }
47 -}
48 -
49 -ReactDOM.render(
50 - <Avatar pagename="Engineering" />,
51 - document.getElementById('example')
52 -);
53 -```
54 -
55 -## Ownership
56 -
57 -In the above example, instances of `Avatar` *own* instances of `PagePic` and `PageLink`. In React, **an owner is the component that sets the `props` of other components**. More formally, if a component `X` is created in component `Y`'s `render()` method, it is said that `X` is *owned by* `Y`. As discussed earlier, a component cannot mutate its `props` — they are always consistent with what its owner sets them to. This fundamental invariant leads to UIs that are guaranteed to be consistent.
58 -
59 -It's important to draw a distinction between the owner-ownee relationship and the parent-child relationship. The owner-ownee relationship is specific to React, while the parent-child relationship is simply the one you know and love from the DOM. In the example above, `Avatar` owns the `div`, `PagePic` and `PageLink` instances, and `div` is the **parent** (but not owner) of the `PagePic` and `PageLink` instances.
60 -
61 -## Children
62 -
63 -When you create a React component instance, you can include additional React components or JavaScript expressions between the opening and closing tags like this:
64 -
65 -```javascript
66 -<Parent><Child /></Parent>
67 -```
68 -
69 -`Parent` can read its children by accessing the special `this.props.children` prop. **`this.props.children` is an opaque data structure:** use the [React.Children utilities](/react/docs/top-level-api.html#react.children) to manipulate them.
70 -
71 -### Child Reconciliation
72 -
73 -**Reconciliation is the process by which React updates the DOM with each new render pass.** In general, children are reconciled according to the order in which they are rendered. For example, suppose two render passes generate the following respective markup:
74 -
75 -```html
76 -// Render Pass 1
77 -<Card>
78 - <p>Paragraph 1</p>
79 - <p>Paragraph 2</p>
80 -</Card>
81 -// Render Pass 2
82 -<Card>
83 - <p>Paragraph 2</p>
84 -</Card>
85 -```
86 -
87 -Intuitively, `<p>Paragraph 1</p>` was removed. Instead, React will reconcile the DOM by changing the text content of the first child and destroying the last child. React reconciles according to the *order* of the children.
88 -
89 -### Stateful Children
90 -
91 -For most components, this is not a big deal. However, for stateful components that maintain data in `this.state` across render passes, this can be very problematic.
92 -
93 -In most cases, this can be sidestepped by hiding elements instead of destroying them:
94 -
95 -```html
96 -// Render Pass 1
97 -<Card>
98 - <p>Paragraph 1</p>
99 - <p>Paragraph 2</p>
100 -</Card>
101 -// Render Pass 2
102 -<Card>
103 - <p style={{'{{'}}display: 'none'}}>Paragraph 1</p>
104 - <p>Paragraph 2</p>
105 -</Card>
106 -```
107 -
108 -### Dynamic Children
109 -
110 -The situation gets more complicated when the children are shuffled around (as in search results) or if new components are added onto the front of the list (as in streams). In these cases where the identity and state of each child must be maintained across render passes, you can uniquely identify each child by assigning it a `key`:
111 -
112 -```javascript
113 - render() {
114 - return (
115 - <ol>
116 - {this.props.results.map((result) => (
117 - <li key={result.id}>{result.text}</li>
118 - ))}
119 - </ol>
120 - );
121 - }
122 -```
123 -
124 -When React reconciles the keyed children, it will ensure that any child with `key` will be reordered (instead of clobbered) or destroyed (instead of reused).
125 -
126 -The `key` should *always* be supplied directly to the components in the array, not to the container HTML child of each component in the array:
127 -
128 -```javascript
129 -// WRONG!
130 -class ListItemWrapper extends React.Component {
131 - render() {
132 - return <li key={this.props.data.id}>{this.props.data.text}</li>;
133 - }
134 -}
135 -class MyComponent extends React.Component {
136 - render() {
137 - return (
138 - <ul>
139 - {this.props.results.map((result) => (
140 - <ListItemWrapper data={result} />
141 - ))}
142 - </ul>
143 - );
144 - }
145 -}
146 -```
147 -```javascript
148 -// Correct :)
149 -class ListItemWrapper extends React.Component {
150 - render() {
151 - return <li>{this.props.data.text}</li>;
152 - }
153 -}
154 -class MyComponent extends React.Component {
155 - render() {
156 - return (
157 - <ul>
158 - {this.props.results.map((result) => (
159 - <ListItemWrapper key={result.id} data={result} />
160 - ))}
161 - </ul>
162 - );
163 - }
164 -}
165 -```
166 -
167 -You can also key children by passing a ReactFragment object. See [Keyed Fragments](create-fragment.html) for more details.
168 -
169 -## Data Flow
170 -
171 -In React, data flows from owner to owned component through `props` as discussed above. This is effectively one-way data binding: owners bind their owned component's props to some value the owner has computed based on its `props` or `state`. Since this process happens recursively, data changes are automatically reflected everywhere they are used.
172 -
173 -## A Note on Performance
174 -
175 -You may be thinking that it's expensive to change data if there are a large number of nodes under an owner. The good news is that JavaScript is fast and `render()` methods tend to be quite simple, so in most applications this is extremely fast. Additionally, the bottleneck is almost always the DOM mutation and not JS execution. React will optimize this for you by using batching and change detection.
176 -
177 -However, sometimes you really want to have fine-grained control over your performance. In that case, simply override `shouldComponentUpdate()` to return false when you want React to skip processing of a subtree. See [the React reference docs](/react/docs/component-specs.html) for more information.
178 -
179 -> Note:
180 ->
181 -> If `shouldComponentUpdate()` returns false when data has actually changed, React can't keep your UI in sync. Be sure you know what you're doing while using it, and only use this function when you have a noticeable performance problem. Don't underestimate how fast JavaScript is relative to the DOM.
docs/docs/04-multiple-components.zh-CN.md deleted
-183
@@ -1,183 +0,0 @@
1 ----
2 -id: multiple-components-zh-CN
3 -title: 复合组件
4 -permalink: docs/multiple-components-zh-CN.html
5 -prev: interactivity-and-dynamic-uis-zh-CN.html
6 -next: reusable-components-zh-CN.html
7 ----
8 -
9 -目前为止,我们已经学了如何用单个组件来展示数据和处理用户输入。下一步让我们来体验 React 最激动人心的特性之一:可组合性(composability)。
10 -
11 -## 动机:关注分离
12 -
13 -通过复用那些接口定义良好的组件来开发新的模块化组件,我们得到了与使用函数和类相似的好处。具体来说就是能够通过开发简单的组件把程序的*不同关注面分离*。如果为程序开发一套自定义的组件库,那么就能以最适合业务场景的方式来展示你的用户界面。
14 -
15 -## 组合实例
16 -
17 -让我们用 Facebook Graph API 来开发一个显示 Facebook 页面图片和用户名的简单 Avatar 组件吧。
18 -
19 -```javascript
20 -var Avatar = React.createClass({
21 - render: function() {
22 - return (
23 - <div>
24 - <PagePic pagename={this.props.pagename} />
25 - <PageLink pagename={this.props.pagename} />
26 - </div>
27 - );
28 - }
29 -});
30 -
31 -var PagePic = React.createClass({
32 - render: function() {
33 - return (
34 - <img src={'https://graph.facebook.com/' + this.props.pagename + '/picture'} />
35 - );
36 - }
37 -});
38 -
39 -var PageLink = React.createClass({
40 - render: function() {
41 - return (
42 - <a href={'https://www.facebook.com/' + this.props.pagename}>
43 - {this.props.pagename}
44 - </a>
45 - );
46 - }
47 -});
48 -
49 -ReactDOM.render(
50 - <Avatar pagename="Engineering" />,
51 - document.getElementById('example')
52 -);
53 -```
54 -
55 -## 从属关系
56 -
57 -上面例子中,`Avatar` 拥有 `PagePic` 和 `PageLink` 的实例。`拥有者` 就是给其它组件设置 `props` 的那个组件。更正式地说,如果组件 `Y` 在 `render()` 方法是创建了组件 `X`,那么 `Y` 就拥有 `X`。上面讲过,组件不能修改自身的 `props` - 它们总是与它们的拥有者所设置的值保持一致。这是保持用户界面一致性的基本不变量。
58 -
59 -把从属关系与父子关系加以区别至关重要。从属关系是 React 特有的,而父子关系简单来讲就是 DOM 里的标签的关系。在上一个例子中,`Avatar` 拥有 `div`、`PagePic` 和 `PageLink` 实例,`div` 是 `PagePic` 和 `PageLink` 实例的**父级**(但不是拥有者)。
60 -
61 -## 子级
62 -
63 -实例化 React 组件时,你可以在开始标签和结束标签之间引用在React 组件或者Javascript 表达式:
64 -
65 -```javascript
66 -<Parent><Child /></Parent>
67 -```
68 -
69 -`Parent` 能通过专门的 `this.props.children` prop 读取子级。**`this.props.children` 是一个不透明的数据结构:** 通过 [React.Children 工具类](/react/docs/top-level-api.html#react.children) 来操作。
70 -
71 -### 子级校正(Reconciliation)
72 -
73 -**校正就是每次 render 方法调用后 React 更新 DOM 的过程。** 一般情况下,子级会根据它们被渲染的顺序来做校正。例如,下面代码描述了两次渲染的过程:
74 -
75 -```html
76 -// 第一次渲染
77 -<Card>
78 - <p>Paragraph 1</p>
79 - <p>Paragraph 2</p>
80 -</Card>
81 -// 第二次渲染
82 -<Card>
83 - <p>Paragraph 2</p>
84 -</Card>
85 -```
86 -
87 -直观来看,只是删除了`<p>Paragraph 1</p>`。事实上,React 先更新第一个子级的内容,然后删除最后一个组件。React 是根据子级的*顺序*来校正的。
88 -
89 -### 子组件状态管理
90 -
91 -对于大多数组件,这没什么大碍。但是,对于使用 `this.state` 来在多次渲染过程中里维持数据的状态化组件,这样做潜在很多问题。
92 -
93 -多数情况下,可以通过隐藏组件而不是删除它们来绕过这些问题。
94 -
95 -```html
96 -// 第一次渲染
97 -<Card>
98 - <p>Paragraph 1</p>
99 - <p>Paragraph 2</p>
100 -</Card>
101 -// 第二次渲染
102 -<Card>
103 - <p style={{'{{'}}display: 'none'}}>Paragraph 1</p>
104 - <p>Paragraph 2</p>
105 -</Card>
106 -```
107 -
108 -### 动态子级
109 -
110 -如果子组件位置会改变(如在搜索结果中)或者有新组件添加到列表开头(如在流中)情况会变得更加复杂。如果子级要在多个渲染阶段保持自己的特征和状态,在这种情况下,你可以通过给子级设置惟一标识的 `key` 来区分。
111 -
112 -```javascript
113 - render: function() {
114 - var results = this.props.results;
115 - return (
116 - <ol>
117 - {results.map(function(result) {
118 - return <li key={result.id}>{result.text}</li>;
119 - })}
120 - </ol>
121 - );
122 - }
123 -```
124 -
125 -当 React 校正带有 key 的子级时,它会确保它们被重新排序(而不是破坏)或者删除(而不是重用)。
126 -
127 -务必把 `key` 添加到子级数组中的组件本身上,而不是数组中每个子级组件内部的最外层 HTML 上:
128 -
129 -```javascript
130 -// 错误!
131 -var ListItemWrapper = React.createClass({
132 - render: function() {
133 - return <li key={this.props.data.id}>{this.props.data.text}</li>;
134 - }
135 -});
136 -var MyComponent = React.createClass({
137 - render: function() {
138 - return (
139 - <ul>
140 - {this.props.results.map(function(result) {
141 - return <ListItemWrapper data={result}/>;
142 - })}
143 - </ul>
144 - );
145 - }
146 -});
147 -```
148 -```javascript
149 -// 正确 :)
150 -var ListItemWrapper = React.createClass({
151 - render: function() {
152 - return <li>{this.props.data.text}</li>;
153 - }
154 -});
155 -var MyComponent = React.createClass({
156 - render: function() {
157 - return (
158 - <ul>
159 - {this.props.results.map(function(result) {
160 - return <ListItemWrapper key={result.id} data={result}/>;
161 - })}
162 - </ul>
163 - );
164 - }
165 -});
166 -```
167 -
168 -也可以传递 ReactFragment 对象来做有 key 的子级。详见[Keyed Fragments](create-fragment.html)
169 -
170 -## 数据流
171 -
172 -React 里,数据通过上面介绍过的 `props` 从拥有者流向归属者。这就是高效的单向数据绑定(one-way data binding):拥有者们通过它们的 `props` 或 `state` 计算出一些值,并把这些值绑定到它们拥有的组件的 props 上。因为这个过程会递归地调用,所以数据变化会自动在所有它们被使用的地方反映出来。
173 -
174 -
175 -## 性能提醒
176 -
177 -你或许会担心如果一个拥有者有大量子级时,对于数据变化做出响应非常耗费性能。值得庆幸的是执行 JavaScript 非常的快,而且 `render()` 方法一般比较简单,所以在大部分应用里这样做速度极快。此外,性能的瓶颈大多是因为 DOM 更新,而非 JS 执行,而且 React 会通过批量更新和变化检测来优化性能。
178 -
179 -但是,有时候需要做细粒度的性能控制。这种情况下,可以重写 `shouldComponentUpdate()` 方法返回 false 来让 React 跳过对子树的处理。参考 [React reference docs](/react/docs/component-specs.html) 了解更多。
180 -
181 -> 注意:
182 ->
183 -> 如果在数据变化时让 `shouldComponentUpdate()` 返回 false,React 就不能保证用户界面同步。当使用它的时候一定确保你清楚到底做了什么,并且只在遇到明显性能问题的时候才使用它。不要低估 JavaScript 的速度,DOM 操作通常才是慢的原因。
docs/docs/05-reusable-components.it-IT.md deleted
-264
@@ -1,264 +0,0 @@
1 ----
2 -id: reusable-components-it-IT
3 -title: Componenti Riutilizzabili
4 -permalink: docs/reusable-components-it-IT.html
5 -prev: multiple-components-it-IT.html
6 -next: transferring-props-it-IT.html
7 ----
8 -
9 -Quando disegni interfacce, separa gli elementi comuni di design (bottoni, campi dei moduli, componenti di layout, etc.) in componenti riutilizzabili con interfacce ben definite. In questo modo, la prossima volta che dovrai costruire una nuova UI, puoi scrivere molto meno codice. Ciò significa tempi di sviluppo più brevi, meno bachi, e meno byte trasferiti sulla rete.
10 -
11 -
12 -## Validazione delle Proprietà
13 -
14 -Mentre la tua applicazione cresce, è utile assicurarsi che i tuoi componenti vengano usati correttamente. Ciò viene fatto permettendoti di specificare i `propTypes`. `React.PropTypes` esporta una gamma di validatori che possono essere usati per assicurarsi che i dati che ricevi siano validi. Quando ad una proprietà è assegnato un valore non valido, sarà mostrato un avvertimento nella console JavaScript. Nota che per motivi di prestazioni, `propTypes` è utilizzato soltanto nella modalità di sviluppo. Di seguito trovi un esempio che documenta i diversi validatori che vengono forniti:
15 -
16 -```javascript
17 -React.createClass({
18 - propTypes: {
19 - // Puoi dichiarare che una proprietà è uno specifico tipo primitivo JS. In
20 - // maniera predefinita, questi sono tutti opzionali.
21 - optionalArray: React.PropTypes.array,
22 - optionalBool: React.PropTypes.bool,
23 - optionalFunc: React.PropTypes.func,
24 - optionalNumber: React.PropTypes.number,
25 - optionalObject: React.PropTypes.object,
26 - optionalString: React.PropTypes.string,
27 - optionalSymbol: React.PropTypes.symbol,
28 -
29 - // Tutto ciò che può essere mostrato: numeri, stringhe, elementi, o un array
30 - // (o frammento) contenente questi tipi.
31 - optionalNode: React.PropTypes.node,
32 -
33 - // Un elemento React.
34 - optionalElement: React.PropTypes.element,
35 -
36 - // Puoi anche dichiarare che una proprietà è un'istanza di una classe. Questo
37 - // validatore usa l'operatore instanceof di JS.
38 - optionalMessage: React.PropTypes.instanceOf(Message),
39 -
40 - // Puoi assicurarti che la tua proprietà sia ristretta a valori specifici
41 - // trattandoli come una enumerazione.
42 - optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),
43 -
44 - // Un oggetto che può essere di uno tra diversi tipi
45 - optionalUnion: React.PropTypes.oneOfType([
46 - React.PropTypes.string,
47 - React.PropTypes.number,
48 - React.PropTypes.instanceOf(Message)
49 - ]),
50 -
51 - // Un array di un tipo specificato
52 - optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
53 -
54 - // Un oggetto con proprietà dai valori di un tipo specificato
55 - optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
56 -
57 - // Un oggetto che accetta una forma particolare
58 - optionalObjectWithShape: React.PropTypes.shape({
59 - color: React.PropTypes.string,
60 - fontSize: React.PropTypes.number
61 - }),
62 -
63 - // Puoi concatenare ciascuna delle precedenti con `isRequired` per assicurarti
64 - // che venga mostrato un avvertimento se la proprietà non viene impostata.
65 - requiredFunc: React.PropTypes.func.isRequired,
66 -
67 - // Un valore di un tipo qualsiasi
68 - requiredAny: React.PropTypes.any.isRequired,
69 -
70 - // Puoi inoltre specificare un validatore personalizzato. Deve restituire un
71 - // oggetto di tipo Error se la validazione fallisce. Non lanciare eccezioni
72 - // o utilizzare `console.warn`, in quanto non funzionerebbe all'interno di
73 - // `oneOfType`.
74 - customProp: function(props, propName, componentName) {
75 - if (!/matchme/.test(props[propName])) {
76 - return new Error('Validazione fallita!');
77 - }
78 - }
79 - },
80 - /* ... */
81 -});
82 -```
83 -
84 -
85 -## Valori Predefiniti delle Proprietà
86 -
87 -React ti permette di definire valori predefiniti per le tue `props` in una maniera molto dichiarativa:
88 -
89 -```javascript
90 -var ComponentWithDefaultProps = React.createClass({
91 - getDefaultProps: function() {
92 - return {
93 - value: 'valore predefinito'
94 - };
95 - }
96 - /* ... */
97 -});
98 -```
99 -
100 -Il risultato di `getDefaultProps()` sarà conservato e usato per assicurarsi che `this.props.value` avrà sempre un valore se non è stato specificato dal componente proprietario. Ciò ti permette di utilizzare in sicurezza le tue proprietà senza dover scrivere codice fragile e ripetitivo per gestirlo da te.
101 -
102 -
103 -## Trasferire le Proprietà: Una Scorciatoia
104 -
105 -Un tipo comune di componente React è uno che estende un elemento basico HTML in maniera semplice. Spesso vorrai copiare qualsiasi attributo HTML passato al tuo componente all'elemento HTML sottostante per risparmiare del codice. Puoi usare la sintassi _spread_ di JSX per ottenerlo:
106 -
107 -```javascript
108 -var CheckLink = React.createClass({
109 - render: function() {
110 - // Questo prende ciascuna proprietà passata a CheckLink e la copia su <a>
111 - return <a {...this.props}>{'√ '}{this.props.children}</a>;
112 - }
113 -});
114 -
115 -ReactDOM.render(
116 - <CheckLink href="/checked.html">
117 - Clicca qui!
118 - </CheckLink>,
119 - document.getElementById('example')
120 -);
121 -```
122 -
123 -## Figlio Singolo
124 -
125 -Con `React.PropTypes.element` puoi specificare che solo un figlio unico possa essere passato come figli ad un componente.
126 -
127 -```javascript
128 -var MyComponent = React.createClass({
129 - propTypes: {
130 - children: React.PropTypes.element.isRequired
131 - },
132 -
133 - render: function() {
134 - return (
135 - <div>
136 - {this.props.children} // Questo deve essere esattamente un elemento oppure lancerà un'eccezione.
137 - </div>
138 - );
139 - }
140 -
141 -});
142 -```
143 -
144 -## Mixin
145 -
146 -I componenti sono la maniera migliore di riutilizzare il codice in React, ma a volte componenti molto diversi possono condividere funzionalità comune. Questi sono a volte chiamate [responsabilità trasversali](https://en.wikipedia.org/wiki/Cross-cutting_concern). React fornisce i `mixin` per risolvere questo problema.
147 -
148 -Un caso d'uso comune è un componente che desidera aggiornarsi ad intervalli di tempo. È facile usare `setInterval()`, ma è anche importante cancellare la chiamata ripetuta quando non è più necessaria per liberare memoria. React fornisce dei [metodi del ciclo di vita](/react/docs/working-with-the-browser.html#component-lifecycle) che ti permettono di sapere quando un componente sta per essere creato o distrutto. Creiamo un semplice mixin che usa questi metodi per fornire una facile funzione `setInterval()` che sarà automaticamente rimossa quando il tuo componente viene distrutto.
149 -
150 -```javascript
151 -var SetIntervalMixin = {
152 - componentWillMount: function() {
153 - this.intervals = [];
154 - },
155 - setInterval: function() {
156 - this.intervals.push(setInterval.apply(null, arguments));
157 - },
158 - componentWillUnmount: function() {
159 - this.intervals.forEach(clearInterval);
160 - }
161 -};
162 -
163 -var TickTock = React.createClass({
164 - mixins: [SetIntervalMixin], // Usa il mixin
165 - getInitialState: function() {
166 - return {seconds: 0};
167 - },
168 - componentDidMount: function() {
169 - this.setInterval(this.tick, 1000); // Chiama un metodo del mixin
170 - },
171 - tick: function() {
172 - this.setState({seconds: this.state.seconds + 1});
173 - },
174 - render: function() {
175 - return (
176 - <p>
177 - React has been running for {this.state.seconds} seconds.
178 - </p>
179 - );
180 - }
181 -});
182 -
183 -ReactDOM.render(
184 - <TickTock />,
185 - document.getElementById('example')
186 -);
187 -```
188 -
189 -Una caratteristica interessante dei mixin è che, se un componente usa molteplici mixin e diversi mixin definiscono lo stesso metodo del ciclo di vita (cioè diversi mixin desiderano effettuare una pulizia quando il componente viene distrutto), viene garantito che tutti i metodi del ciclo di vita verranno chiamati. I metodi definiti nei mixin vengono eseguiti nell'ordine in cui i mixin sono elencati, seguiti da una chiamata al metodo definito nel componente.
190 -
191 -## Classi ES6
192 -
193 -Puoi anche definire le tue classi React come pure classi JavaScript. Per esempio, usando la sintassi delle classi ES6:
194 -
195 -```javascript
196 -class HelloMessage extends React.Component {
197 - render() {
198 - return <div>Ciao {this.props.name}</div>;
199 - }
200 -}
201 -ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
202 -```
203 -
204 -L'API è simile a `React.createClass` con l'eccezione del metodo `getInitialState`. Anziché fornire un metodo `getInitialState` a parte, imposti la tua proprietà `state` nel costruttore.
205 -
206 -Un'altra differenza è che `propTypes` e `defaultProps` sono definite come proprietà del costruttore anziché nel corpo della classe.
207 -
208 -```javascript
209 -export class Counter extends React.Component {
210 - constructor(props) {
211 - super(props);
212 - this.state = {count: props.initialCount};
213 - }
214 - tick() {
215 - this.setState({count: this.state.count + 1});
216 - }
217 - render() {
218 - return (
219 - <div onClick={this.tick.bind(this)}>
220 - Click: {this.state.count}
221 - </div>
222 - );
223 - }
224 -}
225 -Counter.propTypes = { initialCount: React.PropTypes.number };
226 -Counter.defaultProps = { initialCount: 0 };
227 -```
228 -
229 -### Niente Binding Automatico
230 -
231 -I metodi seguono la stessa semantica delle classi ES6 regolari, ciò significa che non effettuano il binding automatico di `this` all'istanza. Dovrai pertanto usare esplicitamente `.bind(this)` oppure [le funzioni freccia](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) `=>`.
232 -
233 -### Niente Mixin
234 -
235 -Sfortunatamente, ES6 è stato lanciato senza alcun supporto per i mixin. Di conseguenza non vi è alcun supporto per i mixin quando usi React con le classi ES6. Stiamo lavorando per rendere più semplice il supporto dei relativi casi d'uso senza ricorrere ai mixin.
236 -
237 -
238 -
239 -## Funzioni Prive di Stato
240 -
241 -Puoi anche definire le tue classi React come semplici funzioni JavaScript. Ad esempio usando la sintassi della funzione priva di stato:
242 -
243 -```javascript
244 -function HelloMessage(props) {
245 - return <div>Ciao {props.name}</div>;
246 -}
247 -ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
248 -```
249 -
250 -Oppure usando la nuova sintassi freccia di ES6:
251 -
252 -```javascript
253 -const HelloMessage = (props) => <div>Ciao {props.name}</div>;
254 -ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
255 -```
256 -
257 -
258 -Questa API semplificata dei componenti è intesa per i componenti che sono pure funzioni dele proprietà. Questi componenti non devono trattenere stato interno, non hanno istanze di supporto, e non posseggono metodi di ciclo di vita. Sono pure trasformate funzionali del loro input, con zero codice boilerplate.
259 -
260 -> NOTA:
261 ->
262 -> Poiché le funzioni prive di stato non hanno un'istanza di supporto, non puoi assegnare un ref a un componente creato con una funzione priva di stato. Normalmente questo non è un problema, poiché le funzioni prive di stato non forniscono un'API imperativa. Senza un'API imperativa, non puoi comunque fare molto con un'istanza. Tuttavia, se un utente desidera trovare il nodo DOM di un componente creato con una funzione priva di stato, occorre avvolgere il componente in un altro componente dotato di stato (ad es. un componente classe ES6) e assegnare il ref al componente dotato di stato.
263 -
264 -In un mondo ideale, la maggior parte dei tuoi componenti sarebbero funzioni prive di stato poiché questi componenti privi di stato seguono un percorso più rapido all'interno del core di React. Questo è un pattern raccomandato, quando possibile.
docs/docs/05-reusable-components.ja-JP.md deleted
-231
@@ -1,231 +0,0 @@
1 ----
2 -id: reusable-components
3 -title: 再利用可能なコンポーネント
4 -permalink: docs/reusable-components-ja-JP.html
5 -prev: multiple-components-ja-JP.html
6 -next: transferring-props-ja-JP.html
7 ----
8 -
9 -インターフェースをデザインするとき、明確に定義されたインターフェースでは共通のデザイン要素(ボタン、フォームフィールド、レイアウトコンポーネントなど)を再利用可能なコンポーネントにブレークダウンします。そのような方法をとることで、次にUIを作成する必要があるときに、書くコードが少なくて済みます。これは、開発速度を上げ、バグを減らし、導線を減らすことを意味します。
10 -
11 -## Propのバリデーション
12 -
13 -アプリが大きくなっていくにつれて、コンポーネントが正しく使われていることを保証することが役に立つようになります。`propTypes` を指定することでそういったことができるようになります。`React.PropTypes` はあなたが受け取ったデータが正しいことを認識するのに使われるバリデータを出力します。不正な値がpropに渡されたときは、警告がJavaScriptコンソールに表示されます。パフォーマンスの点で、 `propTypes` は開発モードでのみチェックされることに注意してください。異なるバリデータが提供された際の例を表すドキュメントは以下の通りです。
14 -
15 -```javascript
16 -React.createClass({
17 - propTypes: {
18 - // propがJSのプリミティブ型であると宣言できます。
19 - // デフォルトで、以下は全てオプションです。
20 - optionalArray: React.PropTypes.array,
21 - optionalBool: React.PropTypes.bool,
22 - optionalFunc: React.PropTypes.func,
23 - optionalNumber: React.PropTypes.number,
24 - optionalObject: React.PropTypes.object,
25 - optionalString: React.PropTypes.string,
26 - optionalSymbol: React.PropTypes.symbol,
27 -
28 - // 何でもレンダリングできます。number、string、要素やそれらを含む配列など。
29 - optionalNode: React.PropTypes.node,
30 -
31 - // Reactの要素。
32 - optionalElement: React.PropTypes.element,
33 -
34 - // propがクラスのインスタンスであるとの宣言もできます。
35 - // JSのinstanceofオペレータを使用しています。
36 - optionalMessage: React.PropTypes.instanceOf(Message),
37 -
38 - // 以下をenumとして扱うことで、propがある値であると保証できます。
39 - optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),
40 -
41 - // たくさんの型のうちのひとつになりうるオブジェクト
42 - optionalUnion: React.PropTypes.oneOfType([
43 - React.PropTypes.string,
44 - React.PropTypes.number,
45 - React.PropTypes.instanceOf(Message)
46 - ]),
47 -
48 - // ある型の配列
49 - optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
50 -
51 - // プロパティの値がある型のものであるオブジェクト
52 - optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
53 -
54 - // 特定の形をとるオブジェクト
55 - optionalObjectWithShape: React.PropTypes.shape({
56 - color: React.PropTypes.string,
57 - fontSize: React.PropTypes.number
58 - }),
59 -
60 - // `isRequired` は上記のどの値にも繋げることができますが、
61 - // propが提供されなかったときには警告が出ることに注意してください。
62 - requiredFunc: React.PropTypes.func.isRequired,
63 -
64 - // どのようなデータ型の値でも大丈夫です
65 - requiredAny: React.PropTypes.any.isRequired,
66 -
67 - // バリデータをカスタマイズすることもできます。
68 - // 以下はバリデーションが落ちた時にはエラーを返します。
69 - // `oneOfType` の中で動かなくなるので、 `console.warn` や throw はしないでください。
70 - customProp: function(props, propName, componentName) {
71 - if (!/matchme/.test(props[propName])) {
72 - return new Error('Validation failed!');
73 - }
74 - }
75 - },
76 - /* ... */
77 -});
78 -```
79 -
80 -
81 -## デフォルトのPropの値
82 -
83 -Reactは以下のように、とても宣言的な方法で `props` のデフォルト値を定義できます。
84 -
85 -```javascript
86 -var ComponentWithDefaultProps = React.createClass({
87 - getDefaultProps: function() {
88 - return {
89 - value: 'default value'
90 - };
91 - }
92 - /* ... */
93 -});
94 -```
95 -
96 -`getDefaultProps()` の結果は `this.props.value` が親コンポーネントで制限されなかった場合に値を保証するためにキャッシュされて使われます。これによって、自分自身でハンドルするための壊れやすいコードを何度も書くことなくpropsをただ安全に使うことができます。
97 -
98 -## Propsの移動: ショートカット
99 -
100 -Reactのコンポーネントに共通しているのは、単純な方法で基本的なHTML要素を拡張していることです。よく、
101 -コンポーネントに渡されるHTML属性を、型付けを守るために、基本的なHTML要素にコピーしたいと考える人もいます。このようなことを行うために、JSXの _拡張された_ シンタックスを使うことができます。
102 -
103 -```javascript
104 -var CheckLink = React.createClass({
105 - render: function() {
106 - // 以下はCheckLinkに渡されたどんなpropsをとることができ、<a>タグにコピーすることもできます。
107 - return <a {...this.props}>{'√ '}{this.props.children}</a>;
108 - }
109 -});
110 -
111 -ReactDOM.render(
112 - <CheckLink href="/checked.html">
113 - Click here!
114 - </CheckLink>,
115 - document.getElementById('example')
116 -);
117 -```
118 -
119 -## 単一の子要素
120 -
121 -`React.PropTypes.element` を使って、childrenとしてコンポーネントにただ一つの子要素が渡されるよう制限できます。
122 -
123 -```javascript
124 -var MyComponent = React.createClass({
125 - propTypes: {
126 - children: React.PropTypes.element.isRequired
127 - },
128 -
129 - render: function() {
130 - return (
131 - <div>
132 - {this.props.children} // これは1つの要素でなくてはなりません。さもなければエラーがthrowされます。
133 - </div>
134 - );
135 - }
136 -
137 -});
138 -```
139 -
140 -## ミックスイン
141 -
142 -コンポーネントはReactでコードを再利用する最良の方法ですが、全く異なったコンポーネントが共通の機能性を共有することもあります。それらは[横断的関心事](https://en.wikipedia.org/wiki/Cross-cutting_concern)と呼ばれることもあります。Reactはこの問題を解決するために、 `mixins` を提供しています。
143 -
144 -共通のユースケースとしては、時間の間隔によって、コンポーネントにそれ自身をアップデートさせたい場合があります。 `setInterval()` を使うのは簡単ですが、メモリをセーブするためにもう必要でなくなった場合にはインターバルをキャンセルすることが重要です。Reactは[ライフサイクルメソッド](/react/docs/working-with-the-browser.html#component-lifecycle)を提供しており、コンポーネントが作成されようとしたり削除されようとした時にそれを検知することができます。コンポーネントが削除されたときに自動的にクリーンアップしてくれる、簡単な `setInterval()` 関数を提供する以下のようなメソッドを使って単純なミックスインを作成してみましょう。
145 -
146 -```javascript
147 -var SetIntervalMixin = {
148 - componentWillMount: function() {
149 - this.intervals = [];
150 - },
151 - setInterval: function() {
152 - this.intervals.push(setInterval.apply(null, arguments));
153 - },
154 - componentWillUnmount: function() {
155 - this.intervals.forEach(clearInterval);
156 - }
157 -};
158 -
159 -var TickTock = React.createClass({
160 - mixins: [SetIntervalMixin], // ミックスインを使う
161 - getInitialState: function() {
162 - return {seconds: 0};
163 - },
164 - componentDidMount: function() {
165 - this.setInterval(this.tick, 1000); // ミックスインのメソッドを呼ぶ
166 - },
167 - tick: function() {
168 - this.setState({seconds: this.state.seconds + 1});
169 - },
170 - render: function() {
171 - return (
172 - <p>
173 - React has been running for {this.state.seconds} seconds.
174 - </p>
175 - );
176 - }
177 -});
178 -
179 -ReactDOM.render(
180 - <TickTock />,
181 - document.getElementById('example')
182 -);
183 -```
184 -
185 -ミックスインの素晴らしい特徴はコンポーネントが複数のミックスインを使っていて、いくつかのミックスインが同じライフサイクルメソッドを定義している場合(すなわち、コンポーネントが削除された際に幾つかのミックスインがクリーンアップを行いたい場合)に、すべてのライフサイクルメソッドが呼ばれることを保証することです。ミックスインで定義されたメソッドは、ミックスインが並んでいる順番に走り、コンポーネントのメソッド呼び出しで呼ばれます。
186 -
187 -## ES6のクラス
188 -
189 -ReactのクラスをただのJavaScriptのクラスとして定義することもできます。例えば、ES6 のクラスシンタックスを使うと、以下のようになります。
190 -
191 -```javascript
192 -class HelloMessage extends React.Component {
193 - render() {
194 - return <div>Hello {this.props.name}</div>;
195 - }
196 -}
197 -ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
198 -```
199 -
200 -APIは `getInitialState` という例外を除き、 `React.createClass` と同じです。APIが異なっている `getInitialState` メソッドを提供する代わりに、コンストラクタの中に `state` プロパティをセットします。
201 -
202 -他の違いは、 `propTypes` と `defaultProps` はクラスのボディに定義される代わりにコンストラクタにプロパティとして定義されます。
203 -
204 -```javascript
205 -export class Counter extends React.Component {
206 - constructor(props) {
207 - super(props);
208 - this.state = {count: props.initialCount};
209 - }
210 - tick() {
211 - this.setState({count: this.state.count + 1});
212 - }
213 - render() {
214 - return (
215 - <div onClick={this.tick.bind(this)}>
216 - Clicks: {this.state.count}
217 - </div>
218 - );
219 - }
220 -}
221 -Counter.propTypes = { initialCount: React.PropTypes.number };
222 -Counter.defaultProps = { initialCount: 0 };
223 -```
224 -
225 -### オートバインディングしません
226 -
227 -メソッドは標準のES6のクラスと同じ仕様です。それは、 `this` をインスタンスに自動的にバインドしないことを意味します。明確に `.bind(this)` を使うか [アロー関数](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/) `=>` を使ってください。
228 -
229 -### ミックスインはありません
230 -
231 -不幸なことに、ES6はミックスインのサポートを行いません。それゆえ、ReactをES6のクラスと一緒に使う際にはミックスインのサポートはありません。代わりに、ミックスインに頼ることなくそれらのユースケースをサポートするのが簡単になるよう努力しています。
docs/docs/05-reusable-components.ko-KR.md deleted
-256
@@ -1,256 +0,0 @@
1 ----
2 -id: reusable-components-ko-KR
3 -title: 재사용가능한 컴포넌트
4 -permalink: docs/reusable-components-ko-KR.html
5 -prev: multiple-components-ko-KR.html
6 -next: transferring-props-ko-KR.html
7 ----
8 -
9 -인터페이스를 설계할 때, 공통적으로 사용되는 디자인 요소들(버튼, 폼 필드, 레이아웃 컴포넌트 등.)을 잘 정의된 인터페이스의 재사용 가능한 컴포넌트로 분해합니다. 이런 방법으로 다음에 UI를 구축할 때에는 훨씬 적은 코드로 만들 수 있습니다. 이 말은 더 빠른 개발 시간, 더 적은 버그, 더 적은 용량으로 할 수 있다는 뜻이죠.
10 -
11 -## Prop 검증
12 -
13 -앱의 규모가 커지면 컴포넌트들이 바르게 사용되었는지 확인하는게 도움이 됩니다. 확인은 `propTypes`를 명시해서 할 수 있습니다. `React.PropTypes`는 받은 데이터가 적절한지(valid) 확인하는데 사용할 수 있는 다양한 검증자(validator)를 제공합니다. prop에 부적절한 값을 명시한다면 JavaScript 콘솔에 경고가 보일 것입니다. 성능상의 문제로 `propTypes`는 개발 모드에서만 검사됩니다. 다음은 제공되는 검증자를 설명하는 예제입니다.
14 -
15 -```javascript
16 -React.createClass({
17 - propTypes: {
18 - // 특정 JavaScript 프리미티브 타입에 대한 prop을 명시할 수 있습니다.
19 - // 기본적으로 이것들은 모두 선택적입니다.
20 - optionalArray: React.PropTypes.array,
21 - optionalBool: React.PropTypes.bool,
22 - optionalFunc: React.PropTypes.func,
23 - optionalNumber: React.PropTypes.number,
24 - optionalObject: React.PropTypes.object,
25 - optionalString: React.PropTypes.string,
26 - optionalSymbol: React.PropTypes.symbol,
27 -
28 - // 렌더링될 수 있는 모든 것: 숫자, 문자열, 요소
29 - // 이것들을 포함하는 배열(이나 프래그먼트)
30 - optionalNode: React.PropTypes.node,
31 -
32 - // React 엘리먼트
33 - optionalElement: React.PropTypes.element,
34 -
35 - // 클래스의 인스턴스 또한 prop으로 명시할 수 있습니다. JavaScript의 instanceof
36 - // 연산자를 사용합니다.
37 - optionalMessage: React.PropTypes.instanceOf(Message),
38 -
39 - // 열거형처럼 특정 값들로만 prop을 제한해서 사용할 수 있습니다.
40 - optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),
41 -
42 - // 많은 타입들 중 하나로 사용할 수 있는 객체가 될 수도 있습니다.
43 - optionalUnion: React.PropTypes.oneOfType([
44 - React.PropTypes.string,
45 - React.PropTypes.number,
46 - React.PropTypes.instanceOf(Message)
47 - ]),
48 -
49 - // 특정 타입의 배열
50 - optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
51 -
52 - // 특정 타입의 속성값을 갖는 객체
53 - optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
54 -
55 - // 특정한 형태(shape)의 객체
56 - optionalObjectWithShape: React.PropTypes.shape({
57 - color: React.PropTypes.string,
58 - fontSize: React.PropTypes.number
59 - }),
60 -
61 - // 위에 언급된 것들을 `isRequired`로 연결해서 prop이 제공되지 않을 때 경고를
62 - // 띄우도록 할 수도 있습니다.
63 - requiredFunc: React.PropTypes.func.isRequired,
64 -
65 - // 어떤 데이터 타입도 가능
66 - requiredAny: React.PropTypes.any.isRequired,
67 -
68 - // 물론 사용자 정의 검증자도 지정할 수 있습니다. 이는 검증이 실패했을 때
69 - // Error 객체를 리턴해야합니다. `console.warn`을 이나 throw를 하면 안됩니다.
70 - // 그렇게하면 `oneOfType` 안에서 작동하지 않습니다.
71 - customProp: function(props, propName, componentName) {
72 - if (!/matchme/.test(props[propName])) {
73 - return new Error('Validation failed!');
74 - }
75 - }
76 - },
77 - /* ... */
78 -});
79 -```
80 -
81 -## 기본 Prop 값
82 -
83 -React는 매우 선언적(declarative)인 방법으로 `props`의 기본값을 정의할 수 있게 해줍니다.
84 -
85 -```javascript
86 -var ComponentWithDefaultProps = React.createClass({
87 - getDefaultProps: function() {
88 - return {
89 - value: 'default value'
90 - };
91 - }
92 - /* ... */
93 -});
94 -```
95 -
96 -`getDefaultProps()`의 결과값은 캐시가 되며, 부모 컴포넌트에서 명시되지 않았을 때 `this.props.value`가 값을 가질 수 있도록 해주는데 사용됩니다.`getDefaultProps()`를 사용하면 반복적이고 깨지기 쉬운 코드를 짤 필요없이 그냥 안전하게 prop을 사용할 수 있습니다.
97 -
98 -## Prop 전달하기: 단축
99 -
100 -React 컴포넌트의 흔히 그냥 기본 HTML 엘리먼트를 확장해서 씁니다. 타이핑을 아끼기 위해 기저의 HTML 엘리먼트에 HTML 속성들을 단순히 복사하는 컴포넌트가 필요할 수도 있습니다. JSX의 _spread_ 문법을 사용하면 이렇게 할 수 있습니다.
101 -
102 -```javascript
103 -var CheckLink = React.createClass({
104 - render: function() {
105 - // 모든 prop을 받아서 CheckLink에 넘기고 <a>에 복사합니다.
106 - return <a {...this.props}>{'√ '}{this.props.children}</a>;
107 - }
108 -});
109 -
110 -ReactDOM.render(
111 - <CheckLink href="/checked.html">
112 - Click here!
113 - </CheckLink>,
114 - document.getElementById('example')
115 -);
116 -```
117 -
118 -## 단일 자식
119 -
120 -`React.PropTypes.element`을 통해 컴포넌트에 한 자식만 보내도록 명시할 수 있습니다.
121 -
122 -```javascript
123 -var MyComponent = React.createClass({
124 - propTypes: {
125 - children: React.PropTypes.element.isRequired
126 - },
127 -
128 - render: function() {
129 - return (
130 - <div>
131 - {this.props.children} // 정확히 한 엘리먼트여야만 하며, 아니면 에러가 발생합니다.
132 - </div>
133 - );
134 - }
135 -
136 -});
137 -```
138 -
139 -## 믹스인
140 -
141 -컴포넌트는 React에서 코드를 재사용할 수 있는 최고의 방법이지만, 가끔 아주 다른 컴포넌트에서 공통 기능이 필요한 때도 있습니다. 이런 상황을 [공통된 관심사(cross-cutting concerns)](https://en.wikipedia.org/wiki/Cross-cutting_concern)라 부르며, React에서는 `mixins`으로 이 문제를 해결합니다.
142 -
143 -예를 들어, 컴포넌트가 주기적으로 업데이트되길 원할 경우가 있습니다. `setInterval()`을 사용하면 쉽지만, 필요 없어지면 메모리를 아끼기 위해 주기를 꼭 취소해야 합니다. React는 컴포넌트가 막 생성거나 없어질 때를 [생명주기 메소드](/react/docs/working-with-the-browser-ko-KR.html#컴포넌트-생명주기)를 통해 알려줍니다. 이런 메소드들을 사용해서 컴포넌트가 사라질 때 자동으로 정리해주는 `setInterval()`를 제공해주는 간단한 믹스인을 만들어보겠습니다.
144 -
145 -```javascript
146 -var SetIntervalMixin = {
147 - componentWillMount: function() {
148 - this.intervals = [];
149 - },
150 - setInterval: function() {
151 - this.intervals.push(setInterval.apply(null, arguments));
152 - },
153 - componentWillUnmount: function() {
154 - this.intervals.forEach(clearInterval);
155 - }
156 -};
157 -
158 -var TickTock = React.createClass({
159 - mixins: [SetIntervalMixin], // 믹스인 사용
160 - getInitialState: function() {
161 - return {seconds: 0};
162 - },
163 - componentDidMount: function() {
164 - this.setInterval(this.tick, 1000); // 믹스인에 있는 메소드를 호출
165 - },
166 - tick: function() {
167 - this.setState({seconds: this.state.seconds + 1});
168 - },
169 - render: function() {
170 - return (
171 - <p>
172 - React has been running for {this.state.seconds} seconds.
173 - </p>
174 - );
175 - }
176 -});
177 -
178 -ReactDOM.render(
179 - <TickTock />,
180 - document.getElementById('example')
181 -);
182 -```
183 -
184 -믹스인의 괜찮은 점은 컴포넌트가 여러 믹스인을 사용하고 여러 믹스인에서 같은 생명주기 메소드를 사용할 때(예를 들어, 여러 믹스인에서 컴포넌트가 사라질 때 뭔가 정리하려 한다면) 모든 생명주기 메소드들의 실행은 보장됩니다. 믹스인에 정의된 메소드은 컴포넌트의 메소드가 호출됨에 따라 믹스인이 나열된 순서대로 실행됩니다.
185 -
186 -## ES6 클래스
187 -
188 -React 클래스를 일반적인 JavaScript 클래스로 선언할 수도 있습니다. 다음의 예제는 ES6 클래스 문법을 사용합니다:
189 -
190 -```javascript
191 -class HelloMessage extends React.Component {
192 - render() {
193 - return <div>Hello {this.props.name}</div>;
194 - }
195 -}
196 -ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
197 -```
198 -
199 -API는 `getInitialState`를 제외하고 `React.createClass`와 유사합니다. 별도의 `getInitialState` 메소드 대신에, 필요한 `state` 프로퍼티를 생성자에서 설정할 수 있습니다.
200 -
201 -또다른 차이점은 `propTypes`와 `defaultProps`가 클래스의 내부가 아니라 생성자의 프로퍼티로 정의되어 있다는 것입니다.
202 -
203 -```javascript
204 -export class Counter extends React.Component {
205 - constructor(props) {
206 - super(props);
207 - this.state = {count: props.initialCount};
208 - }
209 - tick() {
210 - this.setState({count: this.state.count + 1});
211 - }
212 - render() {
213 - return (
214 - <div onClick={this.tick.bind(this)}>
215 - Clicks: {this.state.count}
216 - </div>
217 - );
218 - }
219 -}
220 -Counter.propTypes = { initialCount: React.PropTypes.number };
221 -Counter.defaultProps = { initialCount: 0 };
222 -```
223 -
224 -### 자동 바인딩 안됨
225 -
226 -메소드는 일반 ES6 클래스와 동일한 시멘틱을 따릅니다. `this`를 인스턴스에 자동으로 바인딩하지 않는다는 이야기입니다. 명시적으로 `.bind(this)`나 [화살표 함수(arrow function)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) `=>`를 사용하세요.
227 -
228 -### 믹스인 안됨
229 -
230 -불행하게도 ES6는 믹스인에 대한 지원이 없이 출시되었기 때문에, React에서 ES6 클래스를 사용한다면 믹스인을 사용할 방법이 없습니다. 대신, 우리는 믹스인에 의존하지 않고도 동작하도록 만들기 위해 열심히 노력하고 있습니다.
231 -
232 -## 상태를 가지지 않는 함수
233 -
234 -React 클래스를 일반 JavaScript 함수로 작성할 수도 있습니다. 상태를 가지지 않는 함수 문법을 사용하는 예제입니다.
235 -
236 -```javascript
237 -function HelloMessage(props) {
238 - return <div>Hello {props.name}</div>;
239 -}
240 -ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
241 -```
242 -
243 -아니면 ES6의 화살표 문법을 사용할 수 있습니다.
244 -
245 -```javascript
246 -const HelloMessage = (props) => <div>Hello {props.name}</div>;
247 -ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
248 -```
249 -
250 -이 단순화된 컴포넌트 API는 prop의 순수 함수인 컴포넌트를 나타냅니다. 이 컴포넌트는 내부 상태가 없어야 하고, 내부 인스턴스가 없어야 하고, 컴포넌트 생명주기 메소드가 없어야 합니다. 아무런 준비 과정없이 입력에 대한 순수한 기능적 변환이어야 합니다.
251 -
252 -> 주의:
253 ->
254 -> 상태를 가지지 않는 함수는 내부 인스턴스가 없기 때문에, ref를 상태를 가지지않는 함수에 넣을 수 없습니다. 상태를 가지지 않는 함수는 명령형(imperative) API를 제공하지 않기 때문에 일반적으로 이것은 문제가 되지 않습니다. 명령형 API없이 인스턴스에 할 수 있는 것이 많지 않기도 하죠. 하지만 상태를 가지지 않는 컴포넌트의 DOM 노드를 검색하길 원한다면, 반드시 상태 기반 컴포넌트(예. ES6 클래스 컴포넌트)로 컴포넌트를 감싸고 상태 기반 래퍼 컴포넌트에 ref를 붙여야 합니다.
255 -
256 -이상적으로는, 대부분의 컴포넌트는 상태를 가지지 않는 함수여야 합니다. 왜냐 하면 이런 상태를 가지지 않는 컴포넌트는 React 코어 안에서 더 빠른 코드 경로를 거치기 때문입니다. 이는 가능한 한 추천하는 패턴입니다.
docs/docs/05-reusable-components.md deleted
-462
@@ -1,462 +0,0 @@
1 ----
2 -id: reusable-components
3 -title: Reusable Components
4 -permalink: docs/reusable-components.html
5 -prev: multiple-components.html
6 -next: transferring-props.html
7 ----
8 -
9 -When designing interfaces, break down the common design elements (buttons, form fields, layout components, etc.) into reusable components with well-defined interfaces. That way, the next time you need to build some UI, you can write much less code. This means faster development time, fewer bugs, and fewer bytes down the wire.
10 -
11 -## Prop Validation
12 -
13 -As your app grows it's helpful to ensure that your components are used correctly. We do this by allowing you to specify `propTypes`. `React.PropTypes` exports a range of validators that can be used to make sure the data you receive is valid. When an invalid value is provided for a prop, a warning will be shown in the JavaScript console. Note that for performance reasons `propTypes` is only checked in development mode.
14 -
15 -You can assign a special property to a component to declare its `propTypes`:
16 -
17 -```javascript
18 -class Greeting extends React.Component {
19 - render() {
20 - return (
21 - <h1>Hello, {this.props.name}</h1>
22 - );
23 - }
24 -}
25 -
26 -Greeting.propTypes = {
27 - name: React.PropTypes.string
28 -};
29 -```
30 -
31 -Here is an example documenting the different validators provided:
32 -
33 -```javascript
34 -MyComponent.propTypes = {
35 - // You can declare that a prop is a specific JS primitive. By default, these
36 - // are all optional.
37 - optionalArray: React.PropTypes.array,
38 - optionalBool: React.PropTypes.bool,
39 - optionalFunc: React.PropTypes.func,
40 - optionalNumber: React.PropTypes.number,
41 - optionalObject: React.PropTypes.object,
42 - optionalString: React.PropTypes.string,
43 - optionalSymbol: React.PropTypes.symbol,
44 -
45 - // Anything that can be rendered: numbers, strings, elements or an array
46 - // (or fragment) containing these types.
47 - optionalNode: React.PropTypes.node,
48 -
49 - // A React element.
50 - optionalElement: React.PropTypes.element,
51 -
52 - // You can also declare that a prop is an instance of a class. This uses
53 - // JS's instanceof operator.
54 - optionalMessage: React.PropTypes.instanceOf(Message),
55 -
56 - // You can ensure that your prop is limited to specific values by treating
57 - // it as an enum.
58 - optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),
59 -
60 - // An object that could be one of many types
61 - optionalUnion: React.PropTypes.oneOfType([
62 - React.PropTypes.string,
63 - React.PropTypes.number,
64 - React.PropTypes.instanceOf(Message)
65 - ]),
66 -
67 - // An array of a certain type
68 - optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
69 -
70 - // An object with property values of a certain type
71 - optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
72 -
73 - // An object taking on a particular shape
74 - optionalObjectWithShape: React.PropTypes.shape({
75 - color: React.PropTypes.string,
76 - fontSize: React.PropTypes.number
77 - }),
78 -
79 - // You can chain any of the above with `isRequired` to make sure a warning
80 - // is shown if the prop isn't provided.
81 - requiredFunc: React.PropTypes.func.isRequired,
82 -
83 - // A value of any data type
84 - requiredAny: React.PropTypes.any.isRequired,
85 -
86 - // You can also specify a custom validator. It should return an Error
87 - // object if the validation fails. Don't `console.warn` or throw, as this
88 - // won't work inside `oneOfType`.
89 - customProp: function(props, propName, componentName) {
90 - if (!/matchme/.test(props[propName])) {
91 - return new Error(
92 - 'Invalid prop `' + propName + '` supplied to' +
93 - ' `' + componentName + '`. Validation failed.'
94 - );
95 - }
96 - },
97 -
98 - // You can also supply a custom validator to `arrayOf` and `objectOf`.
99 - // It should return an Error object if the validation fails. The validator
100 - // will be called for each key in the array or object. The first two
101 - // arguments of the validator are the array or object itself, and the
102 - // current item's key.
103 - customArrayProp: React.PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
104 - if (!/matchme/.test(propValue[key])) {
105 - return new Error(
106 - 'Invalid prop `' + propFullName + '` supplied to' +
107 - ' `' + componentName + '`. Validation failed.'
108 - );
109 - }
110 - })
111 -};
112 -```
113 -
114 -### Single Child
115 -
116 -With `React.PropTypes.element` you can specify that only a single child can be passed to a component as children.
117 -
118 -```javascript
119 -class MyComponent extends React.Component {
120 - render() {
121 - // This must be exactly one element or it will warn.
122 - var children = this.props.children;
123 - return (
124 - <div>
125 - {children}
126 - </div>
127 - );
128 - }
129 -}
130 -
131 -MyComponent.propTypes = {
132 - children: React.PropTypes.element.isRequired
133 -};
134 -```
135 -
136 -## Default Prop Values
137 -
138 -React lets you define default values for your `props` in a very declarative way:
139 -
140 -```javascript
141 -class Greeting extends React.Component {
142 - render() {
143 - return (
144 - <h1>Hello, {this.props.name}</h1>
145 - );
146 - }
147 -}
148 -
149 -// Specifies the default values for props:
150 -Greeting.defaultProps = {
151 - name: 'Stranger'
152 -};
153 -
154 -// Renders "Hello, Stranger":
155 -ReactDOM.render(
156 - <Greeting />,
157 - document.getElementById('example')
158 -);
159 -```
160 -
161 -The `defaultProps` will be used to ensure that `this.props.name` will have a value if it was not specified by the parent component. This allows you to safely just use your props without having to write repetitive and fragile code to handle that yourself.
162 -
163 -## Transferring Props: A Shortcut
164 -
165 -A common type of React component is one that extends a basic HTML element in a simple way. Often you'll want to copy any HTML attributes passed to your component to the underlying HTML element. To save typing, you can use the JSX _spread_ syntax to achieve this:
166 -
167 -```javascript
168 -class CheckLink extends React.Component {
169 - render() {
170 - // This takes any props passed to CheckLink and copies them to <a>
171 - return (
172 - <a {...this.props}>{'√ '}{this.props.children}</a>
173 - );
174 - }
175 -}
176 -
177 -ReactDOM.render(
178 - <CheckLink href="/checked.html">
179 - Click here!
180 - </CheckLink>,
181 - document.getElementById('example')
182 -);
183 -```
184 -
185 -## Stateless Functions
186 -
187 -If a component doesn't use local state or lifecycle hooks, you can define it as a function instead of a class:
188 -
189 -```javascript
190 -function Greeting(props) {
191 - return <h1>Hello, {props.name}</h1>;
192 -}
193 -
194 -ReactDOM.render(
195 - <Greeting name="Sebastian" />,
196 - document.getElementById('example')
197 -);
198 -```
199 -
200 -Or using the new ES6 arrow syntax:
201 -
202 -```javascript
203 -const Greeting = (props) => (
204 - <h1>Hello, {props.name}</h1>
205 -);
206 -
207 -ReactDOM.render(
208 - <Greeting name="Sebastian" />,
209 - document.getElementById('example')
210 -);
211 -```
212 -
213 -This simplified component API is intended for components that are pure functions of their props. These components must not retain internal state, do not have backing instances, and do not have the component lifecycle methods. They are pure functional transforms of their input, with zero boilerplate.
214 -
215 -However, you may still specify `.propTypes` and `.defaultProps` by setting them as properties on the function, just as you would set them on an ES6 class:
216 -
217 -```javascript
218 -function Greeting(props) {
219 - return (
220 - <h1>Hello, {props.name}</h1>
221 - );
222 -}
223 -
224 -Greeting.propTypes = {
225 - name: React.PropTypes.string
226 -};
227 -
228 -Greeting.defaultProps = {
229 - name: 'John Doe'
230 -};
231 -
232 -ReactDOM.render(
233 - <Greeting name="Mădălina"/>,
234 - document.getElementById('example')
235 -);
236 -```
237 -
238 ->**Note:**
239 ->
240 -> Because stateless functions don't have a backing instance, you can't attach a ref to a stateless function component. Normally this isn't an issue, since stateless functions do not provide an imperative API. Without an imperative API, there isn't much you could do with an instance anyway. However, if a user wants to find the DOM node of a stateless function component, they must wrap the component in a stateful component (eg. ES6 class component) and attach the ref to the stateful wrapper component.
241 -
242 -In an ideal world, many of your components would be stateless functions. In the future we plan to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations.
243 -
244 -When you don't need local state or lifecycle hooks in a component, we recommend declaring it with a function. Otherwise, we recommend to use the ES6 class syntax.
245 -
246 -## ES6 Classes and React.createClass()
247 -
248 -Normally you would define a React component as a plain JavaScript class:
249 -
250 -```javascript
251 -class Greeting extends React.Component {
252 - render() {
253 - return <h1>Hello, {this.props.name}</h1>;
254 - }
255 -}
256 -```
257 -
258 -If you don't use ES6 yet, you may use [`React.createClass`](/react/docs/top-level-api.html#react.createclass) helper instead:
259 -
260 -
261 -```javascript
262 -var Greeting = React.createClass({
263 - render: function() {
264 - return <h1>Hello, {this.props.name}</h1>;
265 - }
266 -});
267 -```
268 -
269 -The API of ES6 classes is similar to [`React.createClass`](/react/docs/top-level-api.html#react.createclass) with a few exceptions.
270 -
271 -### Declaring Prop Types and Default Props
272 -
273 -With functions and ES6 classes, `propTypes` and `defaultProps` are defined as properties on the components themselves:
274 -
275 -```javascript
276 -class Greeting extends React.Component {
277 - // ...
278 -}
279 -
280 -Greeting.propTypes = {
281 - name: React.PropTypes.string
282 -};
283 -
284 -Greeting.defaultProps = {
285 - name: 'Mary'
286 -};
287 -```
288 -
289 -With `React.createClass()`, you need to define `propTypes` as a property on the passed object, and `getDefaultProps()` as a function on it:
290 -
291 -```javascript
292 -var Greeting = React.createClass({
293 - propTypes: {
294 - name: React.PropTypes.string
295 - },
296 -
297 - getDefaultProps: function() {
298 - return {
299 - name: 'Mary'
300 - };
301 - },
302 -
303 - // ...
304 -
305 -});
306 -```
307 -
308 -### Setting the Initial State
309 -
310 -In ES6 classes, you can define the initial state by assigning `this.state` in the constructor:
311 -
312 -```javascript
313 -class Counter extends React.Component {
314 - constructor(props) {
315 - super(props);
316 - this.state = {count: props.initialCount};
317 - }
318 - // ...
319 -}
320 -```
321 -
322 -With `React.createClass()`, you have to provide a separate `getInitialState` method that returns the initial state:
323 -
324 -```javascript
325 -var Counter = React.createClass({
326 - getInitialState: function() {
327 - return {count: this.props.initialCount};
328 - },
329 - // ...
330 -});
331 -```
332 -
333 -### Autobinding
334 -
335 -In React components declared as ES6 classes, methods follow the same semantics as regular ES6 classes. This means that they don't automatically bind `this` to the instance. You'll have to explicitly use `.bind(this)` in the constructor:
336 -
337 -```javascript
338 -class SayHello extends React.Component {
339 - constructor(props) {
340 - super(props);
341 - // This line is important!
342 - this.handleClick = this.handleClick.bind(this);
343 - }
344 -
345 - handleClick() {
346 - alert('Hello!');
347 - }
348 -
349 - render() {
350 - // Because `this.handleClick` is bound, we can use it as an event handler.
351 - return (
352 - <button onClick={this.handleClick}>
353 - Say hello
354 - </button>
355 - );
356 - }
357 -}
358 -```
359 -
360 -With `React.createClass()`, this is not necessary because it binds all methods:
361 -
362 -```javascript
363 -var SayHello = React.createClass({
364 - handleClick: function() {
365 - alert('Hello!');
366 - },
367 -
368 - render: function() {
369 - return (
370 - <button onClick={this.handleClick}>
371 - Say hello
372 - </button>
373 - );
374 - }
375 -});
376 -```
377 -
378 -This means writing ES6 classes comes with a little more boilerplate code for event handlers, but the upside is slightly better performance in large applications.
379 -
380 -If the boilerplate code is too unattractive to you, you may enable the **experimental** [Class Properties](https://babeljs.io/docs/plugins/transform-class-properties/) syntax proposal with Babel:
381 -
382 -
383 -```javascript
384 -class SayHello extends React.Component {
385 - // WARNING: this syntax is experimental!
386 - // Using an arrow here binds the method:
387 - handleClick = () => {
388 - alert('Hello!');
389 - }
390 -
391 - render() {
392 - return (
393 - <button onClick={this.handleClick}>
394 - Say hello
395 - </button>
396 - );
397 - }
398 -}
399 -```
400 -
401 -Please note that the syntax above is **experimental** and the syntax may change, or the proposal might not make it into the language.
402 -
403 -If you'd rather play it safe, you have a few options:
404 -
405 -* Bind methods in the constructor.
406 -* Use arrow functions, e.g. `onClick={(e) => this.handleClick(e)})`.
407 -* Keep using `React.createClass()`.
408 -
409 -### Mixins
410 -
411 ->**Note:**
412 ->
413 ->ES6 launched without any mixin support. Therefore, there is no support for mixins when you use React with ES6 classes.
414 ->
415 ->**We also found numerous issues in codebases using mixins, [and don't recommend using them in the new code](/react/blog/2016/07/13/mixins-considered-harmful.html).**
416 ->
417 ->This section exists only for the reference.
418 -
419 -Sometimes very different components may share some common functionality. These are sometimes called [cross-cutting concerns](https://en.wikipedia.org/wiki/Cross-cutting_concern). [`React.createClass`](/react/docs/top-level-api.html#react.createclass) lets you use a legacy `mixins` system for that.
420 -
421 -One common use case is a component wanting to update itself on a time interval. It's easy to use `setInterval()`, but it's important to cancel your interval when you don't need it anymore to save memory. React provides [lifecycle methods](/react/docs/working-with-the-browser.html#component-lifecycle) that let you know when a component is about to be created or destroyed. Let's create a simple mixin that uses these methods to provide an easy `setInterval()` function that will automatically get cleaned up when your component is destroyed.
422 -
423 -```javascript
424 -var SetIntervalMixin = {
425 - componentWillMount: function() {
426 - this.intervals = [];
427 - },
428 - setInterval: function() {
429 - this.intervals.push(setInterval.apply(null, arguments));
430 - },
431 - componentWillUnmount: function() {
432 - this.intervals.forEach(clearInterval);
433 - }
434 -};
435 -
436 -var TickTock = React.createClass({
437 - mixins: [SetIntervalMixin], // Use the mixin
438 - getInitialState: function() {
439 - return {seconds: 0};
440 - },
441 - componentDidMount: function() {
442 - this.setInterval(this.tick, 1000); // Call a method on the mixin
443 - },
444 - tick: function() {
445 - this.setState({seconds: this.state.seconds + 1});
446 - },
447 - render: function() {
448 - return (
449 - <p>
450 - React has been running for {this.state.seconds} seconds.
451 - </p>
452 - );
453 - }
454 -});
455 -
456 -ReactDOM.render(
457 - <TickTock />,
458 - document.getElementById('example')
459 -);
460 -```
461 -
462 -If a component is using multiple mixins and several mixins define the same lifecycle method (i.e. several mixins want to do some cleanup when the component is destroyed), all of the lifecycle methods are guaranteed to be called. Methods defined on mixins run in the order mixins were listed, followed by a method call on the component.
docs/docs/05-reusable-components.zh-CN.md deleted
-285
@@ -1,285 +0,0 @@
1 ----
2 -id: reusable-components-zh-CN
3 -title: 可复用组件
4 -permalink: docs/reusable-components-zh-CN.html
5 -prev: multiple-components-zh-CN.html
6 -next: transferring-props-zh-CN.html
7 ----
8 -
9 -设计接口的时候,把通用的设计元素(按钮,表单框,布局组件等)拆成接口良好定义的可复用的组件。这样,下次开发相同界面程序时就可以写更少的代码,也意义着更高的开发效率,更少的 Bug 和更少的程序体积。
10 -
11 -## Prop 验证
12 -
13 -随着应用不断变大,保证组件被正确使用变得非常有用。为此我们引入 `propTypes`。`React.PropTypes` 提供很多验证器 (validator) 来验证传入数据的有效性。当向 props 传入无效数据时,JavaScript 控制台会抛出警告。注意为了性能考虑,只在开发环境验证 `propTypes`。下面用例子来说明不同验证器的区别:
14 -
15 -```javascript
16 -React.createClass({
17 - propTypes: {
18 - // 可以声明 prop 为指定的 JS 基本类型。默认
19 - // 情况下,这些 prop 都是可传可不传的。
20 - optionalArray: React.PropTypes.array,
21 - optionalBool: React.PropTypes.bool,
22 - optionalFunc: React.PropTypes.func,
23 - optionalNumber: React.PropTypes.number,
24 - optionalObject: React.PropTypes.object,
25 - optionalString: React.PropTypes.string,
26 - optionalSymbol: React.PropTypes.symbol,
27 -
28 - // 所有可以被渲染的对象:数字,
29 - // 字符串,DOM 元素或包含这些类型的数组(or fragment) 。
30 - optionalNode: React.PropTypes.node,
31 -
32 - // React 元素
33 - optionalElement: React.PropTypes.element,
34 -
35 - // 你同样可以断言一个 prop 是一个类的实例。
36 - // 用 JS 的 instanceof 操作符声明 prop 为类的实例。
37 - optionalMessage: React.PropTypes.instanceOf(Message),
38 -
39 - // 你可以用 enum 的方式
40 - // 确保你的 prop 被限定为指定值。
41 - optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),
42 -
43 - // 指定的多个对象类型中的一个
44 - optionalUnion: React.PropTypes.oneOfType([
45 - React.PropTypes.string,
46 - React.PropTypes.number,
47 - React.PropTypes.instanceOf(Message)
48 - ]),
49 -
50 - // 指定类型组成的数组
51 - optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
52 -
53 - // 指定类型的属性构成的对象
54 - optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
55 -
56 - // 特定形状参数的对象
57 - optionalObjectWithShape: React.PropTypes.shape({
58 - color: React.PropTypes.string,
59 - fontSize: React.PropTypes.number
60 - }),
61 -
62 - // 你可以在任意东西后面加上 `isRequired`
63 - // 来确保 如果 prop 没有提供 就会显示一个警告。
64 - requiredFunc: React.PropTypes.func.isRequired,
65 -
66 - // 不可空的任意类型
67 - requiredAny: React.PropTypes.any.isRequired,
68 -
69 - // 你可以自定义一个验证器。如果验证失败需要返回一个 Error 对象。
70 - // 不要直接使用 `console.warn` 或抛异常,
71 - // 因为这在 `oneOfType` 里不起作用。
72 - customProp: function(props, propName, componentName) {
73 - if (!/matchme/.test(props[propName])) {
74 - return new Error('Validation failed!');
75 - }
76 - }
77 - },
78 - /* ... */
79 -});
80 -```
81 -
82 -### Single Child
83 -
84 -用 `React.PropTypes.element` 你可以指定仅有一个子级能被传送给组件
85 -
86 -```javascript
87 -var MyComponent = React.createClass({
88 - propTypes: {
89 - children: React.PropTypes.element.isRequired
90 - },
91 -
92 - render: function() {
93 - return (
94 - <div>
95 - {this.props.children} // 这里必须是一个元素否则就会警告
96 - </div>
97 - );
98 - }
99 -
100 -});
101 -```
102 -
103 -## 默认 Prop 值
104 -
105 -React 支持以声明式的方式来定义 `props` 的默认值。
106 -
107 -```javascript
108 -var ComponentWithDefaultProps = React.createClass({
109 - getDefaultProps: function() {
110 - return {
111 - value: 'default value'
112 - };
113 - }
114 - /* ... */
115 -});
116 -```
117 -
118 -当父级没有传入 props 时,`getDefaultProps()` 可以保证 `this.props.value` 有默认值,注意 `getDefaultProps` 的结果会被 *缓存*。得益于此,你可以直接使用 props,而不必写手动编写一些重复或无意义的代码。
119 -
120 -## 传递 Props:捷径
121 -
122 -有一些常用的 React 组件只是对 HTML 做简单扩展。通常,你想复制任何传进你的组件的HTML属性到底层的HTML元素上。为了减少输入,你可以用 JSX _spread_ 语法来完成:
123 -
124 -```javascript
125 -var CheckLink = React.createClass({
126 - render: function() {
127 - // 这样会把 CheckList 所有的 props 复制到 <a>
128 - return <a {...this.props}>{'√ '}{this.props.children}</a>;
129 - }
130 -});
131 -
132 -ReactDOM.render(
133 - <CheckLink href="/checked.html">
134 - Click here!
135 - </CheckLink>,
136 - document.getElementById('example')
137 -);
138 -```
139 -
140 -## Mixins
141 -
142 -组件是 React 里复用代码的最佳方式,但是有时一些不同的组件间也需要共用一些功能。有时会被称为 [跨切面关注点](https://en.wikipedia.org/wiki/Cross-cutting_concern)。React 使用 `mixins` 来解决这类问题。
143 -
144 -一个通用的场景是:一个组件需要定期更新。用 `setInterval()` 做很容易,但当不需要它的时候取消定时器来节省内存是非常重要的。React 提供 [生命周期方法](/react/docs/working-with-the-browser.html#component-lifecycle) 来告知你组件创建或销毁的时间。下面来做一个简单的 mixin,使用 `setInterval()` 并保证在组件销毁时清理定时器。
145 -
146 -```javascript
147 -var SetIntervalMixin = {
148 - componentWillMount: function() {
149 - this.intervals = [];
150 - },
151 - setInterval: function() {
152 - this.intervals.push(setInterval.apply(null, arguments));
153 - },
154 - componentWillUnmount: function() {
155 - this.intervals.forEach(clearInterval);
156 - }
157 -};
158 -
159 -var TickTock = React.createClass({
160 - mixins: [SetIntervalMixin], // 引用 mixin
161 - getInitialState: function() {
162 - return {seconds: 0};
163 - },
164 - componentDidMount: function() {
165 - this.setInterval(this.tick, 1000); // 调用 mixin 的方法
166 - },
167 - tick: function() {
168 - this.setState({seconds: this.state.seconds + 1});
169 - },
170 - render: function() {
171 - return (
172 - <p>
173 - React has been running for {this.state.seconds} seconds.
174 - </p>
175 - );
176 - }
177 -});
178 -
179 -ReactDOM.render(
180 - <TickTock />,
181 - document.getElementById('example')
182 -);
183 -```
184 -
185 -关于 mixin 值得一提的优点是,如果一个组件使用了多个 mixin,并用有多个 mixin 定义了同样的生命周期方法(如:多个 mixin 都需要在组件销毁时做资源清理操作),所有这些生命周期方法都保证会被执行到。方法执行顺序是:首先按 mixin 引入顺序执行 mixin 里方法,最后执行组件内定义的方法。
186 -
187 -## ES6 Classes
188 -
189 -你也可以以一个简单的 JavaScript 类来定义你的React classes。使用ES6 class的例子:
190 -
191 -```javascript
192 -class HelloMessage extends React.Component {
193 - render() {
194 - return <div>Hello {this.props.name}</div>;
195 - }
196 -}
197 -ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
198 -```
199 -
200 -API近似于 `React.createClass` 除了 `getInitialState`。 你应该在构造函数里设置你的`state`,而不是提供一个单独的 `getInitialState` 方法。就像 `getInitialState` 的返回值,你赋给 `this.state` 的值会被作为组件的初始 state。
201 -
202 -另一个不同是 `propTypes` 和 `defaultProps` 是在构造函数里被定义为属性,而不是在 class body 里。
203 -
204 -```javascript
205 -export class Counter extends React.Component {
206 - constructor(props) {
207 - super(props);
208 - this.state = {count: props.initialCount};
209 - }
210 - tick() {
211 - this.setState({count: this.state.count + 1});
212 - }
213 - render() {
214 - return (
215 - <div onClick={this.tick.bind(this)}>
216 - Clicks: {this.state.count}
217 - </div>
218 - );
219 - }
220 -}
221 -Counter.propTypes = { initialCount: React.PropTypes.number };
222 -Counter.defaultProps = { initialCount: 0 };
223 -```
224 -
225 -### 无自动绑定
226 -
227 -方法遵循正式的ES6 class的语义,意味着它们不会自动绑定`this`到实例上。你必须显示的使用`.bind(this)` or [箭头函数](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions) `=>`:
228 -
229 -```javascript
230 -// 你可以使用 bind() 来绑定 `this`
231 -<div onClick={this.tick.bind(this)}>
232 -
233 -// 或者你可以使用箭头函数
234 -<div onClick={() => this.tick()}>
235 -```
236 -
237 -我们建议你在构造函数中绑定事件处理器,这样对于所有实例它们只需绑定一次:
238 -
239 -```javascript
240 -constructor(props) {
241 - super(props);
242 - this.state = {count: props.initialCount};
243 - this.tick = this.tick.bind(this);
244 -}
245 -```
246 -
247 -现在你可以直接使用 `this.tick` 因为它已经在构造函数里绑定过一次了。
248 -
249 -```javascript
250 -// 它已经在构造函数里绑定过了
251 -<div onClick={this.tick}>
252 -```
253 -
254 -这对应用的性能有帮助,特别是当你用 [浅层比较](/react/docs/shallow-compare.html) 实现 [shouldComponentUpdate()](/react/docs/component-specs.html#updating-shouldcomponentupdate) 时。
255 -
256 -### 没有 Mixins
257 -
258 -不幸的是ES6的发布没有任何mixin的支持。因此,当你在ES6 classes下使用React时不支持mixins。作为替代,我们正在努力使它更容易不依靠mixins支持这些用例。
259 -
260 -## 无状态函数
261 -
262 -你也可以用 JavaScript 函数来定义你的 React 类。例如使用无状态函数语法:
263 -
264 -```javascript
265 -function HelloMessage(props) {
266 - return <div>Hello {props.name}</div>;
267 -}
268 -ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
269 -```
270 -
271 -或者使用新的ES6箭头函数:
272 -
273 -```javascript
274 -const HelloMessage = (props) => <div>Hello {props.name}</div>;
275 -ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
276 -```
277 -
278 -这个简化的组件API旨在用于那些纯函数态的组件 。这些组件必须没有保持任何内部状态,没有备份实例,也没有组件生命周期方法。他们纯粹的函数式的转化他们的输入,没有引用。
279 -然而,你仍然可以以设置函数 properties 的方式来指定 `.propTypes` 和 `.defaultProps`,就像你在ES6类里设置他们那样。
280 -
281 -> 注意:
282 ->
283 -> 因为无状态函数没有备份实例,你不能附加一个引用到一个无状态函数组件。 通常这不是问题,因为无状态函数不提供一个命令式的API。没有命令式的API,你就没有任何需要实例来做的事。然而,如果用户想查找无状态函数组件的DOM节点,他们必须把这个组件包装在一个有状态组件里(比如,ES6 类组件) 并且连接一个引用到有状态的包装组件。
284 -
285 -在理想世界里,你的大多数组件都应该是无状态函数,因为将来我们可能会用避免不必要的检查和内存分配的方式来对这些组件进行优化。 如果可能,这是推荐的模式。
docs/docs/06-transferring-props.it-IT.md deleted
-153
@@ -1,153 +0,0 @@
1 ----
2 -id: transferring-props-it-IT
3 -title: Trasferimento delle Proprietà
4 -permalink: docs/transferring-props-it-IT.html
5 -prev: reusable-components-it-IT.html
6 -next: forms-it-IT.html
7 ----
8 -
9 -Un pattern comune in React è l'uso di un'astrazione per esporre un componente. Il componente esterno espone una semplice proprietà per effettuare un'azione che può richiedere un'implementazione più complessa.
10 -
11 -Puoi usare gli [attributi spread di JSX](/react/docs/jsx-spread.html) per unire le vecchie props con valori aggiuntivi:
12 -
13 -```javascript
14 -<Component {...this.props} more="values" />
15 -```
16 -
17 -Se non usi JSX, puoi usare qualsiasi helper come l'API `Object.assign` di ES6, o il metodo `_.extend` di Underscore:
18 -
19 -```javascript
20 -React.createElement(Component, Object.assign({}, this.props, { more: 'values' }));
21 -```
22 -
23 -Nel resto di questo tutorial vengono illustrate le best practices, usando JSX e sintassi sperimentale di ES7.
24 -
25 -## Trasferimento Manuale
26 -
27 -Nella maggior parte dei casi dovresti esplicitamente passare le proprietà. Ciò assicura che venga esposto soltanto un sottoinsieme dell'API interna, del cui funzionamento si è certi.
28 -
29 -```javascript
30 -function FancyCheckbox(props) {
31 - var fancyClass = props.checked ? 'FancyChecked' : 'FancyUnchecked';
32 - return (
33 - <div className={fancyClass} onClick={props.onClick}>
34 - {props.children}
35 - </div>
36 - );
37 -}
38 -ReactDOM.render(
39 - <FancyCheckbox checked={true} onClick={console.log.bind(console)}>
40 - Ciao mondo!
41 - </FancyCheckbox>,
42 - document.getElementById('example')
43 -);
44 -```
45 -
46 -E se aggiungessimo una proprietà `name`? O una proprietà `title`? O `onMouseOver`?
47 -
48 -## Trasferire con `...` in JSX
49 -
50 -> NOTA:
51 ->
52 -> La sintassi `...` fa parte della proposta Object Rest Spread. Questa proposta è in processo di diventare uno standard. Consulta la sezione [Proprietà Rest e Spread ...](/react/docs/transferring-props.html#rest-and-spread-properties-...) di seguito per maggiori dettagli.
53 -
54 -A volte passare manualmente ciascuna proprietà può essere noioso e fragile. In quei casi puoi usare l'[assegnamento destrutturante](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) con le proprietà residue per estrarre un insieme di proprietà sconosciute.
55 -
56 -Elenca tutte le proprietà che desideri consumare, seguite da `...other`.
57 -
58 -```javascript
59 -var { checked, ...other } = props;
60 -```
61 -
62 -Ciò assicura che vengano passate tutte le proprietà TRANNE quelle che stai consumando tu stesso.
63 -
64 -```javascript
65 -function FancyCheckbox(props) {
66 - var { checked, ...other } = props;
67 - var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
68 - // `other` contiene { onClick: console.log } ma non la proprietà checked
69 - return (
70 - <div {...other} className={fancyClass} />
71 - );
72 -}
73 -ReactDOM.render(
74 - <FancyCheckbox checked={true} onClick={console.log.bind(console)}>
75 - Ciao mondo!
76 - </FancyCheckbox>,
77 - document.getElementById('example')
78 -);
79 -```
80 -
81 -> NOTA:
82 ->
83 -> Nell'esempio precedente, la proprietà `checked` è anche un attributo DOM valido. Se non utilizzassi la destrutturazione in questo modo, potresti inavvertitamente assegnarlo al `div`.
84 -
85 -Usa sempre il pattern di destrutturazione quando trasferisci altre proprietà sconosciute in `other`.
86 -
87 -```javascript
88 -function FancyCheckbox(props) {
89 - var fancyClass = props.checked ? 'FancyChecked' : 'FancyUnchecked';
90 - // ANTI-PATTERN: `checked` sarebbe passato al componente interno
91 - return (
92 - <div {...props} className={fancyClass} />
93 - );
94 -}
95 -```
96 -
97 -## Consumare e Trasferire la Stessa Proprietà
98 -
99 -Se il tuo componente desidera consumare una proprietà, ma anche passarla ad altri, puoi passarla esplicitamente mediante `checked={checked}`. Questo è preferibile a passare l'intero oggetto `this.props` dal momento che è più facile effettuarne il linting e il refactoring.
100 -
101 -```javascript
102 -function FancyCheckbox(props) {
103 - var { checked, title, ...other } = props;
104 - var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
105 - var fancyTitle = checked ? 'X ' + title : 'O ' + title;
106 - return (
107 - <label>
108 - <input {...other}
109 - checked={checked}
110 - className={fancyClass}
111 - type="checkbox"
112 - />
113 - {fancyTitle}
114 - </label>
115 - );
116 -}
117 -```
118 -
119 -> NOTA:
120 ->
121 -> L'ordine è importante. Mettendo il `{...other}` prima delle tue proprietà JSX ti assicuri che il consumatore del tuo componente non possa ridefinirle. Nell'esempio precedente, abbiamo garantito che l'elemento input sarà del tipo `"checkbox"`.
122 -
123 -## Proprietà Rest e Spread `...`
124 -
125 -Le proprietà Rest ti permettono di estrarre le proprietà residue di un oggetto in un nuovo oggetto. Vengono escluse tutte le altre proprietà elencate nel pattern di destrutturazione.
126 -
127 -Questa è un'implementazione sperimentale di una [proposta ES7](https://github.com/sebmarkbage/ecmascript-rest-spread).
128 -
129 -```javascript
130 -var { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
131 -x; // 1
132 -y; // 2
133 -z; // { a: 3, b: 4 }
134 -```
135 -
136 -> Nota:
137 ->
138 -> Questa proposta ha raggiunto lo stadio 2 ed è attivata in modo predefinito in Babel. Vecchie versioni di Babel potrebbero richiedere l'abilitazione esplicita di questa trasformazione con `babel --optional es7.objectRestSpread`
139 -
140 -## Trasferire con Underscore
141 -
142 -Se non usi JSX, puoi usare una libreria per ottenere il medesimo pattern. Underscore supporta `_.omit` per omettere delle proprietà ed `_.extend` per copiare le proprietà in un nuovo oggetto.
143 -
144 -```javascript
145 -function FancyCheckbox(props) {
146 - var checked = props.checked;
147 - var other = _.omit(props, 'checked');
148 - var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
149 - return (
150 - React.DOM.div(_.extend({}, other, { className: fancyClass }))
151 - );
152 -}
153 -```
docs/docs/06-transferring-props.ja-JP.md deleted
-151
@@ -1,151 +0,0 @@
1 ----
2 -id: transferring-props
3 -title: propsの移譲
4 -permalink: docs/transferring-props-ja-JP.html
5 -prev: reusable-components-ja-JP.html
6 -next: forms-ja-JP.html
7 -
8 ----
9 -
10 -
11 -コンポーネントを抽象的にラップすることはReactにおいて共通のパターンです。外のコンポーネントは単純なプロパティを表示し、中ではさらに複雑なインプリメンテーションの詳細を持つようになっています。
12 -
13 -以下のように、古いpropsと追加の値を[JSXの拡張属性](/react/docs/jsx-spread-ja-JP.html)を使ってマージすることができます。
14 -
15 -```javascript
16 -<Component {...this.props} more="values" />
17 -```
18 -
19 -JSXを使わない場合は、以下のように、ES6の `Object.assign` か Underscore の `_.extend` といったオブジェクトヘルパーを使うことができます。
20 -
21 -```javascript
22 -React.createElement(Component, Object.assign({}, this.props, { more: 'values' }));
23 -```
24 -
25 -以下のチュートリアルはベストプラクティスを提示しています。JSXや試験的なES7のシンタックスを使っています。
26 -
27 -## 手動での移動
28 -
29 -ほとんどの場合、プロパティを明確に子要素に渡すべきです。それは、内部のAPIのサブセットだけを外に出していることと、認識しているプロパティが動作することを保証します。
30 -
31 -```javascript
32 -function FancyCheckbox(props) {
33 - var fancyClass = props.checked ? 'FancyChecked' : 'FancyUnchecked';
34 - return (
35 - <div className={fancyClass} onClick={props.onClick}>
36 - {props.children}
37 - </div>
38 - );
39 -}
40 -ReactDOM.render(
41 - <FancyCheckbox checked={true} onClick={console.log.bind(console)}>
42 - Hello world!
43 - </FancyCheckbox>,
44 - document.getElementById('example')
45 -);
46 -```
47 -
48 -しかし、 `name` プロパティや `title` プロパティや `onMouseOver` はどうでしょうか?
49 -
50 -## JSXにおける `...` を使った移譲
51 -
52 -> 注意:
53 -> 以下の例では、実験的なES7のシンタックスであることを示すために `--harmony ` フラグが必要になります。ブラウザ上でJSXトランスフォーマーを使う際には、単純に `<script type="text/jsx;harmony=true">` を使ってスクリプトを読み込んでください。詳細については、 [レストとスプレッドのプロパティ ...](/react/docs/transferring-props-ja-JP.html#レストとスプレッドのプロパティ-...)をご覧ください。
54 -
55 -全てのプロパティを渡すのはバグを生みやすく、面倒くさいときがあります。そのようなケースでは、未知のプロパティのセットを使うためにレストプロパティと共に[分割代入引数](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)を使うことができます。
56 -
57 -以下のように `...other` を使うことで、使いたいプロパティを一覧にすることができます。
58 -
59 -```javascript
60 -var { checked, ...other } = props;
61 -```
62 -
63 -これは、自分で指定したものは 除き 、全てのpropsを渡すことを保証します。
64 -
65 -```javascript
66 -function FancyCheckbox(props) {
67 - var { checked, ...other } = props;
68 - var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
69 - // `other` は { onClick: console.log } を含みますが、 checked プロパティは含みません。
70 - return (
71 - <div {...other} className={fancyClass} />
72 - );
73 -}
74 -ReactDOM.render(
75 - <FancyCheckbox checked={true} onClick={console.log.bind(console)}>
76 - Hello world!
77 - </FancyCheckbox>,
78 - document.getElementById('example')
79 -);
80 -```
81 -
82 -> 注意:
83 -> 上の例では、 `checked` propは正式なDOMの属性でもあります。この方法を使って分割代入を行わない場合は、無意識的に渡すこともできます。
84 -
85 -未知の `other` propsを移譲する際には、分割代入パターンを常に使ってください。
86 -
87 -```javascript
88 -function FancyCheckbox(props) {
89 - var fancyClass = props.checked ? 'FancyChecked' : 'FancyUnchecked';
90 - // アンチパターン: `checked` が内部のコンポーネントに渡されます。
91 - return (
92 - <div {...props} className={fancyClass} />
93 - );
94 -}
95 -```
96 -
97 -## 同じpropを使い、移譲する
98 -
99 -コンポーネントがプロパティを使うだけでなく、子要素に渡したい場合は、明確に `checked={checked}` と記述することで再度渡すことができます。 `this.props` オブジェクトで全てを渡すほうが、リファクタリングやチェックをしやすいので好ましいです。
100 -
101 -```javascript
102 -function FancyCheckbox(props) {
103 - var { checked, title, ...other } = props;
104 - var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
105 - var fancyTitle = checked ? 'X ' + title : 'O ' + title;
106 - return (
107 - <label>
108 - <input {...other}
109 - checked={checked}
110 - className={fancyClass}
111 - type="checkbox"
112 - />
113 - {fancyTitle}
114 - </label>
115 - );
116 -}
117 -```
118 -
119 -> 注意:
120 -> 順番の問題です。JSXのpropsの前に `{...other}` を置くことで、コンポーネントの使用者がオーバーライドできないことを保証します。上の例ではinputが `"checkbox"` 型であることを保証しました。
121 -
122 -## レストとスプレッドのプロパティ `...`
123 -
124 -レストプロパティはあるオブジェクトの残りの要素を新しいオブジェクトに引き抜きます。分割代入パターンでリストになっている全てのプロパティを外に出します。
125 -
126 -これは、[ES7プロポーサル](https://github.com/sebmarkbage/ecmascript-rest-spread)の実験的な実行です。
127 -
128 -```javascript
129 -var { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
130 -x; // 1
131 -y; // 2
132 -z; // { a: 3, b: 4 }
133 -```
134 -
135 -> 注意:
136 -> 実験的なES7のシンタックスを有効にするには、 `--harmony` フラグを[JSXコマンドラインツール](https://www.npmjs.com/package/react-tools)で使用してください。
137 -
138 -## Underscoreによる移譲
139 -
140 -JSXを使わない際には、同じパターンを行うライブラリを使うことができます。Underscoreでは、 `_.omit` を使ってプロパティをフィルタしたり、 `_.extend` を使って新しいオブジェクトにプロパティをコピーしたりできます。
141 -
142 -```javascript
143 -function FancyCheckbox(props) {
144 - var checked = props.checked;
145 - var other = _.omit(props, 'checked');
146 - var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
147 - return (
148 - React.DOM.div(_.extend({}, other, { className: fancyClass }))
149 - );
150 -}
151 -```
docs/docs/06-transferring-props.ko-KR.md deleted
-155
@@ -1,155 +0,0 @@
1 ----
2 -id: transferring-props-ko-KR
3 -title: Props 전달
4 -permalink: docs/transferring-props-ko-KR.html
5 -prev: reusable-components-ko-KR.html
6 -next: forms-ko-KR.html
7 ----
8 -
9 -React에서는 컴포넌트를 감싸서 추상화하는 것이 일반적인 패턴입니다. 외부 컴포넌트에서는 간단한 프로퍼티만을 노출하여 복잡한 세부 구현을 감출 수 있습니다.
10 -
11 -[JSX 스프레드 어트리뷰트](/react/docs/jsx-spread-ko-KR.html)를 통해 props에 추가적인 값을 병합할 수 있습니다.
12 -
13 -```javascript
14 -<Component {...this.props} more="values" />
15 -```
16 -
17 -만약 JSX를 사용하지 않는다면 ES6의 `Object.assign`나 Underscore의 `_.extend` 같은 객체 헬퍼를 사용할 수 있습니다:
18 -
19 -```javascript
20 -React.createElement(Component, Object.assign({}, this.props, { more: 'values' }));
21 -```
22 -
23 -이 튜토리얼의 나머지 부분은 모범 답안을 소개할 것입니다. JSX와 실험적인 ES7 구문을 사용합니다.
24 -
25 -## 수동적인 전달
26 -
27 -대부분의 경우 명시적으로 프로퍼티를 아래로 전달해야 합니다. 이는 동작을 확신하는 내부 API의 일부만 공개하도록 합니다.
28 -
29 -```javascript
30 -function FancyCheckbox(props) {
31 - var fancyClass = props.checked ? 'FancyChecked' : 'FancyUnchecked';
32 - return (
33 - <div className={fancyClass} onClick={props.onClick}>
34 - {props.children}
35 - </div>
36 - );
37 -}
38 -ReactDOM.render(
39 - <FancyCheckbox checked={true} onClick={console.log.bind(console)}>
40 - 세상아 안녕!
41 - </FancyCheckbox>,
42 - document.getElementById('example')
43 -);
44 -```
45 -
46 -하지만 `name`이나 `title`, `onMouseOver` 같은 prop들이 더 추가된다면 어떨까요?
47 -
48 -## JSX에서 `...`를 사용해 전달하기
49 -
50 -> 주의:
51 ->
52 -> `...` 구문은 객체 잔여 스프레드 제안의 일부입니다. 이 제안은 표준화 과정에 있습니다. 더 자세한 내용은 밑의 [잔여 프로퍼티와 스프레드 프로퍼티 ...](/react/docs/transferring-props.html#rest-and-spread-properties-...) 부분을 참고하세요.
53 -
54 -
55 -때로는 모든 프로퍼티를 일일이 전달 하는것은 지루하고 덧없는 작업입니다. 이 경우 [구조 해체 할당(destructuring assignment)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)을 다른 프로퍼티를 함께 사용해 미상의 프로퍼티를 추출할 수 있습니다.
56 -
57 -소비할 프로퍼티들을 나열하고, 그 뒤에 `...other`를 넣습니다.
58 -
59 -```javascript
60 -var { checked, ...other } = props;
61 -```
62 -
63 -이는 지금 소비한 props를 *제외한* 나머지를 아래로 전달합니다.
64 -
65 -```javascript
66 -function FancyCheckbox(props) {
67 - var { checked, ...other } = props;
68 - var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
69 - // `other`에는 { onClick: console.log }가 포함되지만 checked 프로퍼티는 제외됩니다
70 - return (
71 - <div {...other} className={fancyClass} />
72 - );
73 -}
74 -ReactDOM.render(
75 - <FancyCheckbox checked={true} onClick={console.log.bind(console)}>
76 - 세상아 안녕!
77 - </FancyCheckbox>,
78 - document.getElementById('example')
79 -);
80 -```
81 -
82 -> 주의:
83 ->
84 -> 위의 예제에서는 `checked` prop 또한 마찬가지로 유효한 DOM 어트리뷰트입니다. 이런 식으로 구조의 해체(destructuring)를 하지 않으면 의도하지 않게 함께 전달될 수 있습니다.
85 -
86 -미상의 `other` props을 전달할 때는 항상 구조 해체 패턴을 사용하세요.
87 -
88 -```javascript
89 -function FancyCheckbox(props) {
90 - var fancyClass = props.checked ? 'FancyChecked' : 'FancyUnchecked';
91 - // 반례: `checked` 또한 내부 컴포넌트로 전달될 것입니다
92 - return (
93 - <div {...props} className={fancyClass} />
94 - );
95 -}
96 -```
97 -
98 -## 같은 Prop을 소비하고 전달하기
99 -
100 -컴포넌트가 프로퍼티를 사용하지만 계속 넘기길 원한다면, `checked={checked}`처럼 명시적으로 다시 넘길 수 있습니다. 리팩토링과 린트(lint)하기가 더 쉬우므로 이 방식이 `this.props` 객체 전부를 넘기는 것보다 낫습니다.
101 -
102 -```javascript
103 -function FancyCheckbox(props) {
104 - var { checked, title, ...other } = props;
105 - var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
106 - var fancyTitle = checked ? 'X ' + title : 'O ' + title;
107 - return (
108 - <label>
109 - <input {...other}
110 - checked={checked}
111 - className={fancyClass}
112 - type="checkbox"
113 - />
114 - {fancyTitle}
115 - </label>
116 - );
117 -}
118 -```
119 -
120 -> 주의:
121 ->
122 -> 순서는 중요합니다. `{...other}`를 JSX props 이전에 넣는 것으로 컴포넌트의 사용자가 확실히 그것들을 오버라이드 할 수 없게 합니다. 위의 예제에서는 input이 `"checkbox"` 타입인 것을 보장합니다.
123 -
124 -<a name="rest-and-spread-properties-..."></a>
125 -## 잔여 프로퍼티와 스프레드 프로퍼티 `...`
126 -
127 -잔여(Rest, `...`) 프로퍼티는 객체에서 소비되지 않은 나머지 프로퍼티를 추출해 새로운 객체로 만들 수 있게 해 줍니다. 구조 해체 패턴에서 열거된 다른 프로퍼티들은 모두 제외됩니다.
128 -
129 -이 제안은 2 단계에 돌입해 이제 바벨에서 기본값으로 활성화되어있습니다. 바벨의 이전 버전은 `babel --optional es7.objectRestSpread`로 명시적으로 활성화 할 필요가 있을 수도 있습니다.
130 -
131 -```javascript
132 -var { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
133 -x; // 1
134 -y; // 2
135 -z; // { a: 3, b: 4 }
136 -```
137 -
138 -> 주의:
139 ->
140 -> 실험적인 ES7 구문을 활성화하려면 [JSX 커맨드라인 도구](https://www.npmjs.com/package/react-tools)를 `--harmony` 플래그와 함께 사용하세요.
141 -
142 -## Underscore로 전달 다루기
143 -
144 -JSX를 사용하지 않는다면 라이브러리를 사용해 같은 패턴을 쓸 수 있습니다. Underscore에서는 `_.omit`을 사용해 특정 프로퍼티를 제외하거나 `_.extend`를 사용해 새로운 객체로 프로퍼티를 복사할 수 있습니다.
145 -
146 -```javascript
147 -function FancyCheckbox(props) {
148 - var checked = props.checked;
149 - var other = _.omit(props, 'checked');
150 - var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
151 - return (
152 - React.DOM.div(_.extend({}, other, { className: fancyClass }))
153 - );
154 -}
155 -```
docs/docs/06-transferring-props.md deleted
-153
@@ -1,153 +0,0 @@
1 ----
2 -id: transferring-props
3 -title: Transferring Props
4 -permalink: docs/transferring-props.html
5 -prev: reusable-components.html
6 -next: forms.html
7 ----
8 -
9 -It's a common pattern in React to wrap a component in an abstraction. The outer component exposes a simple property to do something that might have more complex implementation details.
10 -
11 -You can use [JSX spread attributes](/react/docs/jsx-spread.html) to merge the old props with additional values:
12 -
13 -```javascript
14 -<Component {...this.props} more="values" />
15 -```
16 -
17 -If you don't use JSX, you can use any object helper such as ES6 `Object.assign` or Underscore `_.extend`:
18 -
19 -```javascript
20 -React.createElement(Component, Object.assign({}, this.props, { more: 'values' }));
21 -```
22 -
23 -The rest of this tutorial explains best practices. It uses JSX and experimental ECMAScript syntax.
24 -
25 -## Manual Transfer
26 -
27 -Most of the time you should explicitly pass the properties down. This ensures that you only expose a subset of the inner API, one that you know will work.
28 -
29 -```javascript
30 -function FancyCheckbox(props) {
31 - var fancyClass = props.checked ? 'FancyChecked' : 'FancyUnchecked';
32 - return (
33 - <div className={fancyClass} onClick={props.onClick}>
34 - {props.children}
35 - </div>
36 - );
37 -}
38 -ReactDOM.render(
39 - <FancyCheckbox checked={true} onClick={console.log.bind(console)}>
40 - Hello world!
41 - </FancyCheckbox>,
42 - document.getElementById('example')
43 -);
44 -```
45 -
46 -But what about the `name` prop? Or the `title` prop? Or `onMouseOver`?
47 -
48 -## Transferring with `...` in JSX
49 -
50 -> NOTE:
51 ->
52 -> The `...` syntax is part of the Object Rest Spread proposal. This proposal is on track to become a standard. See the [Rest and Spread Properties ...](/react/docs/transferring-props.html#rest-and-spread-properties-...) section below for more details.
53 -
54 -Sometimes it's fragile and tedious to pass every property along. In that case you can use [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) with rest properties to extract a set of unknown properties.
55 -
56 -List out all the properties that you would like to consume, followed by `...other`.
57 -
58 -```javascript
59 -var { checked, ...other } = props;
60 -```
61 -
62 -This ensures that you pass down all the props EXCEPT the ones you're consuming yourself.
63 -
64 -```javascript
65 -function FancyCheckbox(props) {
66 - var { checked, ...other } = props;
67 - var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
68 - // `other` contains { onClick: console.log } but not the checked property
69 - return (
70 - <div {...other} className={fancyClass} />
71 - );
72 -}
73 -ReactDOM.render(
74 - <FancyCheckbox checked={true} onClick={console.log.bind(console)}>
75 - Hello world!
76 - </FancyCheckbox>,
77 - document.getElementById('example')
78 -);
79 -```
80 -
81 -> NOTE:
82 ->
83 -> In the example above, the `checked` prop is also a valid DOM attribute. If you didn't use destructuring in this way you might inadvertently pass it along.
84 -
85 -Always use the destructuring pattern when transferring unknown `other` props.
86 -
87 -```javascript
88 -function FancyCheckbox(props) {
89 - var fancyClass = props.checked ? 'FancyChecked' : 'FancyUnchecked';
90 - // ANTI-PATTERN: `checked` would be passed down to the inner component
91 - return (
92 - <div {...props} className={fancyClass} />
93 - );
94 -}
95 -```
96 -
97 -## Consuming and Transferring the Same Prop
98 -
99 -If your component wants to consume a property but also wants to pass it along, you can repass it explicitly with `checked={checked}`. This is preferable to passing the full `props` object since it's easier to refactor and lint.
100 -
101 -```javascript
102 -function FancyCheckbox(props) {
103 - var { checked, title, ...other } = props;
104 - var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
105 - var fancyTitle = checked ? 'X ' + title : 'O ' + title;
106 - return (
107 - <label>
108 - <input {...other}
109 - checked={checked}
110 - className={fancyClass}
111 - type="checkbox"
112 - />
113 - {fancyTitle}
114 - </label>
115 - );
116 -}
117 -```
118 -
119 -> NOTE:
120 ->
121 -> Order matters. By putting the `{...other}` before your JSX props you ensure that the consumer of your component can't override them. In the example above we have guaranteed that the input will be of type `"checkbox"`.
122 -
123 -## Rest and Spread Properties `...`
124 -
125 -Rest properties allow you to extract the remaining properties from an object into a new object. It excludes every other property listed in the destructuring pattern.
126 -
127 -This is an experimental implementation of an [ECMAScript proposal](https://github.com/sebmarkbage/ecmascript-rest-spread).
128 -
129 -```javascript
130 -var { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
131 -x; // 1
132 -y; // 2
133 -z; // { a: 3, b: 4 }
134 -```
135 -
136 -> Note:
137 ->
138 -> To transform rest and spread properties using Babel 6, you need to install the [`es2015`](https://babeljs.io/docs/plugins/preset-es2015/) preset, the [`transform-object-rest-spread`](https://babeljs.io/docs/plugins/transform-object-rest-spread/) plugin and configure them in the `.babelrc` file.
139 -
140 -## Transferring with Underscore
141 -
142 -If you don't use JSX, you can use a library to achieve the same pattern. Underscore supports `_.omit` to filter out properties and `_.extend` to copy properties onto a new object.
143 -
144 -```javascript
145 -function FancyCheckbox(props) {
146 - var checked = props.checked;
147 - var other = _.omit(props, 'checked');
148 - var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
149 - return (
150 - React.DOM.div(_.extend({}, other, { className: fancyClass }))
151 - );
152 -}
153 -```
docs/docs/06-transferring-props.zh-CN.md deleted
-153
@@ -1,153 +0,0 @@
1 ----
2 -id: transferring-props-zh-CN
3 -title: 传递 Props
4 -permalink: docs/transferring-props-zh-CN.html
5 -prev: reusable-components-zh-CN.html
6 -next: forms-zh-CN.html
7 ----
8 -
9 -React 里有一个非常常用的模式就是对组件做一层抽象。组件对外公开一个简单的属性(Props)来实现功能,但内部的实现可能非常复杂。
10 -
11 -可以使用 [JSX 展开属性](/react/docs/jsx-spread-zh-CN.html) 来合并现有的 props 和其它值:
12 -
13 -```javascript
14 -<Component {...this.props} more="values" />
15 -```
16 -
17 -如果不使用 JSX,可以使用一些对象辅助方法如 ES6 的 `Object.assign` 或 Underscore `_.extend`。
18 -
19 -```javascript
20 -React.createElement(Component, Object.assign({}, this.props, { more: 'values' }));
21 -```
22 -
23 -下面的教程介绍一些最佳实践。使用了 JSX 和 试验性的ECMAScript 语法。
24 -
25 -## 手动传递
26 -
27 -大部分情况下你应该显式地向下传递 props。这样可以确保只公开你认为是安全的内部 API 的子集。
28 -
29 -```javascript
30 -function FancyCheckbox(props) {
31 - var fancyClass = props.checked ? 'FancyChecked' : 'FancyUnchecked';
32 - return (
33 - <div className={fancyClass} onClick={props.onClick}>
34 - {props.children}
35 - </div>
36 - );
37 -}
38 -ReactDOM.render(
39 - <FancyCheckbox checked={true} onClick={console.log.bind(console)}>
40 - Hello world!
41 - </FancyCheckbox>,
42 - document.getElementById('example')
43 -);
44 -```
45 -
46 -但 `name` 这个属性怎么办?还有 `title`、`onMouseOver` 这些 props?
47 -
48 -## 在 JSX 里使用 `...` 传递
49 -
50 -> 注意:
51 ->
52 -> 在下面的例子中,`--harmony ` 标志是必须的因为这个语法是ES7的实验性语法。如果用浏览器中的JSX转换器,以 `<script type="text/jsx;harmony=true">`简单的打开你脚本就行了。详见[Rest and Spread Properties ...](/react/docs/transferring-props-zh-CN.html#剩余属性和展开属性-...)
53 -
54 -有时把所有属性都传下去是不安全或啰嗦的。这时可以使用 [解构赋值](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) 中的剩余属性特性来把未知属性批量提取出来。
55 -
56 -列出所有当前要使用的属性,后面跟着 `...other`。
57 -
58 -```javascript
59 -var { checked, ...other } = props;
60 -```
61 -
62 -这样能确保把所有 props 传下去,*除了* 那些已经被使用了的。
63 -
64 -```javascript
65 -function FancyCheckbox(props) {
66 - var { checked, ...other } = props;
67 - var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
68 - // `other` 包含 { onClick: console.log } 但 checked 属性除外
69 - return (
70 - <div {...other} className={fancyClass} />
71 - );
72 -}
73 -ReactDOM.render(
74 - <FancyCheckbox checked={true} onClick={console.log.bind(console)}>
75 - Hello world!
76 - </FancyCheckbox>,
77 - document.getElementById('example')
78 -);
79 -```
80 -
81 -> 注意:
82 ->
83 -> 上面例子中,`checked` 属性也是一个有效的 DOM 属性。如果你没有使用解构赋值,那么可能无意中把它传下去。
84 -
85 -在传递这些未知的 `other` 属性时,要经常使用解构赋值模式。
86 -
87 -```javascript
88 -function FancyCheckbox(props) {
89 - var fancyClass = props.checked ? 'FancyChecked' : 'FancyUnchecked';
90 - // 反模式:`checked` 会被传到里面的组件里
91 - return (
92 - <div {...props} className={fancyClass} />
93 - );
94 -}
95 -```
96 -
97 -## 使用和传递同一个 Prop
98 -
99 -如果组件需要使用一个属性又要往下传递,可以直接使用 `checked={checked}` 再传一次。这样做比传整个 `props` 对象要好,因为更利于重构和语法检查。
100 -
101 -```javascript
102 -function FancyCheckbox(props) {
103 - var { checked, title, ...other } = props;
104 - var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
105 - var fancyTitle = checked ? 'X ' + title : 'O ' + title;
106 - return (
107 - <label>
108 - <input {...other}
109 - checked={checked}
110 - className={fancyClass}
111 - type="checkbox"
112 - />
113 - {fancyTitle}
114 - </label>
115 - );
116 -}
117 -```
118 -
119 -> 注意:
120 ->
121 -> 顺序很重要,把 `{...other}` 放到 JSX props 前面会使 props 不会被覆盖。上面例子中我们可以保证 input 的 type 是 `"checkbox"`。
122 -
123 -## 剩余属性和展开属性 `...`
124 -
125 -剩余属性可以把对象剩下的属性提取到一个新的对象。这会把所有在解构赋值中列出的属性剔除。
126 -
127 -这是 [ECMAScript 草案](https://github.com/sebmarkbage/ecmascript-rest-spread) 中的试验特性。
128 -
129 -```javascript
130 -var { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
131 -x; // 1
132 -y; // 2
133 -z; // { a: 3, b: 4 }
134 -```
135 -
136 -> 注意:
137 ->
138 -> 要用 Babel 6转换 rest 和 spread 属性,你需要安装 [`es2015`](https://babeljs.io/docs/plugins/preset-es2015/) preset,[`transform-object-rest-spread`](https://babeljs.io/docs/plugins/transform-object-rest-spread/) 插件并在 `.babelrc` 里配置他们.
139 -
140 -## 使用 Underscore 来传递
141 -
142 -如果不使用 JSX,可以使用一些库来实现相同效果。Underscore 提供 `_.omit` 来过滤属性,`_.extend` 复制属性到新的对象。
143 -
144 -```javascript
145 -function FancyCheckbox(props) {
146 - var checked = props.checked;
147 - var other = _.omit(props, 'checked');
148 - var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
149 - return (
150 - React.DOM.div(_.extend({}, other, { className: fancyClass }))
151 - );
152 -}
153 -```
docs/docs/07-forms.it-IT.md deleted
-165
@@ -1,165 +0,0 @@
1 ----
2 -id: forms-it-IT
3 -title: Moduli
4 -permalink: docs/forms-it-IT.html
5 -prev: transferring-props-it-IT.html
6 -next: working-with-the-browser-it-IT.html
7 ----
8 -
9 -I componenti dei moduli come `<input>`, `<textarea>` e `<option>` differiscono dagli altri componenti nativi poiché possono essere alterati tramite interazione dell'utente. Questi componenti forniscono interfacce che rendono più semplice gestire i moduli in risposta all'interazione dell'utente.
10 -
11 -Per maggiori informazioni sugli eventi dell'elemento `<form>` consulta [Eventi dei Moduli](/react/docs/events.html#form-events).
12 -
13 -## Proprietà Interattive
14 -
15 -I componenti dei moduli supportano un numero di proprietà che vengono modificate dall'interazione dell'utente:
16 -
17 -* `value`, supportato dai elementi `<input>` e `<textarea>`.
18 -* `checked`, supportato dagli elementi `<input>` dal tipo `checkbox` o `radio`.
19 -* `selected`, supportato dagli elementi `<option>`.
20 -
21 -In HTML, in valore di `<textarea>` è impostato tramite un nodo di testo figlio. In React, devi invece usare la proprietà `value`.
22 -
23 -I componenti dei moduli ti permettono di reagire ai cambiamenti impostando una callback come proprietà `onChange`. La proprietà `onChange` funziona in tutti i browser e viene scatenata in risposta all'interazione dell'utente quando:
24 -
25 -* Il `value` di `<input>` o `<textarea>` cambia.
26 -* Lo stato `checked` di `<input>` cambia.
27 -* Lo stato `selected` di `<option>` cambia.
28 -
29 -Come tutti gli eventi DOM, la proprietà `onChange` è supportata su tutti i componenti nativi e può essere usata per gestire la propagazione di eventi di cambiamento.
30 -
31 -> Nota:
32 ->
33 -> Per `<input>` e `<textarea>`, `onChange` rimpiazza — e dovrebbe generalmente essere utilizzata in sostituzione — il gestore di eventi [`oninput`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput) nativo del DOM.
34 -
35 -
36 -## Componenti Controllati
37 -
38 -Un `<input>` il cui `value` è impostato è un componente *controllato*. In un `<input>` controllato, il valore dell'elemento visualizzato si riflette sempre nella sua proprietà `value`. Ad esempio:
39 -
40 -```javascript
41 - render: function() {
42 - return <input type="text" value="Ciao!" />;
43 - }
44 -```
45 -
46 -Ciò visualizzerà un input che ha sempre il valore di `value` impostato a `Ciao!`. Ciascuna immissione dell'utente non avrà effetto sull'elemento visualizzato poiché React ha dichiarato il suo `value` pari a `Ciao!`. Se volessi aggiornare il `value` in risposta all'input dell'utente, puoi usare l'evento `onChange`:
47 -
48 -```javascript
49 - getInitialState: function() {
50 - return {value: 'Ciao!'};
51 - },
52 - handleChange: function(event) {
53 - this.setState({value: event.target.value});
54 - },
55 - render: function() {
56 - var value = this.state.value;
57 - return <input type="text" value={value} onChange={this.handleChange} />;
58 - }
59 -```
60 -
61 -In questo esempio, stiamo semplicemente accettando il valore più recente fornito dall'utente e aggiornando la proprietà `value` del componente `<input>`. Questo pattern semplifica l'implementazione di interfacce che rispondono o validano l'interazione dell'utente. Ad esempio:
62 -
63 -```javascript
64 - handleChange: function(event) {
65 - this.setState({value: event.target.value.substr(0, 140)});
66 - }
67 -```
68 -
69 -Così si può accettare l'input dell'utente ma ne tronca il valore ai primi 140 caratteri.
70 -
71 -### Potenziali Problemi con Checkbox e Radio Button
72 -
73 -Fai attenzione che, allo scopo di normalizzare la gestione del cambiamento degli elementi checkbox e radio button, React usa un evento `click` al posto di un evento `change`. Nella maggior parte dei casi questo funziona nel modo previsto, tranne quando viene usato `preventDefault` in un gestore dell'evento `change`. `preventDefault` impedisce al browser di aggiornare visualmente l'input, anche se `checked` cambia il suo valore. Questo può essere evitato rimuovendo la chiamata a `preventDefault`, oppure effettuando il cambio del valore di `checked` tramite `setTimeout`.
74 -
75 -
76 -## Componenti Non Controllati
77 -
78 -Un `<input>` che non fornisce un `value` (o lo imposta a `null`) è un componente *non controllato*. In un `<input>` non controllato, il valore dell'elemento visualizzato rifletterà l'input dell'utente. Ad esempio:
79 -
80 -```javascript
81 - render: function() {
82 - return <input type="text" />;
83 - }
84 -```
85 -
86 -Questo visualizzerà un campo di input il cui valore iniziale è vuoto. Ciascun input dell'utente si rifletterà immediatamente nell'elemento visualizzato. Se desideri reagire ai cambiamenti del valore, puoi usare il gestore di eventi `onChange` proprio come con i componenti controllati.
87 -
88 -### Valore Predefinito
89 -
90 -Se desideri inizializzare il componente con un valore non vuoto, puoi fornire una proprietà `defaultValue`. Ad esempio:
91 -
92 -```javascript
93 - render: function() {
94 - return <input type="text" defaultValue="Ciao!" />;
95 - }
96 -```
97 -
98 -Questo esempio funzionerà in maniera simile all'esempio precedente sui **Componenti Controllati**.
99 -
100 -Similmente, `<input>` supporta `defaultChecked` e `<select>` supporta `defaultValue`.
101 -
102 -> Nota:
103 ->
104 -> Le proprietà `defaultValue` e `defaultChecked` sono usate soltanto durante il rendering iniziale. Se devi aggiornare il valore in un rendering successivo, dovrai usare un [componente controllato](#controlled-components).
105 -
106 -
107 -## Argomenti Avanzati
108 -
109 -
110 -### Perché Componenti Controllati?
111 -
112 -Usare componenti di moduli come `<input>` in React presenta una difficoltà aggiuntiva, assente quando si scrive un modulo tradizionale in HTML. Ad esempio, in HTML:
113 -
114 -```html
115 - <input type="text" name="title" value="Senza titolo" />
116 -```
117 -
118 -Questo visualizza un campo di input *inizializzato* con il valore `Senza titolo`. Quando l'utente modifica il campo, la *proprietà* `value` del nodo cambierà. Tuttavia, `node.getAttribute('value')` restituirà ancora il valore usato durante l'inizializzazione, `Senza titolo`.
119 -
120 -Diversamente dall'HTML, i componenti React devono rappresentare lo stato della vista in ciascun momento e non soltanto durante l'inizializzazione. Ad esempio, in React:
121 -
122 -```javascript
123 - render: function() {
124 - return <input type="text" name="title" value="Senza titolo" />;
125 - }
126 -```
127 -
128 -Dal momento che questo metodo descrive la vista in ogni momento, il valore del campo di testo deve *sempre* essere `Senza titolo`.
129 -
130 -
131 -### Perché il Valore della Textarea?
132 -
133 -In HTML, il valore di `<textarea>` è solitamente impostato usando un nodo di testo figlio:
134 -
135 -```html
136 - <!-- antipattern: NON FARLO! -->
137 - <textarea name="description">Questa è la descrizione.</textarea>
138 -```
139 -
140 -Per l'HTML, questo approccio permette agli sviluppatori di fornire facilmente valori su più righe. Tuttavia, dal momento che React è JavaScript, non abbiamo limitazioni sulle stringhe e possiamo usare `\n` se desideriamo andare a capo. In un mondo in cui abbiamo `value` e `defaultValue`, il ruolo giocato dal nodo figlio è ambiguo. Per questa ragione, non dovresti utilizzare il nodo figlio quando imposti il valore delle `<textarea>`:
141 -
142 -```javascript
143 - <textarea name="description" value="Questa è la descrizione." />
144 -```
145 -
146 -Se tuttavia decidi di *usare* il nodo di testo figlio, questo si comporterà come `defaultValue`.
147 -
148 -
149 -### Perché il Value di Select?
150 -
151 -L'elemento `<option>` selezionato in un elemento HTML `<select>` è normalmente specificato attraverso l'attributo `selected` dell'opzione stessa. In React, allo scopo di rendere i componenti più semplici da manipolare, viene invece adottato il formato seguente:
152 -
153 -```javascript
154 - <select value="B">
155 - <option value="A">Arancia</option>
156 - <option value="B">Banana</option>
157 - <option value="C">Ciliegia</option>
158 - </select>
159 -```
160 -
161 -Per creare un componente non controllato, viene invece usato `defaultValue`.
162 -
163 -> Nota:
164 ->
165 -> Puoi passare un array come valore dell'attributo `value`, se desideri selezionare più opzioni in un tag `select` a scelta multipla: `<select multiple={true} value={['B', 'C']}>`.
docs/docs/07-forms.ja-JP.md deleted
-150
@@ -1,150 +0,0 @@
1 ----
2 -id: forms
3 -title: フォーム
4 -permalink: docs/forms-ja-JP.html
5 -prev: transferring-props-ja-JP.html
6 -next: working-with-the-browser-ja-JP.html
7 ----
8 -
9 -`<input>` や `<textarea>` や `<option>` のようなフォームのコンポーネントはユーザの入力によって変化しうるので、他のネイティブのコンポーネントとは異なります。以下のコンポーネントは、ユーザの入力に返答することにおいて、フォームを操作することを簡単にするインターフェースを提供します。
10 -
11 -`<form>` のイベントについての情報は、[フォームのイベント](/react/docs/events.html#form-events)をご覧ください。
12 -
13 -## 双方向のprops
14 -
15 -以下のように、フォームのコンポーネントはユーザの入力に影響されるいくつかのpropsをサポートしています。
16 -
17 -* `value` は `<input>` と `<textarea>` コンポーネントにサポートされています。
18 -* `checked` は `<input>` コンポーネントの `checkbox` か `radio` タイプにサポートされています。
19 -* `selected` は `<option>` コンポーネントにサポートされています。
20 -
21 -HTMLでは、 `<textarea>` の値は子要素によってセットされます。Reactでは、 `value` を代わりに使うべきです。
22 -
23 -フォームコンポーネントは `onChange` propにコールバックをセットすることで変更を検知することを可能にします。`onChange` propはブラウザ上で、ユーザの入力に返答する際に発火するために動きます。それは以下のようなタイミングです。
24 -
25 -* `<input>` か `<textarea>` の `value` が変わる時。
26 -* `<input>` の `checked` ステータスが変わる時。
27 -* `<option>` の `selected` ステータスが変わる時。
28 -
29 -全てのDOMのイベントのように、 `onChange` propは全てのネイティブのコンポーネントにサポートされており、何度も発生するチェンジイベントを検知するのに使われることもあります。
30 -
31 -> 注意:
32 -> `<input>` と `<textarea>` にとって、 `onChange` は DOMのビルトインの [`oninput`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput) イベントハンドラの代替のものです。そして、一般的に、代わりに使われています。
33 -
34 -## 制御されたコンポーネント
35 -
36 -`<input>` と `value` のセットは *制御された* コンポーネントです。制御された `<input>` では、レンダリングされた要素の値は、常に `value` propを反映します。例えば、
37 -
38 -```javascript
39 - render: function() {
40 - return <input type="text" value="Hello!" />;
41 - }
42 -```
43 -
44 -上記は、常に `Hello!` という値を持つinputをレンダリングするでしょう。ユーザのinputはレンダリングされた要素に何も影響を与えないでしょう。なぜなら、Reactが、値が `Hello!` になるように宣言しているからです。ユーザのinputに返答する形で値を更新したいなら、以下のように `onChange` イベントが使用できます。
45 -
46 -```javascript
47 - getInitialState: function() {
48 - return {value: 'Hello!'};
49 - },
50 - handleChange: function(event) {
51 - this.setState({value: event.target.value});
52 - },
53 - render: function() {
54 - var value = this.state.value;
55 - return <input type="text" value={value} onChange={this.handleChange} />;
56 - }
57 -```
58 -
59 -この例では、ユーザから提供された、最新の値を単純に受け入れ `<input>` コンポーネントの `value` propを更新します。 このパターンはユーザの入力に返答したり、バリデーションしたりするインターフェースを実行することを簡単にします。例えば、
60 -
61 -```javascript
62 - handleChange: function(event) {
63 - this.setState({value: event.target.value.substr(0, 140)});
64 - }
65 -```
66 -
67 -上記はユーザのinputを受け入れますが、値を最初の140字に切り取ります。
68 -
69 -
70 -## 制御されないコンポーネント
71 -
72 -`value` を与えられていない(もしくは `null` がセットされている) `<input>` は *制御されない* コンポーネントです。制御されない `<input>` では、レンダリングされた要素の値はユーザのinputを反映します。例えば、
73 -
74 -```javascript
75 - render: function() {
76 - return <input type="text" />;
77 - }
78 -```
79 -
80 -上記は、空の値で最初は始まるinputをレンダリングします。どのようなユーザのinputも即座にレンダリングされた要素によって反映されます。値の更新を検知したいなら、 `onChange` イベントを、制御されたコンポーネントと同様に使用することができます。
81 -
82 -コンポーネントを空ではない値で初期化したいなら、 `defaultValue` propを提供することができます。例えば、
83 -
84 -```javascript
85 - render: function() {
86 - return <input type="text" defaultValue="Hello!" />;
87 - }
88 -```
89 -
90 -この例は、上記の **制御されたコンポーネント** の例と同じように動くでしょう。
91 -
92 -同様に、 `<input>` は `defaultChecked` をサポートし、 `<select>` は `defaultValue` をサポートします。
93 -
94 -## 高度なトピック
95 -
96 -
97 -### なぜコントロールされたコンポーネントを使うのでしょうか?
98 -
99 -`<input>` のようなフォームのコンポーネントをReactで使うことは、伝統的なHTMLのフォームを書いた時には無視される表現であることを表します。例えば、HTMLでは、
100 -
101 -```html
102 - <input type="text" name="title" value="Untitled" />
103 -```
104 -
105 -上記は、 `Untitled` という値で *初期化* されたinputをレンダリングします。ユーザがinputを更新する時、ノードの `value` *プロパティ* が変更されるでしょう。しかし、 `node.getAttribute('value')` は初期化の際に使用された値である `Untitled` をまだリターンします。
106 -
107 -HTMLと違って、Reactのコンポーネントは初期化の時だけではなく、いつでもビューのステータスを再度表示しなくてはなりません。例えば、Reactでは、
108 -
109 -```javascript
110 - render: function() {
111 - return <input type="text" name="title" value="Untitled" />;
112 - }
113 -```
114 -
115 -このメソッドがいつでもビューを描画するので、次のテキストの入力の値は *常に* `Untitled` になります。
116 -
117 -
118 -### なぜテキストエリアの値を使うのでしょうか?
119 -
120 -HTMLでは、 `<textarea>` の値は普通、以下のようにその子要素を使うことでセットされます。
121 -
122 -```html
123 - <!-- 反例: このようにはしないでください! -->
124 - <textarea name="description">This is the description.</textarea>
125 -```
126 -
127 -HTMLでは、開発者は簡単に複数行に渡る値を提供できます。しかし、ReactがJavaScriptであるので、文字列の制限を私たちは持っておらず、改行をしたい場合は `\n` を使えます。 `value` と `defaultValue` を私たちが持っている世界では、子要素が果たす役割は曖昧になっています。この理由から、以下のように `<textarea>` の値をセットする際には子要素を使うべきではありません。
128 -
129 -```javascript
130 - <textarea name="description" value="This is a description." />
131 -```
132 -
133 -子要素を使うことを *決めた* 場合は、 `defaultValue` と同様の動きをします。
134 -
135 -### なぜセレクトバリューを使うのでしょうか?
136 -
137 -HTMLの `<select>` の選択された `<option>` は、普通はオプションの `selected` 属性によって指定されます。Reactでは、コンポーネントの操作を簡単にするために、以下のようなフォーマットが代わりに適用されます。
138 -
139 -```javascript
140 - <select value="B">
141 - <option value="A">Apple</option>
142 - <option value="B">Banana</option>
143 - <option value="C">Cranberry</option>
144 - </select>
145 -```
146 -
147 -制御されないコンポーネントを作成するために、 `defaultValue` が代わりに使われます。
148 -
149 -> 注意:
150 -> 配列を `value` 属性の中に渡すことができます。これで、以下のように、 `select` タグの中で複数のオプションを選択することができます。 `<select multiple={true} value={['B', 'C']}>`
docs/docs/07-forms.ko-KR.md deleted
-159
@@ -1,159 +0,0 @@
1 ----
2 -id: forms-ko-KR
3 -title: 폼
4 -permalink: docs/forms-ko-KR.html
5 -prev: transferring-props-ko-KR.html
6 -next: working-with-the-browser-ko-KR.html
7 ----
8 -
9 -`<input>`, `<textarea>`, `<option>` 같은 폼 컴포넌트는 다른 네이티브 컴포넌트와 다릅니다. 왜냐하면, 사용자의 상호작용에 의해 변경될 수 있기 때문이죠. 이런 컴포넌트들은 사용자의 상호작용에 반응하여 폼을 더 쉽게 관리할 수 있도록 인터페이스를 제공합니다.
10 -
11 -`<form>` 이벤트에 관한 정보는 [폼 이벤트](/react/docs/events-ko-KR.html#폼-이벤트)를 보세요.
12 -
13 -## Props의 상호작용
14 -
15 -폼 컴포넌트는 사용자 상호작용을 통해 영향을 받는 몇 가지 props를 지원합니다.
16 -
17 -* `value`: `<input>`, `<textarea>` 컴포넌트에서 사용가능.
18 -* `checked`: `checkbox`, `radio`타입의 `<input>` 컴포넌트에서 사용가능.
19 -* `selected`: `<option>` 컴포넌트에서 사용가능.
20 -
21 -HTML에서는 `<textarea>` 태그의 값을 설정할 때 `<textarea>` 태그의 자식이 사용되지만, React에서는 `value` 를 사용해야 합니다.
22 -
23 -폼 컴포넌트는 `onChange` prop의 콜백을 설정하여 변경을 감시(listening)할 수 있습니다. `onChange` prop는 브라우저에 관계없이 다음과 같은 사용자 상호작용에 반응합니다.
24 -
25 -* `<input>`, `<textarea>`의 `value` 변경.
26 -* `<input>`의 `checked` state 변경.
27 -* `<option>`의 `selected` state 변경.
28 -
29 -모든 DOM 이벤트처럼 `onChange` prop은 모든 네이티브 컴포넌트에서 지원되며 일어난(bubbled) 변경 이벤트를 감시하는데 사용할 수 있습니다.
30 -
31 -> 주의:
32 ->
33 -> `<input>`, `<textarea>`에서는 `onChange`가 DOM의 [`oninput`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput) 이벤트 핸들러와 같은 기능을 제공하므로 일반적인 경우에는 `onChange`를 사용하세요.
34 -
35 -## 제어되는(controlled) 컴포넌트
36 -
37 -`value`가 설정된 `<input>`은 *제어되는* 컴포넌트입니다. 제어되는 `<input>`에서, 렌더 엘리먼트의 값은 항상 `value` prop을 반영합니다. 예를 들어,
38 -
39 -```javascript
40 - render: function() {
41 - return <input type="text" value="Hello!" />;
42 - }
43 -```
44 -
45 -이것은 항상 `Hello!`의 값을 가지는 input을 렌더합니다. 어떤 사용자 입력도 렌더된 엘리먼트에는 영향을 주지 않는데, 왜냐하면 React가 값을 `Hello!`로 설정했기 때문입니다. 사용자 입력에 따라 값을 업데이트하길 원한다면, `onChange` 이벤트를 사용할 수 있습니다.
46 -
47 -```javascript
48 - getInitialState: function() {
49 - return {value: 'Hello!'};
50 - },
51 - handleChange: function(event) {
52 - this.setState({value: event.target.value});
53 - },
54 - render: function() {
55 - var value = this.state.value;
56 - return <input type="text" value={value} onChange={this.handleChange} />;
57 - }
58 -```
59 -
60 -이 예제에서는, 단순히 사용자가 주는 최신값을 받고 `<input>` 컴포넌트의 `value` prop을 업데이트하고 있습니다. 이 패턴은 사용자의 상호작용에 반응하거나 검증하는 인터페이스를 쉽게 구현하게 합니다. 예를 들어,
61 -
62 -```javascript
63 - handleChange: function(event) {
64 - this.setState({value: event.target.value.substr(0, 140)});
65 - }
66 -```
67 -
68 -이것은 사용자 입력을 받아들이지만, 시작에서부터 140자로 값을 자릅니다.
69 -
70 -### 체크박스와 라디오 버튼의 잠재적인 문제
71 -
72 -변경 핸들링을 일반화하기 위해 React는 `change` 이벤트 대신에 `click` 이벤트를 사용하는 것에 주의하세요. `change` 핸들러 안에서 `preventDefault`를 호출하는 경우를 제외하고 이 동작은 예상대로 동작합니다. 이런 경우 `preventDefault`를 제거하거나, `setTimeout`에 `checked`의 전환을 넣어서 해결 가능합니다.
73 -
74 -## 제어되지 않는(Uncontrolled) 컴포넌트
75 -
76 -`value` 가 없(거나 `null`로 설정되어 있)는 `<input>`은 *제어되지 않는* 컴포넌트입니다. 제어되지 않는 `<input>`에서 렌더된 엘리먼트의 value값은 사용자의 입력을 반영합니다. 예를 들어,
77 -
78 -```javascript
79 - render: function() {
80 - return <input type="text" />;
81 - }
82 -```
83 -
84 -이것은 빈 값으로 시작되는 input을 렌더합니다. 임의의 사용자 입력은 즉시 렌더된 엘리먼트에 반영됩니다. 값의 업데이트를 감시하길 원한다면, 제어되는 컴포넌트처럼 `onChange` 이벤트를 사용할 수 있습니다.
85 -
86 -### 기본 값
87 -
88 -비어 있지 않은 값으로 초기화하길 원한다면, `defaultValue` prop로 할 수 있습니다. 예를 들어,
89 -
90 -```javascript
91 - render: function() {
92 - return <input type="text" defaultValue="Hello!" />;
93 - }
94 -```
95 -
96 -이 예제는 위에있는 **제어되지 않는 컴포넌트**에 더 가깝게 동작할 것입니다.
97 -
98 -마찬가지로, `<input>`은 `defaultChecked`를 지원하고 `<select>`는 `defaultValue`를 지원합니다.
99 -
100 -> 주의:
101 ->
102 -> `defaultValue`, `defaultChecked` prop은 최초 렌더에서만 사용됩니다. 뒤에 일어나는 렌더에서 값을 업데이트할 필요가 있다면, [제어되는(controlled) 컴포넌트](#제어되는controlled-컴포넌트)를 사용하셔야 합니다.
103 -
104 -## 심화 주제
105 -
106 -### 왜 제어되는 컴포넌트인가요?
107 -
108 -React에서 `<input>`같은 폼 컴포넌트를 사용하면, 전통적인 폼 HTML을 쓸 때에는 없던 어려운 문제가 있습니다. 예를 들어 HTML에서
109 -
110 -```html
111 - <input type="text" name="title" value="Untitled" />
112 -```
113 -
114 -이렇게 하면 input은 `Untitled` 값으로 *초기화* 됩니다. 사용자가 input을 업데이트할 때, 노드의 `value` *프로퍼티*가 변경될 것입니다. 하지만, `node.getAttribute('value')`은 여전히 초기화 때 사용했던 값인 `Untitled`를 리턴합니다.
115 -
116 -HTML과 다르게, React 컴포넌트는 초기화 시점 뿐만 아니라, 어떤 시점이라도 반드시 뷰의 state를 나타내야 합니다. 예를 들어 React에서
117 -
118 -```javascript
119 - render: function() {
120 - return <input type="text" name="title" value="Untitled" />;
121 - }
122 -```
123 -
124 -이 메소드가 어떤 시점에도 뷰를 기술하기 때문에, 텍스트 input의 값은 *언제나* `Untitled`입니다.
125 -
126 -### 왜 Textarea에 value를 사용하나요?
127 -
128 -HTML에서, `<textarea>`의 값은 보통 그것의 자식들로 설정됩니다.
129 -
130 -```html
131 - <!-- 안티패턴: 이렇게 하지 마세요! -->
132 - <textarea name="description">이것은 설명입니다.</textarea>
133 -```
134 -
135 -HTML에서는 이렇게 하면 여러 줄의 값을 쉽게 개발자가 넣을 수 있게 합니다. 하지만, React는 JavaScript기 때문에, 우리는 문자열 제한이 없고 개행이 필요하면 `\n`을 사용할 수 있습니다. 이 곳에서는 `value`와 `defaultValue`가 있고, 그것이 자식들의 역할을 모호하게 합니다. 이런 이유로, `<textarea>`의 값을 설정할 때에는 자식들을 사용하지 않아야 합니다.
136 -
137 -```javascript
138 - <textarea name="description" value="이것은 설명입니다." />
139 -```
140 -
141 -자식들을 사용하기로 *했다면*, 자식들은 `defaultValue`처럼 동작할 것입니다.
142 -
143 -### 왜 Select에 value를 사용하나요?
144 -
145 -HTML `<select>`에서 선택된 `<option>`은 보통 option의 `selected` 어트리뷰트로 기술됩니다. React에서는 컴포넌트를 관리하기 쉽게 하기 위해, 다음 형식이 대신 채용됐습니다.
146 -
147 -```javascript
148 - <select value="B">
149 - <option value="A">Apple</option>
150 - <option value="B">Banana</option>
151 - <option value="C">Cranberry</option>
152 - </select>
153 -```
154 -
155 -제어되지 않는 컴포넌트로 만드려면, 대신 `defaultValue`를 사용하세요.
156 -
157 -> 주의:
158 ->
159 -> `select` 태그에 여러 옵션을 선택할 수 있도록, `value` 어트리뷰트에 배열을 넘길 수도 있습니다. `<select multiple={true} value={['B', 'C']}>`
docs/docs/07-forms.md deleted
-179
@@ -1,179 +0,0 @@
1 ----
2 -id: forms
3 -title: Forms
4 -permalink: docs/forms.html
5 -prev: transferring-props.html
6 -next: working-with-the-browser.html
7 ----
8 -
9 -Form components such as `<input>`, `<textarea>`, and `<option>` differ from other native components because they can be mutated via user interactions. These components provide interfaces that make it easier to manage forms in response to user interactions.
10 -
11 -For information on events on `<form>` see [Form Events](/react/docs/events.html#form-events).
12 -
13 -## Interactive Props
14 -
15 -Form components support a few props that are affected via user interactions:
16 -
17 -* `value`, supported by `<input>` and `<textarea>` components.
18 -* `checked`, supported by `<input>` components of type `checkbox` or `radio`.
19 -* `selected`, supported by `<option>` components.
20 -
21 -In HTML, the value of `<textarea>` is set via children. In React, you should use `value` instead.
22 -
23 -Form components allow listening for changes by setting a callback to the `onChange` prop. The `onChange` prop works across browsers to fire in response to user interactions when:
24 -
25 -* The `value` of `<input>` or `<textarea>` changes.
26 -* The `checked` state of `<input>` changes.
27 -* The `selected` state of `<option>` changes.
28 -
29 -Like all DOM events, the `onChange` prop is supported on all native components and can be used to listen to bubbled change events.
30 -
31 -> Note:
32 ->
33 -> For `<input>` and `<textarea>`, `onChange` supersedes — and should generally be used instead of — the DOM's built-in [`oninput`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput) event handler.
34 -
35 -## Controlled Components
36 -
37 -A **controlled** `<input>` has a `value` prop. Rendering a controlled `<input>` will reflect the value of the `value` prop.
38 -
39 -```javascript
40 - render() {
41 - return <input type="text" value="Hello!" />;
42 - }
43 -```
44 -
45 -User input will have no effect on the rendered element because React has declared the value to be `Hello!`. To update the value in response to user input, you could use the `onChange` event:
46 -
47 -```javascript
48 -class MyForm extends React.Component {
49 - constructor(props) {
50 - super(props);
51 - this.state = {value: 'Hello!'};
52 - this.handleChange = this.handleChange.bind(this);
53 - }
54 -
55 - handleChange(event) {
56 - this.setState({value: event.target.value});
57 - }
58 -
59 - render() {
60 - return (
61 - <input
62 - type="text"
63 - value={this.state.value}
64 - onChange={this.handleChange}
65 - />
66 - );
67 - }
68 -}
69 -```
70 -
71 -In this example, we are accepting the value provided by the user and updating the `value` prop of the `<input>` component. This pattern makes it easy to implement interfaces that respond to or validate user interactions. For example:
72 -
73 -```javascript
74 - handleChange(event) {
75 - this.setState({value: event.target.value.substr(0, 140)});
76 - }
77 -```
78 -
79 -This would accept user input and truncate the value to the first 140 characters.
80 -
81 -A **Controlled** component does not maintain its own internal state; the component renders purely based on props.
82 -
83 -### Potential Issues With Checkboxes and Radio Buttons
84 -
85 -Be aware that, in an attempt to normalize change handling for checkbox and radio inputs, React uses a `click` event in place of a `change` event. For the most part this behaves as expected, except when calling `preventDefault` in a `change` handler. `preventDefault` stops the browser from visually updating the input, even if `checked` gets toggled. This can be worked around either by removing the call to `preventDefault`, or putting the toggle of `checked` in a `setTimeout`.
86 -
87 -## Uncontrolled Components
88 -
89 -An `<input>` without a `value` property is an *uncontrolled* component:
90 -
91 -```javascript
92 - render() {
93 - return <input type="text" />;
94 - }
95 -```
96 -
97 -This will render an input that starts off with an empty value. Any user input will be immediately reflected by the rendered element. If you wanted to listen to updates to the value, you could use the `onChange` event just like you can with controlled components.
98 -
99 -An **uncontrolled** component maintains its own internal state.
100 -
101 -### Default Value
102 -
103 -If you want to initialize the component with a non-empty value, you can supply a `defaultValue` prop. For example:
104 -
105 -```javascript
106 - render() {
107 - return <input type="text" defaultValue="Hello!" />;
108 - }
109 -```
110 -
111 -This example will function much like the **Controlled Components** example above.
112 -
113 -Likewise, `<input type="checkbox">` and `<input type="radio">` support `defaultChecked`, and `<select>` supports `defaultValue`.
114 -
115 -> Note:
116 ->
117 -> The `defaultValue` and `defaultChecked` props are only used during initial render. If you need to update the value in a subsequent render, you will need to use a [controlled component](#controlled-components).
118 -
119 -## Advanced Topics
120 -
121 -### Why Controlled Components?
122 -
123 -Using form components such as `<input>` in React presents a challenge that is absent when writing traditional form HTML. For example, in HTML:
124 -
125 -```html
126 - <input type="text" name="title" value="Untitled" />
127 -```
128 -
129 -This renders an input *initialized* with the value, `Untitled`. When the user updates the input, the node's `value` *property* will change. However, `node.getAttribute('value')` will still return the value used at initialization time, `Untitled`.
130 -
131 -Unlike HTML, React components must represent the state of the view at any point in time and not only at initialization time. For example, in React:
132 -
133 -```javascript
134 - render() {
135 - return <input type="text" name="title" value="Untitled" />;
136 - }
137 -```
138 -
139 -Since this method describes the view at any point in time, the value of the text input should *always* be `Untitled`.
140 -
141 -### Why Textarea Value?
142 -
143 -In HTML, the value of `<textarea>` is usually set using its children:
144 -
145 -```html
146 - <!-- antipattern: DO NOT DO THIS! -->
147 - <textarea name="description">This is the description.</textarea>
148 -```
149 -
150 -For HTML, this easily allows developers to supply multiline values. However, since React is JavaScript, we do not have string limitations and can use `\n` if we want newlines. In a world where we have `value` and `defaultValue`, it is ambiguous what role children play. For this reason, you should not use children when setting `<textarea>` values:
151 -
152 -```javascript
153 - <textarea name="description" value="This is a description." />
154 -```
155 -
156 -If you *do* decide to use children, they will behave like `defaultValue`.
157 -
158 -### Why Select Value?
159 -
160 -The selected `<option>` in an HTML `<select>` is normally specified through that option's `selected` attribute. In React, in order to make components easier to manipulate, the following format is adopted instead:
161 -
162 -```javascript
163 - <select value="B">
164 - <option value="A">Apple</option>
165 - <option value="B">Banana</option>
166 - <option value="C">Cranberry</option>
167 - </select>
168 -```
169 -
170 -To make an uncontrolled component, `defaultValue` is used instead.
171 -
172 -> Note:
173 ->
174 -> You can pass an array into the `value` attribute, allowing you to select multiple options in a `select` tag: `<select multiple={true} value={['B', 'C']}>`.
175 -
176 -### Imperative operations
177 -
178 -If you need to imperatively perform an operation, you have to obtain a [reference to the DOM node](/react/docs/more-about-refs.html#the-ref-callback-attribute).
179 -For instance, if you want to imperatively submit a form, one approach would be to attach a `ref` to the `form` element and manually call `form.submit()`.
docs/docs/07-forms.zh-CN.md deleted
-168
@@ -1,168 +0,0 @@
1 ----
2 -id: forms-zh-CN
3 -title: 表单组件
4 -permalink: docs/forms-zh-CN.html
5 -prev: transferring-props-zh-CN.html
6 -next: working-with-the-browser-zh-CN.html
7 ----
8 -
9 -诸如 `<input>`、`<textarea>`、`<option>` 这样的表单组件不同于其他原生组件,因为他们可以通过用户交互发生变化。这些组件提供的界面使响应用户交互的表单数据处理更加容易。
10 -
11 -关于 `<form>` 事件详情请查看 [表单事件](/react/docs/events-zh-CN.html#表单事件)。
12 -
13 -## 交互属性
14 -
15 -表单组件支持几个受用户交互影响的属性:
16 -
17 -* `value`,用于 `<input>`、`<textarea>` 组件。
18 -* `checked`,用于类型为 `checkbox` 或者 `radio` 的 `<input>` 组件。
19 -* `selected`,用于 `<option>` 组件。
20 -
21 -在 HTML 中,`<textarea>` 的值通过子节点设置;在 React 中则应该使用 `value` 代替。
22 -
23 -表单组件可以通过 `onChange` 回调函数来监听组件变化。当用户做出以下交互时,`onChange` 执行并通过浏览器做出响应:
24 -
25 -* `<input>` 或 `<textarea>` 的 `value` 发生变化时。
26 -* `<input>` 的 `checked` 状态改变时。
27 -* `<option>` 的 `selected` 状态改变时。
28 -
29 -和所有 DOM 事件一样,所有的 HTML 原生组件都支持 `onChange` 属性,而且可以用来监听冒泡的 `change` 事件。
30 -
31 -> 注意:
32 ->
33 -> 对于 `<input>` and `<textarea>`, `onChange` 取代 — 一般应该用来替代 — DOM内建的 [`oninput`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput) 事件处理。
34 -
35 -## 受控组件
36 -
37 -一个*受控*的 `<input>` 有一个 `value` prop。渲染一个受控 `<input>` 会反映 `value` prop 的值。
38 -
39 -```javascript
40 - render: function() {
41 - return <input type="text" value="Hello!" />;
42 - }
43 -```
44 -
45 -用户输入在被渲染的元素里将没有作用,因为 React 已经声明值为 `Hello!`。要更新 value 来响应用户输入,你可以使用 `onChange` 事件:
46 -
47 -```javascript
48 - getInitialState: function() {
49 - return {value: 'Hello!'};
50 - },
51 - handleChange: function(event) {
52 - this.setState({value: event.target.value});
53 - },
54 - render: function() {
55 - return (
56 - <input
57 - type="text"
58 - value={this.state.value}
59 - onChange={this.handleChange}
60 - />
61 - );
62 - }
63 -```
64 -
65 -在这个例子中,我们接受用户提供的值并更新 `<input>` 组件的 `value` prop。这个模式使实现响应或者验证用户输入的界面更容易。例如:
66 -
67 -```javascript
68 - handleChange: function(event) {
69 - this.setState({value: event.target.value.substr(0, 140)});
70 - }
71 -```
72 -
73 -上面的代码接受用户输入,并截取前 140 个字符。
74 -
75 -受控组件不维持一个自己的内部状态;它单纯的基于 props 渲染。
76 -
77 -### 复选框与单选按钮的潜在问题
78 -
79 -当心,在力图标准化复选框与单选按钮的变换处理中,React使用 `click` 事件代替 `change` 事件。在大多数情况下它们表现的如同预期,除了在`change` handler中调用`preventDefault` 。`preventDefault` 阻止了浏览器视觉上更新输入,即使`checked`被触发。变通的方式是要么移除`preventDefault`的调用,要么把`checked` 的触发放在一个`setTimeout`里。
80 -
81 -## 不受控组件
82 -
83 -一个没有 `value` 属性的 `<input>` 是一个不*受控*组件:
84 -
85 -```javascript
86 - render: function() {
87 - return <input type="text" />;
88 - }
89 -```
90 -
91 -上面的代码将渲染出一个空值的输入框,用户输入将立即反应到元素上。和受控元素一样,使用 `onChange` 事件可以监听值的变化。
92 -
93 -*不受控*组件维持它自己的内部状态。
94 -
95 -### 默认值
96 -
97 -如果想给组件设置一个非空的初始值,可以使用 `defaultValue` 属性。例如:
98 -
99 -```javascript
100 - render: function() {
101 - return <input type="text" defaultValue="Hello!" />;
102 - }
103 -```
104 -
105 -这个例子会像上面的 **受控组件** 例子一样运行。
106 -
107 -同样的, `<input type="checkbox">` 和 `<input type="radio">` 支持 `defaultChecked` 、 `<select>` 支持 `defaultValue`.
108 -
109 -> 注意:
110 ->
111 -> `defaultValue` 和 `defaultChecked` props 只能在内部渲染时被使用。 如果你需要在随后的渲染更新值, 你需要使用 [受控组件](#受控组件).
112 -
113 -## 高级主题
114 -
115 -### 为什么使用受控组件?
116 -
117 -在 React 中使用诸如 `<input>` 的表单组件时,遇到了一个在传统 HTML 中没有的挑战。比如下面的代码:
118 -
119 -```html
120 - <input type="text" name="title" value="Untitled" />
121 -```
122 -
123 -它渲染一个*初始值*为 `Untitled` 的输入框。当用户改变输入框的值时,节点的 `value` 属性( *property*)将随之变化,但是 `node.getAttribute('value')` 还是会返回初始设置的值 `Untitled`.
124 -
125 -与 HTML 不同,React 组件必须在任何时间点表现视图的状态,而不仅仅是在初始化时。比如在 React 中:
126 -
127 -```javascript
128 - render: function() {
129 - return <input type="text" name="title" value="Untitled" />;
130 - }
131 -```
132 -
133 -由于这个方法描述了在任意时间点上的视图,那么文本输入框的值就应该*始终*为 `Untitled`。
134 -
135 -### 为什么 `<textarea>` 使用 `value` 属性?
136 -
137 -在 HTML 中, `<textarea>` 的值通常使用子节点设置:
138 -
139 -```html
140 - <!-- 反例:在 React 中不要这样使用! -->
141 - <textarea name="description">This is the description.</textarea>
142 -```
143 -
144 -对 HTML 而言,让开发者设置多行的值很容易。但是,由于 React 是 JavaScript,没有字符串限制,可以使用 `\n` 实现换行。简言之,React 已经有 `value`、`defaultValue` 属性,`<textarea>` 组件的子节点扮演什么角色就有点模棱两可了。基于此, 设置 `<textarea>` 值时不应该使用子节点:
145 -
146 -```javascript
147 - <textarea name="description" value="This is a description." />
148 -```
149 -
150 -如果 *非要* 使用子节点,效果和使用 `defaultValue` 一样。
151 -
152 -### 为什么 `<select>` 使用 `value` 属性
153 -
154 -HTML 中 `<select>` 通常使用 `<option>` 的 `selected` 属性设置选中状态;React 为了更方便地控制组件,采用以下方式代替:
155 -
156 -```javascript
157 - <select value="B">
158 - <option value="A">Apple</option>
159 - <option value="B">Banana</option>
160 - <option value="C">Cranberry</option>
161 - </select>
162 -```
163 -
164 -如果是不受控组件,则使用 `defaultValue`。
165 -
166 -> 注意:
167 ->
168 -> 给 `value` 属性传递一个数组,可以选中多个选项:`<select multiple={true} value={['B', 'C']}>`。
docs/docs/08-working-with-the-browser.it-IT.md deleted
-109
@@ -1,109 +0,0 @@
1 ----
2 -id: working-with-the-browser-it-IT
3 -title: Lavorare con il Browser
4 -permalink: docs/working-with-the-browser-it-IT.html
5 -prev: forms-it-IT.html
6 -next: more-about-refs-it-IT.html
7 ----
8 -
9 -React offre potenti astrazioni che ti liberano in molti casi dal compito di manipolare direttamente il DOM, ma a volte potresti avere bisogno di accedere alle API sottostanti, ad esempio per lavorare con una libreria di terze parti o altro codice preesistente.
10 -
11 -
12 -## Il DOM Virtuale
13 -
14 -React è così veloce perché non interagisce direttamente con il DOM. React gestisce una rappresentazione veloce del DOM in memoria. I metodi `render()` restituiscono una *descrizione* del DOM, e React può confrontare questa descrizione con la rappresentazione in memoria per calcolare la maniera più veloce di aggiornare il browser.
15 -
16 -In aggiunta, React implementa un intero sistema di eventi sintetici che fa in modo che tutti gli oggetti evento siano conformi alle specifiche W3C nonostante le incompatibilità dei browser, e ciascun evento si propaga in maniera consistente ed efficiente in ogni browser. Puoi anche utilizzare alcuni eventi HTML5 in IE8!
17 -
18 -Nella maggior parte dei casi è sufficiente rimanere nel mondo del "browser fittizio" di React poiché più efficiente e facile da concepire. Tuttavia, a volte potresti aver bisogno di accedere alle API sottostanti, ad esempio per lavorare con una libreria di terze parti come un plugin jQuery. React fornisce convenienti vie di fuga perché tu possa utilizzare direttamente le API DOM sottostanti.
19 -
20 -
21 -## I Ref e findDOMNode()
22 -
23 -Per interagire con il browser, avrai bisogno di un riferimento a un nodo DOM. Puoi assegnare un attributo `ref` a ciascun elemento, ciò ti permette di fare riferimento all'**istanza di supporto** del componente. Questo è utile se devi invocare funzioni imperative sul componente, oppure desideri accedere ai nodi DOM sottostanti. Per saperne di piu sui ref, incluso la maniera di usarli con efficacia, leggi la nostra documentazione [riferimenti a componenti](/react/docs/more-about-refs-it-IT.html).
24 -
25 -
26 -## Ciclo di Vita del Componente
27 -
28 -I componenti hanno tree fasi principali del ciclo di vita:
29 -
30 -* **Montaggio:** Un componente sta venendo inserito nel DOM.
31 -* **Aggiornamento:** Viene effettuato nuovamente il rendering del componente per determinare se il DOM vada aggiornato.
32 -* **Smontaggio:** Un componente sta venendo rimosso dal DOM.
33 -
34 -React offre metodi del ciclo di vita che puoi specificare per inserirti in questo processo. Offriamo dei metodi il cui nome inizia per **will**, chiamati immediatamente prima che qualcosa accada, o per **did** che sono chiamati immediatamente dopo che qualcosa è accaduto.
35 -
36 -
37 -### Montaggio
38 -
39 -* `getInitialState(): object` è invocato prima che un componente viene montato. Componenti dotati di stato dovrebbero implementare questo metodo e restituire lo stato iniziale.
40 -* `componentWillMount()` è invocato immediatamente prima che si effettui il montaggio.
41 -* `componentDidMount()` è invocato immediatamente dopo che il montaggio è avvenuto. L'inizializzazione che richiede l'esistenza di nodi DOM dovrebbe avvenire in questo metodo.
42 -
43 -
44 -### Aggiornamento
45 -
46 -* `componentWillReceiveProps(object nextProps)` è invocato quando un componente montato riceve nuove proprietà. Questo metodo dovrebbe essere utilizzato per confrontare `this.props` e `nextProps` per effettuare transizioni di stato utilizzando `this.setState()`.
47 -* `shouldComponentUpdate(object nextProps, object nextState): boolean` è invocato quando un componente decide se i cambiamenti debbano risultare in un aggiornamento del DOM. Implementa questo metodo come un'ottimizzazione per confrontare `this.props` con `nextProps` e `this.state` con `nextState`, e restituisci `false` se React debba rimandare l'aggiornamento.
48 -* `componentWillUpdate(object nextProps, object nextState)` è invocato immediatamente prima che l'aggiornamento avvenga. Non puoi chiamare `this.setState()` al suo interno.
49 -* `componentDidUpdate(object prevProps, object prevState)` è invocato immediatamente dopo che l'aggiornamento è avvenuto.
50 -
51 -
52 -### Smontaggio
53 -
54 -* `componentWillUnmount()` è invocato immediatamente prima che un componente venga smontato e distrutto. Puoi effettuare operazioni di pulizia al suo interno.
55 -
56 -
57 -### Metodi Montati
58 -
59 -Componenti compositi _montati_ supportano anche i seguenti metodi:
60 -
61 -* `findDOMNode(): DOMElement` può essere invocato su ciascun componente montato per ottenere un riferimento al suo nodo DOM.
62 -* `forceUpdate()` può essere invocato su ciascun componente montato quando si è certi che un aspetto interno del componente è cambiato senza usare `this.setState()`.
63 -
64 -
65 -## Supporto per i Browser e Polyfill
66 -
67 -A Facebook supportiamo vecchi browser, incluso IE8. Abbiamo impiegato per un lungo tempo i polyfill per consentirci di scrivere JS con un occhio al futuro. Ciò significa che non abbiamo una quantità di hack sparsi nel nostro codice e possiamo tuttavia aspettarci che il nostro codice "semplicemente funzioni". Ad esempio, anziché usare `+new Date()`, possiamo scrivere `Date.now()`. Dal momento che la versione open source di React è la stessa che usiamo internamente, vi abbiamo applicato la stessa filosofia di scrivere JS guardando avanti.
68 -
69 -In aggiunta a questa filosofia, abbiamo anche deciso, in qualità di autori di una libreria JS, non dovremmo fornire i polyfill assieme alla nostra libreria. Se ciascuna libreria facesse ciò, con buona probabilità invieresti lo stesso polyfill diverse volte, cosa che potrebbe risultare in una rilevante quantità di codice inutilizzato. Se il tuo prodotto deve supportare vecchi browser, con buona probabilità stai già usando qualcosa come [es5-shim](https://github.com/es-shims/es5-shim).
70 -
71 -
72 -### Polyfill Richiesti per Supportare Vecchi Browser
73 -
74 -`es5-shim.js` tratto da [es5-shim di kriskowal](https://github.com/es-shims/es5-shim) fornisce le seguenti API indispensabili a React:
75 -
76 -* `Array.isArray`
77 -* `Array.prototype.every`
78 -* `Array.prototype.forEach`
79 -* `Array.prototype.indexOf`
80 -* `Array.prototype.map`
81 -* `Date.now`
82 -* `Function.prototype.bind`
83 -* `Object.keys`
84 -* `String.prototype.split`
85 -* `String.prototype.trim`
86 -
87 -`es5-sham.js`, anch'esso tratto da [es5-shim di kriskowal](https://github.com/es-shims/es5-shim), provides the following that React needs:
88 -
89 -* `Object.create`
90 -* `Object.freeze`
91 -
92 -La build non minificata di React richiede le seguenti API tratte da [console-polyfill di paulmillr](https://github.com/paulmillr/console-polyfill).
93 -
94 -* `console.*`
95 -
96 -Quando si usano elementi HTML5 in IE8 incluso `<section>`, `<article>`, `<nav>`, `<header>` e `<footer>`, è inoltre necessario includere [html5shiv](https://github.com/aFarkas/html5shiv) o uno script equivalente.
97 -
98 -
99 -### Problemi Cross-browser
100 -
101 -Nonostante React sia molto buono ad astrarre le differenze tra browser, alcuni browser sono limitati o presentano comportamenti scorretti per i quali non abbiamo potuto trovare un rimedio.
102 -
103 -
104 -#### Evento onScroll su IE8
105 -
106 -Su IE8 l'evento `onScroll` non viene propagato, e IE8 non possiede una API per definire gestori di eventi nella fase di cattura dell'evento, con il risultato che React non ha alcun modo di reagire a questi eventi.
107 -Al momento i gestori di questo evento vengono ignorati su IE8.
108 -
109 -Leggi la issue [onScroll doesn't work in IE8](https://github.com/facebook/react/issues/631) su GitHub per maggiori informazioni.
docs/docs/08-working-with-the-browser.ja-JP.md deleted
-137
@@ -1,137 +0,0 @@
1 ----
2 -id: working-with-the-browser
3 -title: ブラウザと動くこと
4 -permalink: docs/working-with-the-browser-ja-JP.html
5 -prev: forms-ja-JP.html
6 -next: more-about-refs-ja-JP.html
7 ----
8 -
9 -Reactはほとんどのケースで、DOMを直接触ることからあなたを解放するパワフルな抽象性を提供します。しかし、単純に根本的なAPIにアクセスする必要がある場合もあります。サードパーティのライブラリや現存するコードと動かす必要があるかもしれません。
10 -
11 -## 仮想DOM
12 -
13 -ReactはDOMと直接対話を行わないため、とても速いです。Reactは速いメモリ上のDOMの表現を持っています。 `render()` メソッドはDOMの *記述* をリターンします。Reactはこの記述とメモリ上の表現のdiffをとることができ、ブラウザを更新する最速の方法を計算することができます。
14 -
15 -加えて、Reactはブラウザ依存があるにも関わらず、W3Cの使用に則っていると保証されているイベントオブジェクトのような、完全に合成されたイベントシステムを実行します。HTML5のイベントをIE8で使うこともできます!
16 -
17 -パフォーマンスが優れており、簡単であると思われるので、ほとんどの場合、Reactの「偽のブラウザ」を使うべきです。しかし、jQueryプラグインのようなサードパーティのライブラリと動かすかもしれません。基本的なAPIに単純にアクセスする必要がある時もあります。Reactは基本的なDOMのAPIを直接使うための脱出口を提供しています。
18 -
19 -## 参照とfindDOMNode()
20 -
21 -ブラウザと相互に影響するために、DOMノードへの参照が必要になるでしょう。ReactはコンポーネントのDOMノードへの参照を得ることができる `ReactDOM.findDOMNode(component)` 関数を持っています。
22 -
23 -> 注意:
24 -> `findDOMNode()` はマウントされたコンポーネントの上でのみ動きます(これは、DOMに配置されたコンポーネントという意味です)。まだマウントされていない(まだ作成されていないコンポーネントの上で `render()` の `findDOMNode()` を呼ぶようなものです)コンポーネントの上でこれを呼ぼうとした場合、例外がスローされます。
25 -
26 -Reactのコンポーネントへの参照を得るためには、現在のReactコンポーネントを得るために `this` を使ったり、あなたがオーナーのコンポーネントを表す参照を使ったりできます。それらは、以下のように動きます。
27 -
28 -```javascript
29 -var MyComponent = React.createClass({
30 - handleClick: function() {
31 - // 生のDOMのAPIを使ってテキスト入力に明確にフォーカスします。
32 - ReactDOM.findDOMNode(this.refs.myTextInput).focus();
33 - },
34 - render: function() {
35 - // この参照属性はコンポーネントがマウントされた時に、
36 - // this.refs のコンポーネントへの参照を追加します。
37 - return (
38 - <div>
39 - <input type="text" ref="myTextInput" />
40 - <input
41 - type="button"
42 - value="Focus the text input"
43 - onClick={this.handleClick}
44 - />
45 - </div>
46 - );
47 - }
48 -});
49 -
50 -ReactDOM.render(
51 - <MyComponent />,
52 - document.getElementById('example')
53 -);
54 -```
55 -
56 -
57 -## 参照に関しての詳細
58 -
59 -参照に関して、詳細に学ぶためと、効率的にそれらを使う方法については、[参照に関しての詳細](/react/docs/more-about-refs.html)ドキュメントを読んでください。
60 -
61 -
62 -## コンポーネントライフサイクル
63 -
64 -コンポーネントは以下のように、ライフサイクルの3つのパートを持っています
65 -
66 -* **マウンティング:** コンポーネントはDOMにインサートされます。
67 -* **アップデーティング:** DOMがアップデートする必要があるとき、コンポーネントを決定するために再度レンダリングされます。
68 -* * **アンマウンティング:** コンポーネントはDOMから削除されます。
69 -
70 -Reactは上記のプロセスになるように指定できるライフサイクルメソッドを提供します。私たちは何かが起こる直前に呼ばれる **未来の** メソッドと何かが起こった直後に呼ばれる **過去の** メソッドを使うことができます。
71 -
72 -### マウンティング
73 -
74 -* `getInitialState(): object` はコンポーネントがマウントされる前に実行されます。ステートフルなコンポーネントはこのメソッドをインプリメントする必要があり、最初のstateのデータをリターンする必要があります。
75 -* `componentWillMount()` はマウンティングが起きる直前に実行されます。
76 -* `componentDidMount()` はマウンティングが起きた直後に実行されます。DOMノードを必要とする初期化はここで行われるべきです。
77 -
78 -### アップデーティング
79 -
80 -* `componentWillReceiveProps(object nextProps)` はマウントされたコンポーネントが新しいpropsを受け取ったときに実行されます。このメソッドは `this.setState()` を使ったstateの変更を実行するために `this.props` と `nextProps` とを比較するのに使われるべきです。
81 -* `shouldComponentUpdate(object nextProps, object nextState): boolean` は何かしらの変更がDOMをアップデートしなければいけないかどうかコンポーネントが決めるときに実行されます。このメソッドを `this.props` と `nextProps` そして `this.state` と `nextState` の比較の最適化のために実行してください。そして、Reactがアップデートをスキップするべきときには `false` を返してください。
82 -* `componentWillUpdate(object nextProps, object nextState)` はアップデーティングが発生する直前に実行されます。ここで `this.setState()` を呼ぶことはできません。
83 -* `componentDidUpdate(object prevProps, object prevState)` はアップデーティングが発生した直後に実行されます。
84 -
85 -### アンマウンティング
86 -
87 -* `componentWillUnmount()` はコンポーネントがアンマウントされ、削除される直前に実行されます。クリーンアップはここで行われるべきです。
88 -
89 -### マウントのメソッド
90 -
91 -_マウントされた_ 複合的なコンポーネントも以下のようなメソッドをサポートします。
92 -
93 -* `findDOMNode(): DOMElement` はレンダリングされたDOMノードへの参照を得るために、どのマウントされたコンポーネントの上でも実行されます。
94 -* `forceUpdate()` は `this.setState()` を使うことなくコンポーネントのstateが変更された際にさらにその詳細について知るときにどのマウントされたコンポーネントの上でも実行されます。
95 -
96 -## ブラウザのサポートとポリフィル
97 -
98 -Facebookでは、IE8を含む古いブラウザをサポートしています。私たちは将来に向けたJSを書くことができるように、長い間ポリフィルを使ってきました。これは、私たちのコードベースにたくさんの処理が散らばり、「ただ動くだけの」コードであることを予想することしかできないことを意味します。例えば、 `+new Date()` を見る代わりに、 `Date.now()` と記述しています。オープンソースであるReactを私たちは内部で使っているので、将来に向けたJSを使うという哲学を持ち越しています。
99 -
100 -この哲学に加えて、私たちはJSのライブラリの作者として、ライブラリの一部としてポリフィルを含めるべきではないというスタンスをとっています。全てのライブラリがこのようなことを行ったなら、死んだコードの大きな塊になりうる同じポリフィルを何度も記述しなくてもよくなるでしょう。あなたのプロダクトが古いブラウザをサポートする必要があるなら、[es5-shim](https://github.com/es-shims/es5-shim)のようなものを使うことにチャンスがあるでしょう。
101 -
102 -### ポリフィルは古いブラウザをサポートする必要があります
103 -
104 -[kriskowal's es5-shim](https://github.com/es-shims/es5-shim) の `es5-shim.js` はReactが必要とする以下のようなものを提供します。
105 -
106 -* `Array.isArray`
107 -* `Array.prototype.every`
108 -* `Array.prototype.forEach`
109 -* `Array.prototype.indexOf`
110 -* `Array.prototype.map`
111 -* `Date.now`
112 -* `Function.prototype.bind`
113 -* `Object.keys`
114 -* `String.prototype.split`
115 -* `String.prototype.trim`
116 -
117 -[kriskowal's es5-shim](https://github.com/es-shims/es5-shim)の `es5-sham.js` もまたReactが必要とする以下のようなものを提供します。
118 -
119 -* `Object.create`
120 -* `Object.freeze`
121 -
122 -小さくされていないReactのビルドは[paulmillr's console-polyfill](https://github.com/paulmillr/console-polyfill)にある以下のようなものを必要とします。
123 -
124 -* `console.*`
125 -
126 -`<section>` 、 `<article>` 、 `<nav>` 、 `<header>` 、 `<footer>` を含むHTML5の要素をIE8で使うときには、[html5shiv](https://github.com/aFarkas/html5shiv)か、似たようなスクリプトをインクルードする必要があります。
127 -
128 -### クロスブラウザの問題
129 -
130 -Reactはブラウザ間の違いを抽象化することにおいてとても優れていますが、一時的な解決ができない、制限や独特な動作をするブラウザもあります。
131 -
132 -#### IE8のonScrollイベント
133 -
134 -IE8では `onScroll` イベントは発火せず、イベントのフェーズをキャプチャするハンドラを定義するAPIを持っていません。それは、Reactがそれらのイベントを検知する方法が無いということを意味します。現状、IE8ではこのイベントは無視されています。
135 -
136 -詳細な情報については、GitHubのイシューである[onScrollがIE8で動かない](https://github.com/facebook/react/issues/631)を参照してください。
137 -
docs/docs/08-working-with-the-browser.ko-KR.md deleted
-100
@@ -1,100 +0,0 @@
1 ----
2 -id: working-with-the-browser-ko-KR
3 -title: 브라우저에서의 동작
4 -permalink: docs/working-with-the-browser-ko-KR.html
5 -prev: forms-ko-KR.html
6 -next: more-about-refs-ko-KR.html
7 ----
8 -
9 -React는 대부분의 경우 직접 DOM을 다루지 않아도 될만큼 강력한 추상화를 제공합니다. 하지만 서드파티 라이브러리나 기존의 코드들을 다루다 보면 간혹 기저(underlying)의 API에 접근해야 할 때도 있습니다.
10 -
11 -
12 -## 가상의 DOM
13 -
14 -React는 DOM을 직접 다루지 않기 때문에 매우 빠릅니다. React는 메모리에(in-memory) DOM의 표상(representation)을 관리합니다. `render()` 메소드는 사실은 DOM의 *서술*를 반환하고, React는 이를 메모리에 있는 DOM의 표상과 비교해 가장 빠른 방식으로 계산해서 브라우저를 업데이트해 줍니다.
15 -
16 -게다가 React는 브라우저의 괴악함(quirks)에도 불구하고 모든 이벤트 객체가 W3C 명세를 보장하도록 통합적인 이벤트 시스템을 구현했습니다. 모든 것이 일관된 방식으로 일어나고(bubbles) 효율적으로 크로스 브라우징을 수행합니다. 심지어 IE8에서도 HTML5 이벤트를 사용할 수 있습니다!
17 -
18 -더 효율적이고 쉬우므로 대개의 경우 React의 "가짜 브라우저"를 이용해 작업을 하게 될 것입니다. 하지만 간혹 jQuery 플러그인 같은 서드파티 라이브러리를 다루다 보면 기저(underlying)의 API에 접근할 필요가 있을지도 모릅니다. React는 기저의 DOM API를 직접 다루는 회피방법을 제공합니다.
19 -
20 -
21 -## Refs와 findDOMNode()
22 -
23 -브라우저와 상호 작용하려면 DOM 노드에 대한 참조가 필요합니다. `ref`를 어떤 엘리먼트에도 붙일 수 있으며, 이를 통해 컴포넌트 **지원 인스턴스**를 참조 할 수 있습니다. 이는 컴포넌트에 필수 적인 기능을 호출할 때나 기저의 DOM 노드에 접근하고 싶을 때 유용합니다. [refs에서 컴포넌트로](/react/docs/more-about-refs-ko-KR.html) 문서에서 refs를 효율적으로 사용하는 법을 포함해 더 많은 내용을 익혀보세요.
24 -
25 -
26 -<a name="component-lifecycle"></a>
27 -## 컴포넌트 생명주기
28 -
29 -컴포넌트의 생명주기에는 세 가지 주요 부분이 있습니다:
30 -
31 -* **Mounting:** 컴포넌트가 DOM에 삽입되고 있습니다.
32 -* **Updating:** 컴포넌트가 DOM의 업데이트 여부를 결정하기 위해 다시 렌더링되고 있습니다.
33 -* **Unmounting:** 컴포넌트가 DOM에서 제거되고 있습니다.
34 -
35 -React는 이 프로세스에 훅을 지정할 수 있는 생명주기 메소드를 제공합니다. 발생 직전 시점을 위한 **will** 메소드, 발생 직후 시점을 위한 **did** 메소드가 있습니다.
36 -
37 -### Mounting
38 -
39 -* `getInitialState(): object`는 컴포넌트가 마운트되기 전에 호출됩니다. 상태기반 컴포넌트는 이를 구현하고 초기 상태 데이터를 리턴합니다.
40 -* `componentWillMount()`는 마운팅되기 직전에 호출됩니다.
41 -* `componentDidMount()`는 마운팅 직후 호출됩니다. 초기화에 필요한 DOM 노드는 이곳에 있어야 합니다.
42 -
43 -### Updating
44 -
45 -* `componentWillReceiveProps(object nextProps)`는 마운트된 컴포넌트가 새로운 props을 받을 때 호출됩니다. 이 메소드는 `this.props`와 `nextProps`을 비교하여 `this.setState()`를 사용해 상태 변환을 수행하는데 사용되야 합니다.
46 -* `shouldComponentUpdate(object nextProps, object nextState): boolean`는 컴포넌트가 어떤 변경이 DOM의 업데이트를 보증하는지 결정해야 할 때 호출됩니다. 최적화하려면, React가 업데이트를 무시해야할 때 `this.props`와 `nextProps`를, `this.state`와 `nextState`를 비교해 `false`를 리턴하면 됩니다.
47 -* `componentWillUpdate(object nextProps, object nextState)`는 업데이트가 발생하기 직전에 호출됩니다. 이 시점에는 `this.setState()`를 호출할 수 없습니다.
48 -* `componentDidUpdate(object prevProps, object prevState)`는 업데이트가 발생한 후 즉시 호출됩니다.
49 -
50 -### Unmounting
51 -
52 -* `componentWillUnmount()`는 컴포넌트가 언마운트되어 파괴되기 직전에 호출됩니다. 정리(Cleanup)는 여기서 처리해야 합니다.
53 -
54 -### Mounted 메소드
55 -
56 -_마운트된_ 합성 컴포넌트들은 다음과 같은 메소드를 지원합니다:
57 -
58 -* `component.forceUpdate()`는 `this.setState()`를 사용하지 않고 변경된 컴포넌트의 상태의 변경을 적용하고 싶을 때 마운트된 컴포넌트에서 사용할 수 있습니다.
59 -
60 -## 브라우저 지원과 Polyfill
61 -
62 -페이스북에서 우리는 IE8을 포함한 구식 브라우저를 지원합니다. 미래지향적인 JS를 작성할 수 있도록 우리는 polyfill을 오랫동안 써왔습니다. 이는 우리의 코드베이스에 구식 브라우저를 위한 코드뭉치를 흩뿌려 놓을 필요가 없으며 그럼에도 우리의 코드가 "잘 작동"할 것이라 예상할 수 있음을 의미합니다. 예를 들어, `+new Date()` 대신에 그냥 `Date.now()`를 사용할 수 있습니다. 오픈소스 React는 우리가 내부에서 사용하는것과 동일하기 때문에, 우리는 이를 통해 미래지향적인 JS를 사용하는 철학을 전달했습니다.
63 -
64 -그 철학에 더하여, 우리는 또한 JS 라이브러리의 저자로서 polyfill을 라이브러리에 포함해서 배포하지 않습니다. 만약 모든 라이브러리가 이런 짓을 하면, 같은 polyfill을 여러 번 내리게 되어 쓸모없이 크기만 차지하는 죽은 코드들을 만들 것 입니다. 당신의 제품이 구식 브라우저를 지원해야한다면, [es5-shim](https://github.com/es-shims/es5-shim) 같은 녀석을 사용할 기회가 있었을 겁니다.
65 -
66 -### Polyfill은 구식 브라우저를 지원하기 위해 필요하다
67 -
68 -[kriskowal's es5-shim](https://github.com/es-shims/es5-shim)의 `es5-shim.js`는 React에 필요한 다음의 기능을 제공합니다:
69 -
70 -* `Array.isArray`
71 -* `Array.prototype.every`
72 -* `Array.prototype.forEach`
73 -* `Array.prototype.indexOf`
74 -* `Array.prototype.map`
75 -* `Date.now`
76 -* `Function.prototype.bind`
77 -* `Object.keys`
78 -* `String.prototype.split`
79 -* `String.prototype.trim`
80 -
81 -[kriskowal's es5-shim](https://github.com/kriskowal/es5-shim)의 `es5-sham.js`는, React에 필요한 다음의 기능도 제공합니다:
82 -
83 -* `Object.create`
84 -* `Object.freeze`
85 -
86 -압축되지 않은 React 빌드는 [paulmillr의 console-polyfill](https://github.com/paulmillr/console-polyfill)에서 다음의 기능이 필요합니다.
87 -
88 -* `console.*`
89 -
90 -`<section>`, `<article>`, `<nav>`, `<header>`, `<footer>`등 HTML5 엘리먼트를 IE8에서 이용하려면 [html5shiv](https://github.com/aFarkas/html5shiv)같은 스크립트가 추가로 필요합니다.
91 -
92 -### 크로스 브라우징 이슈
93 -
94 -React가 브라우저별 차이점을 썩 잘 추상화하긴 했지만 일부는 한정적이거나 우리가 발견하지 못한 이상한(quirky) 동작을 보여주기도 합니다.
95 -
96 -#### IE8에서의 onScroll 이벤트
97 -
98 -IE8에서는 `onScroll` 이벤트가 일어나지(bubble) 않으며, IE8은 이벤트의 캡쳐링 단계를 위한 핸들러를 정의하는 API를 갖고 있지 않습니다. 이는 React가 이 이벤트를 이해(listen) 할 방법이 없음을 뜻합니다. 현재 이 이벤트 핸들러는 IE8에서 무시됩니다.
99 -
100 -더 많은 정보는 [onScroll doesn't work in IE8](https://github.com/facebook/react/issues/631) GitHub 이슈를 살펴보세요.
docs/docs/08-working-with-the-browser.md deleted
-60
@@ -1,60 +0,0 @@
1 ----
2 -id: working-with-the-browser
3 -title: Working With the Browser
4 -permalink: docs/working-with-the-browser.html
5 -prev: forms.html
6 -next: more-about-refs.html
7 ----
8 -
9 -React provides powerful abstractions that free you from touching the DOM directly in most cases, but sometimes you simply need to access the underlying API, perhaps to work with a third-party library or existing code.
10 -
11 -## The Virtual DOM
12 -
13 -React is very fast because it never talks to the DOM directly. React maintains a fast in-memory representation of the DOM. `render()` methods actually return a *description* of the DOM, and React can compare this description with the in-memory representation to compute the fastest way to update the browser.
14 -
15 -Additionally, React implements a full synthetic event system such that all event objects are guaranteed to conform to the W3C spec despite browser quirks, and everything bubbles consistently and efficiently across browsers. You can even use some HTML5 events in older browsers that don't ordinarily support them!
16 -
17 -Most of the time you should stay within React's "faked browser" world since it's more performant and easier to reason about. However, sometimes you simply need to access the underlying API, perhaps to work with a third-party library like a jQuery plugin. React provides escape hatches for you to use the underlying DOM API directly.
18 -
19 -## Refs and findDOMNode()
20 -
21 -To interact with the browser, you'll need a reference to a DOM node. You can attach a `ref` to any element, which allows you to reference the **backing instance** of the component. This is useful if you need to invoke imperative functions on the component, or want to access the underlying DOM nodes. To learn more about refs, including ways to use them effectively, see our [refs to components](/react/docs/more-about-refs.html) documentation.
22 -
23 -## Component Lifecycle
24 -
25 -Components have three main parts of their lifecycle:
26 -
27 -* **Mounting:** A component is being inserted into the DOM.
28 -* **Updating:** A component is being re-rendered to determine if the DOM should be updated.
29 -* **Unmounting:** A component is being removed from the DOM.
30 -
31 -React provides lifecycle methods that you can specify to hook into this process. We provide **will** methods, which are called right before something happens, and **did** methods which are called right after something happens.
32 -
33 -### Mounting
34 -
35 -* `getInitialState(): object` is invoked before a component is mounted. Stateful components should implement this and return the initial state data.
36 -* `componentWillMount()` is invoked immediately before mounting occurs.
37 -* `componentDidMount()` is invoked immediately after mounting occurs. Initialization that requires DOM nodes should go here.
38 -
39 -### Updating
40 -
41 -* `componentWillReceiveProps(object nextProps)` is invoked when a mounted component receives new props. This method should be used to compare `this.props` and `nextProps` to perform state transitions using `this.setState()`.
42 -* `shouldComponentUpdate(object nextProps, object nextState): boolean` is invoked when a component decides whether any changes warrant an update to the DOM. Implement this as an optimization to compare `this.props` with `nextProps` and `this.state` with `nextState` and return `false` if React should skip updating.
43 -* `componentWillUpdate(object nextProps, object nextState)` is invoked immediately before updating occurs. You cannot call `this.setState()` here.
44 -* `componentDidUpdate(object prevProps, object prevState)` is invoked immediately after updating occurs.
45 -
46 -### Unmounting
47 -
48 -* `componentWillUnmount()` is invoked immediately before a component is unmounted and destroyed. Cleanup should go here.
49 -
50 -### Mounted Methods
51 -
52 -_Mounted_ composite components also support the following method:
53 -
54 -* `component.forceUpdate()` can be invoked on any mounted component when you know that some deeper aspect of the component's state has changed without using `this.setState()`.
55 -
56 -## Browser Support
57 -
58 -React supports most popular browsers, including Internet Explorer 9 and above.
59 -
60 -(We don't support older browsers that don't support ES5 methods, but you may find that your apps do work in older browsers if polyfills such as [es5-shim and es5-sham](https://github.com/es-shims/es5-shim) are included in the page. You're on your own if you choose to take this path.)
docs/docs/08-working-with-the-browser.zh-CN.md deleted
-60
@@ -1,60 +0,0 @@
1 ----
2 -id: working-with-the-browser-zh-CN
3 -title: 与浏览器协作
4 -permalink: docs/working-with-the-browser-zh-CN.html
5 -prev: forms-zh-CN.html
6 -next: more-about-refs-zh-CN.html
7 ----
8 -
9 -React提供了强大的抽象机制使你在大多数情况下免于直接接触DOM,但有时你仅仅只需要访问底层API,也许是为了与第三方库或者已有的代码协作。
10 -
11 -## 虚拟 DOM
12 -
13 -React非常快速是因为它从不直接操作DOM。React维持了一个快速的内存中的DOM表示。`render()` 方法实际上返回一个对DOM的*描述*,然后React能将其与内存中的“描述”进行比较,以计算出最快速的方式更新浏览器。
14 -
15 -此外,React实现了一个完备的合成事件(synthetic event)系统,以使得所有的事件对象都被保证符合W3C细则,而不论各个浏览器的怪癖,并且所有事件跨浏览器地一致并高效的冒泡(bubbles),你甚至能在IE8里使用一些HTML5事件!
16 -
17 -大多数时间你应该和React的"伪造浏览器"呆在一起,因为它更高性能并且容易推理。然而,有时你只需要访问底层API,或许是为了与第三方库比如一个jQuery插件协作。React为你提供了安全舱口来直接使用底层API。
18 -
19 -## Refs 和 findDOMNode()
20 -
21 -为了与浏览器互动,你需要一个指向DOM node的引用。你可以连接一个 `ref` 到任何的元素,这允许你引用组件的 **backing instance** 。如果你需要在组件上调用命令式函数,或者想访问底层的DOM节点,它很有用。要了解更多关于 refs,包括更有效使用他们的方法,请查看我们的 [关于Refs的更多内容](/react/docs/more-about-refs-zh-CN.html) 文档。
22 -
23 -## 组件的生命周期
24 -
25 -组件的生命周期有三个主要部分:
26 -
27 -* **挂载:** 组件被注入DOM。
28 -* **更新:** 组件被重新渲染来决定DOM是否应被更新。
29 -* **卸载:** 组件从DOM中被移除。
30 -
31 -React提供生命周期方法,以便你可以指定钩挂到这个过程上。我们提供了 **will** 方法,该方法在某事发生前被调用,**did**方法,在某事发生后被调用。
32 -
33 -### 挂载
34 -
35 -* `getInitialState(): object` 在组件挂载前被调用。有状态组件(Stateful components) 应该实现此函数并返回初始state的数据。
36 -* `componentWillMount()` 在挂载发生前被立即调用。
37 -* `componentDidMount()` 在挂载发生后被立即调用。 需要DOM node的初始化应该放在这里。
38 -
39 -### 更新
40 -
41 -* `componentWillReceiveProps(object nextProps)` 当挂载的组件接收到新的props时被调用。此方法应该被用于比较`this.props` 和 `nextProps`以用于使用`this.setState()`执行状态转换。
42 -* `shouldComponentUpdate(object nextProps, object nextState): boolean` 当组件决定任何改变是否要更新到DOM时被调用。作为一个优化实现比较`this.props` 和 `nextProps` 、`this.state` 和 `nextState` ,如果React应该跳过更新,返回`false`。
43 -* `componentWillUpdate(object nextProps, object nextState)` 在更新发生前被立即调用。你不能在此调用`this.setState()`。
44 -* `componentDidUpdate(object prevProps, object prevState)` 在更新发生后被立即调用。
45 -
46 -### 卸载
47 -
48 -* `componentWillUnmount()` 在组件被卸载和摧毁前被立即调用。清理应该放在这里。
49 -
50 -### 已挂载的方法
51 -
52 -_Mounted_ 复合组件同样支持以下方法:
53 -
54 -* `component.forceUpdate()` 可以在任何已挂载的组件上调用,在你知道某些深处的组件状态在未使用 `this.setState()` 就被改变了时。
55 -
56 -## 浏览器支持
57 -
58 -React 支持绝大多数流行的浏览器,包括 Internet Explorer 9 及以上。
59 -
60 -(我们不支持那些不支持 ES5 methods 的更老的浏览器,但你可能发现如果你的页面包含了类似 [es5-shim and es5-sham](https://github.com/es-shims/es5-shim) 的填充物时是可以在更老的浏览器上运行的。是否做这一步取决于你自己。)
docs/docs/08.1-more-about-refs.it-IT.md deleted
-141
@@ -1,141 +0,0 @@
1 ----
2 -id: more-about-refs-it-IT
3 -title: Riferimenti ai Componenti
4 -permalink: docs/more-about-refs-it-IT.html
5 -prev: working-with-the-browser-it-IT.html
6 -next: tooling-integration-it-IT.html
7 ----
8 -Dopo aver costruito il tuo componente, potresti trovarti nella situazione di volere invocare dei metodi sulle istanze di componenti restituite da `render()`. Nella maggior parte dei casi, questo non è necessario poiché il flusso di dati reattivo assicura sempre che le proprietà più recenti siano assegnate a ciascun figlio prodotto da `render()`. Tuttavia, esistono dei casi in cui potrebbe essere necessario o desiderabile, quindi React fornisce una via d'uscita conosciuta come `refs`. Queste `refs` (riferimenti) sono particolarmente utili quando vuoi: trovare il markup DOM prodotto da un componente (ad esempio, per posizionarlo in modo assoluto), usare componenti React in una più ampia applicazione non-React, oppure effettuare la transizione del tuo codice a React.
9 -
10 -Vediamo come ottenere un ref, e quindi passiamo ad un esempio completo.
11 -
12 -## Il ref restituito da ReactDOM.render
13 -
14 -Da non confondersi con il metodo `render()` che definisci sul tuo componente (il quale restituisce un elemento DOM virtuale), [ReactDOM.render()](/react/docs/top-level-api-it-IT.html#reactdom.render) restituisce un riferimento all'**istanza di supporto** del tuo componente (o `null` per i [componenti privi di stato](/react/docs/reusable-components.html#stateless-functions)).
15 -
16 -
17 -```js
18 -var myComponent = ReactDOM.render(<MyComponent />, myContainer);
19 -```
20 -
21 -Tieni a mente, tuttavia, che JSX non restituisce un'istanza di un componente! È solo un **ReactElement**: una rappresentazione leggera che istruisce React su come il componente montato debba apparire.
22 -
23 -```js
24 -var myComponentElement = <MyComponent />; // Questo è un semplice ReactElement.
25 -
26 -// Qui va del codice...
27 -
28 -var myComponentInstance = ReactDOM.render(myComponentElement, myContainer);
29 -myComponentInstance.doSomething();
30 -```
31 -
32 -> Nota:
33 ->
34 -> Questo deve essere usato soltanto al livello più alto. All'interno dei componenti, lascia che i tuoi `props` e `state` gestiscano la comunicazione con i componenti figli, oppure utilizza uno degli altri metodi per ottenere un ref (attributo stringa o callback).
35 -
36 -
37 -## L'Attributo ref Come Callback
38 -
39 -React supporta un attributo speciale che puoi assegnare a qualsiasi componente. L'attributo `ref` può essere una funzione callback, che sarà eseguita immediatamente dopo che il componente viene montato. Il componente referenziato sarà passato come parametro, e la funzione callback può utilizzare il componente immediatamente, oppure conservarne un riferimento per un uso successivo, o entrambe.
40 -
41 -È semplice come aggiungere un attributo `ref` a qualsiasi cosa restituita da `render` usando una funzione freccia di ES6:
42 -
43 -```js
44 - render: function() {
45 - return (
46 - <TextInput
47 - ref={function(input) {
48 - if (input != null) {
49 - input.focus();
50 - }
51 - }} />
52 - );
53 - },
54 -```
55 -
56 -oppure usando una funzione freccia ES6:
57 -
58 -```js
59 - render: function() {
60 - return <TextInput ref={(c) => this._input = c} />;
61 - },
62 - componentDidMount: function() {
63 - this._input.focus();
64 - },
65 -```
66 -
67 -Nota che quando il componente referenziato viene smontato e quando il valore di ref cambia, ref sarà chiamata con `null` come argomento. Ciò impedisce i memory leak nel caso in cui l'istanza venga conservata, come nel primo esempio. Nota che quando assegni il valore di ref a un'espressione di funzione in linea come negli esempi precedenti, React vede un oggetto funzione diverso ogni volta e pertanto in occasione di ciascun aggiornamento, ref verrà chiamata con `null` immediatamente prima di essere chiamata con l'istanza del componente.
68 -
69 -Puoi accedere al nodo DOM del componente direttamente chiamando `ReactDOM.findDOMNode(argomentoDellaTuaCallback)`.
70 -
71 -
72 -## L'Attributo ref Come Stringa
73 -
74 -React supporta anche l'uso di una stringa (anziché una callback) come proprietà ref su qualsiasi componente, sebbene allo stato attuale questo approccio sia quasi esclusivamente superato.
75 -
76 -1. Assegna un attributo `ref` a qualsiasi cosa restituita da `render` come:
77 -
78 - ```html
79 - <input ref="myInput" />
80 - ```
81 -
82 -2. Altrove nel codice (tipicamente in un gestore di eventi), accedi all'**istanza di supporto** tramite `this.refs` come segue:
83 -
84 - ```javascript
85 - this.refs.myInput
86 - ```
87 -
88 - Puoi accedere direttamente al nodo DOM del componente chiamando `ReactDOM.findDOMNode(this.refs.myInput)`.
89 -
90 -
91 -## Un Esempio Completo
92 -Per ottenere un riferimento a un componente React, puoi usare `this` per ottenere il componente React attuale, oppure usare un ref per ottenere un riferimento a un componente di tua proprietà. Il funzionamento è il seguente:
93 -
94 -```javascript
95 -var MyComponent = React.createClass({
96 - handleClick: function() {
97 - // Assegna il focus esplicitamente al campo di testo usando l'API DOM nativa.
98 - this.myTextInput.focus();
99 - },
100 - render: function() {
101 - // L'attributo ref aggiunge un riferimento al componente a this.refs quando
102 - // il componente viene montato
103 - return (
104 - <div>
105 - <input type="text" ref={(ref) => this.myTextInput = ref} />
106 - <input
107 - type="button"
108 - value="Assegna il focus al campo di testo"
109 - onClick={this.handleClick}
110 - />
111 - </div>
112 - );
113 - }
114 -});
115 -
116 -ReactDOM.render(
117 - <MyComponent />,
118 - document.getElementById('example')
119 -);
120 -```
121 -
122 -In questo esempio, otteniamo un riferimento all'**istanza di supporto** del campo di testo e vi invochiamo il metodo `focus()` quando il bottone viene cliccato.
123 -
124 -Per componenti compositi, il riferimento si riferisce a un'istanza della classe del componente, quindi puoi invocare ogni metodo definito in tale classe. Se devi accedere al nodo DOM sottostante per il componente, puoi usare [ReactDOM.findDOMNode](/react/docs/top-level-api-it-IT.html#reactdom.finddomnode).
125 -
126 -## Riassunto
127 -
128 -I riferimenti `ref` sono la maniera corretta di inviare un messaggio a una precisa istanza di un figlio in una maniera che sarebbe impraticabile attraverso le normali proprietà `props` e `state` di React. Tuttavia, esse non dovrebbero essere la tua astrazione principale per far fluire i dati attraverso la tua applicazione. In modo predefinito, usa il flusso dati di React e utilizza i `ref` per casi d'uso che sono intrinsecamente non reattivi.
129 -
130 -### Benefici:
131 -
132 -- Puoi definire ogni metodo pubblico nelle classi dei tuoi componenti (come un metodo per reimpostare un Typeahead) e chiamare tali metodi pubblici attraverso i riferimenti (come ad esempio `this.refs.myTypeahead.reset()`).
133 -- Effettuare misure sul DOM richiede quasi sempre l'accesso ad un componente "nativo" come `<input />` accedendo il suo nodo DOM sottostante attraverso `ReactDOM.findDOMNode(this.refs.myInput)`. I riferimenti sono uno degli unici metodi praticabili per fare ciò in maniera affidabile.
134 -- I riferimenti sono gestiti automaticamente per te! Se un figlio è distrutto, anche il suo riferimento è distrutto. Pertanto non preoccuparti del consumo di memoria (a meno che tu non faccia qualcosa di folle per conservare un riferimento).
135 -
136 -### Precauzioni:
137 -
138 -- *Non accedere mai* ai riferimenti dentro il metodo render di un componente - oppure mentre il metodo render di qualsiasi componente è in esecuzione ovunque nella pila di chiamate.
139 -- Se vuoi preservare la resilienza al Crushing del compilatore Google Closure Compiler, assicurati di non accedere mai come proprietà a ciò che è stato specificato come stringa. Ciò significa che devi accedere come `this.refs['myRefString']` se il tuo ref è stato definito come `ref="myRefString"`.
140 -- Se non hai ancora programmato parecchie applicazioni con React, la tua prima inclinazione è solitamente di provare a utilizzare i riferimenti per "fare succedere qualcosa" nella tua applicazione. Se questo è il tuo caso, fermati un momento e pensa in maniera critica al luogo corretto nella gerarchia dei componenti in cui lo `state` debba trovarsi. Spesso ti accorgerai che il luogo corretto per "possedere" lo stato si trova a un livello più alto nella gerarchia. Posizionare lì lo stato spesso elimina ogni necessità di usare i `ref` per "fare accadere qualcosa" – al contrario, il flusso dei dati solitamente otterrà lo scopo desiderato.
141 -- I ref non possono essere assegnati a [funzioni prive di stato](/react/docs/reusable-components-it-IT.html#stateless-functions), poiché il componente non possiede un'istanza di supporto. Puoi tuttavia racchiudere un componente privo di stato in un componente composito standard e assegnare il ref al componente composito.
docs/docs/08.1-more-about-refs.ja-JP.md deleted
-147
@@ -1,147 +0,0 @@
1 ----
2 -id: more-about-refs
3 -title: 参照についての詳細
4 -permalink: docs/more-about-refs-ja-JP.html
5 -prev: working-with-the-browser-ja-JP.html
6 -next: tooling-integration-ja-JP.html
7 -
8 ----
9 -renderメソッドからUIの構成をリターンした後、あなたは「リーチアウト」を見て、renderから返ってきたコンポーネントのインスタンスの上でメソッドを実行するでしょう。多くの場合、アプリケーションにおいて、データフローを作成することは必要ではありません。リアクティブなデータフローは常に最新の `props` が `render()` から出力されたそれぞれの子要素に送られたことを保証するからです。しかし、まだ必要であったり、利益をもたらすケースもあります。
10 -
11 -`''` という空の文字列でその値をアップデートした後にフォーカスするということを `<input />` 要素(インスタンスのサブ階層に存在します)に伝えたいという場合を考えましょう。
12 -
13 -```javascript
14 - var App = React.createClass({
15 - getInitialState: function() {
16 - return {userInput: ''};
17 - },
18 - handleChange: function(e) {
19 - this.setState({userInput: e.target.value});
20 - },
21 - clearAndFocusInput: function() {
22 - this.setState({userInput: ''}); // inputをクリアします
23 - // ここで、<input /> にフォーカスさせたいです!
24 - },
25 - render: function() {
26 - return (
27 - <div>
28 - <div onClick={this.clearAndFocusInput}>
29 - Click to Focus and Reset
30 - </div>
31 - <input
32 - value={this.state.userInput}
33 - onChange={this.handleChange}
34 - />
35 - </div>
36 - );
37 - }
38 - });
39 -```
40 -
41 -この例では、どうにかしてinputに何かを「伝え」たいということに着目してください。何かというのは、propsから推測できるものではありません。このケースでは、inputが今フォーカスされるべきであるということを「伝え」たいのです。しかし、いくつか問題があります。`render()` で返されるものは実際の「子供の」要素ではありません。しかし、特別なインスタンスにおいて子要素の *説明* を行うよりかは、スナップショットを見ていったほうがいいでしょう。
42 -
43 -> 注意:
44 -> `render()` からリターンされるものは *実際に* レンダリングされた子要素のインスタンスではないと覚えておいてください。 `render()` からリターンされるものは、ある特定の時点においてのコンポーネントの副階層にある単なる子要素のインスタンスの *説明* に過ぎません。
45 -
46 -これは、 `render()` からリターンされる何かを「保持し続ける」ことはできないことを意味します。そして、それは何かしら意味のあることであると予測できます。
47 -
48 -```javascript
49 - // 反例: このようには記述しないでください!
50 - render: function() {
51 - var myInput = <input />; // このinputの上にあるメソッドを未来のいつかの
52 - this.rememberThisInput = myInput; // タイミングで呼ぼうとしています!いえいっ!
53 - return (
54 - <div>
55 - <div>...</div>
56 - {myInput}
57 - </div>
58 - );
59 - }
60 -```
61 -
62 -この反例では、 `<input />` は単に `<input />` の *説明* に過ぎず、この説明は `<input />` の *現実の* **バッキングインスタンス** を作るために使われます。
63 -
64 -では、inputの *現実の* バッキングインスタンスについて、どのように話していきましょうか?
65 -
66 -## 参照の文字列属性
67 -
68 -Reactは `render()` からの出力であるコンポーネントであれば何でもアタッチできるとても特別なプロパティをサポートしています。この特別なプロパティは `render()` からのリターンである **バッキングインスタンス** に対応したものに参照することを許可します。これはどのタイミングにおいても、固有のインスタンスであることを保証されています。
69 -
70 -これは以下のように単純です。
71 -
72 -1. 以下のように、 `render` からのリターンであれば何でも `ref` 属性をアサインする。
73 -
74 - ```html
75 - <input ref="myInput" />
76 - ```
77 -
78 -2. いくつかの他のコードは(一般的にイベントハンドラのコード)、以下にあるように `this.refs` を通して **バッキングインスタンス** にアクセスします。
79 -
80 - ```javascript
81 - this.refs.myInput
82 - ```
83 -
84 -`ReactDOM.findDOMNode(this.refs.myInput)` を呼ぶことで、コンポーネントのDOMノードに直接アクセスできる。
85 -
86 -## 参照のコールバック属性
87 -
88 -`ref` 属性は名前の代わりのコールバック関数になり得ます。このコールバックはコンポーネントがマウントされた直後に実行されます。参照されたコンポーネントはパラメータとして渡され、コールバック関数はコンポーネントを即座に使用するか、または将来使用するために参照を保存します(またはその両方を行います)。
89 -
90 -これは、以下のように、 `render` でリターンされてきたものに `ref` 属性をアサインするのと同じくらい簡単です。
91 -
92 - ```html
93 - <input ref={ function(component){ ReactDOM.findDOMNode(component).focus();} } />
94 - ```
95 -
96 -
97 -## 完全な例
98 -
99 -```javascript
100 - var App = React.createClass({
101 - getInitialState: function() {
102 - return {userInput: ''};
103 - },
104 - handleChange: function(e) {
105 - this.setState({userInput: e.target.value});
106 - },
107 - clearAndFocusInput: function() {
108 - // inputをクリアする
109 - this.setState({userInput: ''}, function() {
110 - // このコードはコンポーネントが再度レンダリングされた後に実行されます。
111 - ReactDOM.findDOMNode(this.refs.theInput).focus(); // どーん!フォーカスされました!
112 - });
113 - },
114 - render: function() {
115 - return (
116 - <div>
117 - <div onClick={this.clearAndFocusInput}>
118 - Click to Focus and Reset
119 - </div>
120 - <input
121 - ref="theInput"
122 - value={this.state.userInput}
123 - onChange={this.handleChange}
124 - />
125 - </div>
126 - );
127 - }
128 - });
129 -```
130 -
131 -この例では、レンダリング関数は `<input />` インスタンスの説明をリターンします。しかし、実際のインスタンスは `this.refs.theInput` を通してアクセスされます。 `ref="theInput"` を持つ子要素のコンポーネントが `render` からリターンされる限り、 `this.refs.theInput` は固有のインスタンスにアクセスするでしょう。これは `<Typeahead ref="myTypeahead" />` のような高階層の(DOMでない)コンポーネントでも同様に動きます。
132 -
133 -## 要約
134 -
135 -リアクティブな `props` と `state` を通してのストリーミングのアクセスは便利とは言えないため、参照は特定の子要素のインスタンスにメッセージを送るための素晴らしい方法です。しかし、それらは、アプリケーションを通したデータフローの抽象化につながるわけではありません。デフォルトで、リアクティブなデータフローを使ってください。そして、ユースケースのために `ref` を保存するのは本質的にはリアクティブではありません。
136 -
137 -### 利益:
138 -
139 -- コンポーネントクラス(例えば、Typeaheadのリセットメソッドのようなもの)にパブリックなメソッドを定義できる。また、参照(例えば、 `this.refs.myTypeahead.reset()` のように)を通してそれらのパブリックなメソッドを呼べる。
140 -- DOMの計測を行うことは大体いつも `<input />` のような「ネイティブの」コンポーネントや `ReactDOM.findDOMNode(this.refs.myInput)` を通した根本のDOMノードにアクセスすることを必要とします。参照は、こういったことを期待通りに行う唯一の実用的な方法です。
141 -- 参照は自動的に管理されます!もし子要素が削除されたら、その参照もまた削除されます。メモリに関しての心配は要りません(あなた自身が参照を維持するために何かおかしなことを行っていなければ)。
142 -
143 -### 警告:
144 -
145 -- *決して* コンポーネントのレンダリングメソッドの中の参照にアクセスしてはいけません。たとえコンポーネントのレンダリングメソッドのいずれかがコールスタックの中のどこかで動いているとしても。
146 -- もしGoogle Closure Compilerのクラッシュからの回復を守りたいなら、文字列として指定されたプロパティとしてアクセスしてはいけないことに気をつけてください。これは、 `ref="myRefString"` として参照が定義されている場合は、 `this.refs['myRefString']` を使ってアクセスしなければいけないことを意味します。
147 -- まだReactでプログラムを書いたことがない場合は、アプリケーションで「何かを起こす」ために参照を使おうとするでしょう。もしそのケースだった場合は、時間をかけて `state` がコンポーネントの階層のどこで保持されるべきか批評的に考えてください。多くの場合は、そのstateを「保持する」ための固有の場所が階層の高いレベルにあることがクリアになります。そのstateをその場所に配置することはよく「何かを起こす」ために `ref` を使うための願望を排除します。代わりに、データフローは普通、目標を達成します。
docs/docs/08.1-more-about-refs.ko-KR.md deleted
-139
@@ -1,139 +0,0 @@
1 ----
2 -id: more-about-refs-ko-KR
3 -title: refs에서 컴포넌트로
4 -permalink: docs/more-about-refs-ko-KR.html
5 -prev: working-with-the-browser-ko-KR.html
6 -next: tooling-integration-ko-KR.html
7 ----
8 -컴포넌트를 빌드한 후에는 `render()`에서 반환된 컴포넌트 인스턴스에 접근하거나 메소드를 호출할 방법이 필요할 수도 있습니다. 반응적 데이터 플로우가 `render()`의 결과물에서 최신의 `props`가 각각의 자식으로 보내진 것을 항상 보장하기 때문에 애플리케이션의 데이터 플로우를 만드는데 대체로 이런 작업은 필요가 없지만, 여전히 이런 작업이 필요하거나 유리한 경우가 있긴 합니다. React는 이를 위해 `refs`라는 탈출구를 제공합니다. `refs`(레퍼런스)는 특히 다음과 같은 경우 유용합니다: 컴포넌트에 의해 렌더된 DOM 마크업을 찾을때 (인스턴스내의 절대적인 위치), 큰 프로젝트의 일부에 React 컴포넌트를 사용하는 경우 또는 기존의 코드베이스를 React로 변경하는 경우.
9 -
10 -ref를 어떻게 얻는지 살펴보고, 예제를 완성해 봅시다.
11 -
12 -## ReactDOM.render에서 반환된 ref
13 -
14 -컴포넌트에서 정의한, 가상의 DOM 엘리먼트를 반환하는 `render()`와 헷갈리지 않도록 합니다. [ReactDOM.render()](/react/docs/top-level-api-ko-KR.html#reactdom.render)는 컴포넌트의 **지원 인스턴스(backing instance)**에 대한 참조를 반환 합니다. [상태를 가지지 않는 컴포넌트](/react/docs/reusable-components-ko-KR.html#상태를-가지지-않는-함수)에 대해선 `null`을 반환하죠.
15 -
16 -
17 -```js
18 -var myComponent = ReactDOM.render(<MyComponent />, myContainer);
19 -```
20 -
21 -명심하세요. 위의 코드는 컴포넌트 인스턴스를 반환하지 않습니다! 이는 그저 **ReactElement**:React에 마운트된 컴포넌트가 어떻게 보여야 할지 알려주는 경량의 표상(representation) 입니다.
22 -
23 -```js
24 -var myComponentElement = <MyComponent />; // 이건 그냥 ReactElement 입니다.
25 -
26 -// 여기 코드가 위치합니다...
27 -
28 -var myComponentInstance = ReactDOM.render(myComponentElement, myContainer);
29 -myComponentInstance.doSomething();
30 -```
31 -
32 -> 주의:
33 ->
34 -> 이는 오직 최상위 레벨에서만 사용되어야 합니다. 컴포넌트의 내부에서는 `props`와 `state`가 자식 컴포넌트와 통신하도록 하거나 문자열이나 콜백 어트리뷰트 등 ref를 얻어오는 다른 방법을 사용하도록 하세요.
35 -
36 -## ref 콜백 어트리뷰트
37 -
38 -React는 어떤 컴포넌트에든 추가할 수 있는 특별한 어트리뷰트를 제공합니다. `ref` 어트리뷰트는 콜백 함수일 수 있으며 이는 컴포넌트가 마운트 된 후 즉시 실행됩니다. 참조된 컴포넌트는 파라미터로 전달될 것이며 콜백 함수는 즉시, 혹은 미래에 사용하기 위해 컴포넌트의 참조를 저장합니다.
39 -
40 -`render`에서 반환되는 무엇에든 `ref` 어트리뷰트를 추가하는 것은 간단합니다:
41 -
42 -```js
43 - render: function() {
44 - return (
45 - <TextInput
46 - ref={function(input) {
47 - if (input != null) {
48 - input.focus();
49 - }
50 - }} />
51 - );
52 - },
53 -```
54 -ES6 화살표 함수를 사용한다면 다음과 같습니다:
55 -
56 -```js
57 - render: function() {
58 - return <TextInput ref={(c) => this._input = c} />;
59 - },
60 - componentDidMount: function() {
61 - this._input.focus();
62 - },
63 -```
64 -
65 -`<div />` 같은 DOM 컴포넌트에 ref를 추가하면 DOM 노드를 얻게 됩니다; `<TextInput />` 같은 합성 컴포넌트에 ref를 추가하면 React 클래스 인스턴스를 얻게 됩니다. 후자의 경우, 클래스에 정의되어 있는 노출된 메소드를 호출할 수 있습니다.
66 -
67 -참조된 컴포넌트가 언마운트되고 ref가 변경되면 이전의 ref는 `null`을 인수로 호출됨을 주의 하세요. 이는 첫번째 예제에서처럼 인스턴트가 저장된 경우의 메모리 누수를 방지합니다. 또한 예제와 같이 ref를 인라인 함수 표현식으로 서술하게되면 React는 모든 업데이트에 대해 다른 함수 객체를 참조하게 됩니다. ref는 컴포넌트의 인스턴스의 호출 이전에 `null` 객체와 함께 즉시 호출될 것입니다.
68 -
69 -## ref 문자열 어트리뷰트
70 -
71 -React는 ref에 콜백 대신 문자열도 지원합니다 이런 접근은 이제 과거의 것이긴 합니다.
72 -
73 -
74 -1. `render`에서 반환된 값을 `ref` 어트리뷰트에 할당합니다:
75 -
76 - ```html
77 - <input ref="myInput" />
78 - ```
79 -
80 -2. 다른 코드(일반적으로는 이벤트 핸들러 코드)에서 `this.refs`를 통해 **지원 인스턴스**에 접근 합니다:
81 -
82 - ```javascript
83 - var input = this.refs.myInput;
84 - var inputValue = input.value;
85 - var inputRect = input.getBoundingClientRect();
86 - ```
87 -
88 -## 최종 예제
89 -React 컴포넌트의 참조를 얻기 위해서, 현재의 React 컴포넌트를 위해서는 `this`를, 소유한 컴포넌트에 대해서는 ref를 사용할 수 있습니다. 다음과 같이 작동 합니다:
90 -
91 -```javascript
92 -var MyComponent = React.createClass({
93 - handleClick: function() {
94 - // 명시적으로 텍스트 인풋에 포커스하기 위해 raw DOM API를 사용합니다.
95 - this.myTextInput.focus();
96 - },
97 - render: function() {
98 - // ref 어트리뷰트는 컴포넌트가 마운트되면
99 - // this.refs에 컴포넌트에 대한 참조를 추가합니다.
100 - return (
101 - <div>
102 - <input type="text" ref={(ref) => this.myTextInput = ref} />
103 - <input
104 - type="button"
105 - value="Focus the text input"
106 - onClick={this.handleClick}
107 - />
108 - </div>
109 - );
110 - }
111 -});
112 -
113 -ReactDOM.render(
114 - <MyComponent />,
115 - document.getElementById('example')
116 -);
117 -```
118 -
119 -이 예제에서, 텍스트 인풋의 **지원 인스턴스**에 대한 참조를 얻었으며 버튼이 클릭되었을때 `focus()`를 호출했습니다.
120 -
121 -합성 컴포넌트에서는 참조는 컴포넌트 클래스의 인스턴스를 가리키기 때문에 클래스에 정의된 어떤 메소드도 호출할 수 있습니다. 컴포넌트의 기저에 있는 DOM 노드에 접근하기 위해서는 [ReactDOM.findDOMNode](/react/docs/top-level-api-ko-KR.html#reactdom.finddomnode)를 "탈출구"로 사용할 수 있습니다. 하지만 이는 캡슐화를 깨며, 대부분의 경우 React 모델을 이용해 더 명확한 방법으로 구조를 짤 수 있기 때문에 추천하지 않습니다.
122 -
123 -
124 -## 요약
125 -
126 -Refs는 반응적인 `props`와 `state` 스트리밍을 통해서는 불편했던 특정한 자식 인스턴스에 메시지 보내기를 수행하는 좋은 방법입니다. 하지만 애플리케이션의 데이터 플로우 전반에 사용해도 되는 go-to 같은 개념은 아닙니다. 기본적으로는 반응적인 데이터 플로우를 사용하고, `ref`는 근본적으로 반응적이지 않은 경우에만 사용하세요.
127 -
128 -### 이점:
129 -
130 -- 컴포넌트 클래스에 public 메소드(ex. Typeahead의 reset)를 선언할 수 있으며 refs를 통해 그를 호출할 수 있습니다. (ex. `this.refs.myTypeahead.reset()`) 대부분, 이는 선언적으로 refs를 사용하는 것보다 내장 React 데이터 흐름을 명확하게 합니다.
131 -- DOM을 측정하기 위해서는 거의 항상 `<input />` 같은 "기본" 컴포넌트를 다루고 ref를 통해 그 기저의 DOM 노드에 접근해야 합니다. Refs는 이 일을 확실하게 수행하는 몇 안 되는 실용적인 방법의 하나입니다.
132 -- Refs는 자동으로 관리합니다! 자식이 파괴되면, 그의 ref도 마찬가지로 파괴됩니다. 참조를 유지하기 위해 뭔가 미친 짓을 하지 않는 한, 메모리 걱정은 하지 않아도 됩니다.
133 -
134 -### 주의:
135 -
136 -- 컴포넌트의 렌더 메소드에서는, 혹은 컴포넌트의 렌더 메소드가 콜스택 어디에서든 실행되는 동안에는 절대 접근하지 마세요.
137 -- Google Closure Compiler에서의 어드벤스드 모드 분쇄 복원력 유지(to preserve advanced-mode crushing resilience)를 위해서는 문자열로 정의한 것을 절대 프로퍼티로 접근하지 마세요. ref가 ref="myRefString"으로 정의되어 있다면 this.refs['myRefString']으로만 접근해야 한다는 이야기 입니다.
138 -- React로 앱을 여럿 만들어 본 경험이 없다면, 보통은 처음엔 앱에서 "무언가 일어나도록" 하는데 refs를 사용하게 될 것입니다. 이 경우, 잠시 시간을 내어 `state`가 컴포넌트 계층구조의 어느 부분에서 관리되어야 할지 비판적으로 생각해 봅시다. 대개는 state가 계층구조의 더 높은 레벨에서 "소유"하는 것이 타당함이 명확해집니다. 그렇게 함으로써 `ref`를 사용해 "무언가 일어나도록" 하려는 욕망이 대부분 제거됩니다. - 대신에 데이터 플로우를 통해 대개 원하는 바를 달성하게 될 것입니다.
139 -- Refs는 [상태를 가지지 않는 함수](/react/docs/reusable-components-ko-KR.html#상태를-가지지-않는-함수)에 붙일 수 없습니다. 왜냐하면 컴포넌트가 내부 인스턴스를 가지지 않기 때문입니다. 상태를 가지지 않는 컴포넌트는 항상 일반 컴포넌트로 감싸 ref를 조합 컴포넌트에 붙일 수 있습니다.
docs/docs/08.1-more-about-refs.md deleted
-143
@@ -1,143 +0,0 @@
1 ----
2 -id: more-about-refs
3 -title: Refs to Components
4 -permalink: docs/more-about-refs.html
5 -prev: working-with-the-browser.html
6 -next: tooling-integration.html
7 ----
8 -After building your component, you may find yourself wanting to "reach out" and invoke methods on component instances returned from `render()`. In most cases, this should be unnecessary because the reactive data flow always ensures that the most recent props are sent to each child that is output from `render()`. However, there are a few cases where it still might be necessary or beneficial, so React provides an escape hatch known as `refs`. These `refs` (references) are especially useful when you need to find the DOM markup rendered by a component (for instance, to position it absolutely), use React components in a larger non-React application, or transition your existing codebase to React.
9 -
10 -Let's look at how to get a ref, and then dive into a complete example.
11 -
12 -## The ref returned from ReactDOM.render
13 -
14 -Not to be confused with the `render()` function that you define on your component (and which returns a virtual DOM element), [ReactDOM.render()](/react/docs/top-level-api.html#reactdom.render) will return a reference to your component's **backing instance** (or `null` for [stateless components](/react/docs/reusable-components.html#stateless-functions)).
15 -
16 -
17 -```js
18 -var myComponent = ReactDOM.render(<MyComponent />, myContainer);
19 -```
20 -
21 -Keep in mind, however, that the JSX doesn't return a component instance! It's just a **ReactElement**: a lightweight representation that tells React what the mounted component should look like.
22 -
23 -```js
24 -var myComponentElement = <MyComponent />; // This is just a ReactElement.
25 -
26 -// Some code here...
27 -
28 -var myComponentInstance = ReactDOM.render(myComponentElement, myContainer);
29 -myComponentInstance.doSomething();
30 -```
31 -
32 -> Note:
33 ->
34 -> This should only ever be used at the top level. Inside components, let your `props` and `state` handle communication with child components, or use one of the other methods of getting a ref (string attribute or callbacks).
35 -
36 -## The ref Callback Attribute
37 -
38 -React supports a special attribute that you can attach to any component. The `ref` attribute can be a callback function, and this callback will be executed immediately after the component is mounted. The referenced component will be passed in as a parameter, and the callback function may use the component immediately, or save the reference for future use (or both).
39 -
40 -It's as simple as adding a `ref` attribute to anything returned from `render`:
41 -
42 -```js
43 - render: function() {
44 - return (
45 - <TextInput
46 - ref={function(input) {
47 - if (input != null) {
48 - input.focus();
49 - }
50 - }} />
51 - );
52 - },
53 -```
54 -or using an ES6 arrow function:
55 -
56 -```js
57 - render: function() {
58 - return <TextInput ref={(c) => this._input = c} />;
59 - },
60 - componentDidMount: function() {
61 - this._input.focus();
62 - },
63 -```
64 -
65 -When attaching a ref to a DOM component like `<div />`, you get the DOM node back; when attaching a ref to a composite component like `<TextInput />`, you'll get the React class instance. In the latter case, you can call methods on that component if any are exposed in its class definition.
66 -
67 -Note that when the referenced component is unmounted and whenever the ref changes, the old ref will be called with `null` as an argument. This prevents memory leaks in the case that the instance is stored, as in the second example. Also note that when writing refs with inline function expressions as in the examples here, React sees a different function object each time so on every update, ref will be called with `null` immediately before it's called with the component instance.
68 -
69 -## The ref String Attribute
70 -
71 -> Note:
72 ->
73 -> Although string refs are not deprecated, they are considered legacy, and will likely be deprecated at some point in the future. Callback refs are preferred.
74 -
75 -React also supports using a string (instead of a callback) as a ref prop on any component.
76 -
77 -1. Assign a `ref` attribute to anything returned from `render` such as:
78 -
79 - ```html
80 - <input ref="myInput" />
81 - ```
82 -
83 -2. In some other code (typically event handler code), access the **backing instance** via `this.refs` as in:
84 -
85 - ```javascript
86 - var input = this.refs.myInput;
87 - var inputValue = input.value;
88 - var inputRect = input.getBoundingClientRect();
89 - ```
90 -
91 -## A Complete Example
92 -In order to get a reference to a React component, you can either use `this` to get the current React component, or you can use a ref to get a reference to a component you own. They work like this:
93 -
94 -```javascript
95 -var MyComponent = React.createClass({
96 - handleClick: function() {
97 - // Explicitly focus the text input using the raw DOM API.
98 - if (this.myTextInput !== null) {
99 - this.myTextInput.focus();
100 - }
101 - },
102 - render: function() {
103 - // The ref attribute is a callback that saves a reference to the
104 - // component to this.myTextInput when the component is mounted.
105 - return (
106 - <div>
107 - <input type="text" ref={(ref) => this.myTextInput = ref} />
108 - <input
109 - type="button"
110 - value="Focus the text input"
111 - onClick={this.handleClick}
112 - />
113 - </div>
114 - );
115 - }
116 -});
117 -
118 -ReactDOM.render(
119 - <MyComponent />,
120 - document.getElementById('example')
121 -);
122 -```
123 -
124 -In this example, we get a reference to the text input **backing instance** and we call `focus()` when the button is clicked.
125 -
126 -For composite components, the reference will refer to an instance of the component class so you can invoke any methods that are defined on that class. If you need access to the underlying DOM node for that component, you can use [ReactDOM.findDOMNode](/react/docs/top-level-api.html#reactdom.finddomnode) as an "escape hatch" but we don't recommend it since it breaks encapsulation and in almost every case there's a clearer way to structure your code within the React model.
127 -
128 -## Summary
129 -
130 -Refs are a great way to send a message to a particular child instance in a way that would be inconvenient to do via streaming Reactive `props` and `state`. They should, however, not be your go-to abstraction for flowing data through your application. By default, use the Reactive data flow and save `ref`s for use cases that are inherently non-reactive.
131 -
132 -### Benefits:
133 -
134 -- You can define any public method on your component classes (such as a reset method on a Typeahead) and call those public methods through refs (such as `this.refs.myTypeahead.reset()`). In most cases, it's clearer to use the built-in React data flow instead of using refs imperatively.
135 -- Performing DOM measurements almost always requires reaching out to a "native" component such as `<input />` and accessing its underlying DOM node using a ref. Refs are one of the only practical ways of doing this reliably.
136 -- Refs are automatically managed for you! If that child is destroyed, its ref is also destroyed for you. No worrying about memory here (unless you do something crazy to retain a reference yourself).
137 -
138 -### Cautions:
139 -
140 -- *Never* access refs inside of any component's render method – or while any component's render method is even running anywhere in the call stack.
141 -- If you want to preserve Google Closure Compiler advanced-mode crushing resilience, make sure to never access as a property that was specified as a string. This means you must access using `this.refs['myRefString']` if your ref was defined as `ref="myRefString"`.
142 -- If you have not programmed several apps with React, your first inclination is usually going to be to try to use refs to "make things happen" in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. Often, it becomes clear that the proper place to "own" that state is at a higher level in the hierarchy. Placing the state there often eliminates any desire to use `ref`s to "make things happen" – instead, the data flow will usually accomplish your goal.
143 -- Refs may not be attached to a [stateless function](/react/docs/reusable-components.html#stateless-functions), because the component does not have a backing instance. You can always wrap a stateless component in a standard composite component and attach a ref to the composite component.
docs/docs/08.1-more-about-refs.zh-CN.md deleted
-137
@@ -1,137 +0,0 @@
1 ----
2 -id: more-about-refs-zh-CN
3 -title: 对组件的refs
4 -permalink: docs/more-about-refs-zh-CN.html
5 -prev: working-with-the-browser-zh-CN.html
6 -next: tooling-integration-zh-CN.html
7 ----
8 -在建立你的组件以后,你也许发现你想“接触”并且调用从 `render()`返回的组件实例上的方法。大部分情况下,这是不必要的因为响应式的数据流总是确保最近的 props 被送到每一个从 `render()` 输出的子级。然而,有一些情况下它仍旧是必要或者有益的,所以 React 提供了一个被称为 `refs` 的安全舱口。这些 `refs` (引用) 在你需要时特别有用 如:查找被组件绘制的 DOM 标记(例如,绝对定位它),使用 React 组件在一个大的非React组件里,或者转换你已有的代码库到React。
9 -
10 -让我们来看看怎样取得一个ref,然后深入完整的例子。
11 -
12 -## 从 ReactDOM.render 返回的 ref
13 -
14 -不要被你在你的组件(它返回一个虚拟的DOM元素)里定义的 `render()` 迷惑了, [ReactDOM.render()](/react/docs/top-level-api.html#reactdom.render) 会返回一个对你的组件的 **backing instance** 的引用([无状态组件](/react/docs/reusable-components.html#stateless-functions) 返回 `null`).
15 -
16 -```js
17 -var myComponent = ReactDOM.render(<MyComponent />, myContainer);
18 -```
19 -
20 -记住,不管怎样,JSX不会返回一个组件的实例!它只是一个 **ReactElement**: 一个轻量级的表达,告诉React被挂载的组件应该长什么样。
21 -
22 -```js
23 -var myComponentElement = <MyComponent />; // 这只是一个 ReactElement.
24 -
25 -// 省略一些代码 ...
26 -
27 -var myComponentInstance = ReactDOM.render(myComponentElement, myContainer);
28 -myComponentInstance.doSomething();
29 -```
30 -
31 -> 注意:
32 ->
33 -> 这只应该用在顶层上。在组件内部,让你的 `props` 和 `state` 来处理和子组件的通信,或者使用其他获取ref的方法(string attribute or callbacks)。
34 -
35 -## ref Callback 属性
36 -
37 -React支持一种非常特殊的属性,你可以附加到任何的组件上。 `ref` 属性可以是一个回调函数,这个回调函数会在组件被挂载后立即执行。被引用的组件会被作为参数传递,回调函数可以用立即使用这个组件,或者保存引用以后使用(或者二者皆是)。
38 -
39 -简单的说就是添加一个 `ref` 属性到任何从 `render` 返回的东西上:
40 -
41 -```js
42 - render: function() {
43 - return (
44 - <TextInput
45 - ref={function(input) {
46 - if (input != null) {
47 - input.focus();
48 - }
49 - }} />
50 - );
51 - },
52 -```
53 -或者使用ES6的箭头函数:
54 -
55 -```js
56 - render: function() {
57 - return <TextInput ref={(c) => this._input = c} />;
58 - },
59 - componentDidMount: function() {
60 - this._input.focus();
61 - },
62 -```
63 -
64 -当连接一个ref到一个DOM组件如 `<div />`,你取回DOM节点;当连接一个ref到一个复合组件如 `<TextInput />`,你会得到React类的实例。在后一种情况下,你可以调用任何那个组件的类暴露的方法。
65 -
66 -注意当被引用的组件卸载和每当ref变动,旧的ref将会被以`null`做参数调用。这阻止了在实例被保存的情况下的内存泄露,如第二个例子。注意当像在这里的例子,使用内联函数表达式写refs,React在每次更新都看到不同的函数对象,ref将会被以`null` 立即调用在它被以组件实例调用前。
67 -
68 -## ref String 属性
69 -
70 -React同样支持使用一个字符串(代替回调函数)在任意组件上作为一个 ref prop,尽管这个方法在这点上主要是遗留物。
71 -
72 -1. 赋值`ref`属性为任何从`render` 返回的东西,比如:
73 -
74 - ```html
75 - <input ref="myInput" />
76 - ```
77 -
78 -2. 在其他一些代码中(典型的如事件处理的代码),通过`this.refs`访问 **支持实例(backing instance)**,如:
79 -
80 - ```javascript
81 - var input = this.refs.myInput;
82 - var inputValue = input.value;
83 - var inputRect = input.getBoundingClientRect();
84 - ```
85 -
86 -## 完整的示例
87 -
88 -为了获取一个React组件的引用,你既可以使用 `this` 来获取当前的React组件,也可以使用一个 ref 来获取一个你拥有的组件的引用。他们像这样工作:
89 -
90 -```javascript
91 -var MyComponent = React.createClass({
92 - handleClick: function() {
93 - // Explicitly focus the text input using the raw DOM API.
94 - this.myTextInput.focus();
95 - },
96 - render: function() {
97 - // The ref attribute adds a reference to the component to
98 - // this.refs when the component is mounted.
99 - return (
100 - <div>
101 - <input type="text" ref={(ref) => this.myTextInput = ref} />
102 - <input
103 - type="button"
104 - value="Focus the text input"
105 - onClick={this.handleClick}
106 - />
107 - </div>
108 - );
109 - }
110 -});
111 -
112 -ReactDOM.render(
113 - <MyComponent />,
114 - document.getElementById('example')
115 -);
116 -```
117 -
118 -在这个例子中,我们获得一个对 text input **backing instance** 的引用 并且当按钮被点击时我们调用 `focus()`。
119 -
120 -对于复合组件,引用会指向一个组件类的实例所以你可以调用那个类定义的任何方法。如果你需要访问那个组件的底层的DOM节点,你可以使用 [ReactDOM.findDOMNode](/react/docs/top-level-api.html#reactdom.finddomnode) 作为一个 `安全舱口` 但是我们不推荐这样,因为它打破了封装,在大多数情况下都有一个清晰的方法来以React模式构建你的代码.
121 -
122 -## 总结
123 -
124 -Refs是一种很好的发送消息给特定子实例(通过流式的Reactive `props` 和 `state`来做会不方便)的方式。它们应该,不论怎样,不是你的应用中数据流通的首选。默认情况下,使用响应式数据流,并为本身不是reactive的用例保存`ref`。
125 -
126 -### 优点:
127 -
128 -- 你可以在你的组件类里定义任何的公开方法(比如在一个Typeahead的重置方法)然后通过refs调用那些公开方法(比如`this.refs.myTypeahead.reset()`)。在大多数情况下,使用内建的React数据流更清晰,而不是使用强制的ref。
129 -- 实行DOM测量几乎总是需要接触到 "原生" 组件比如 `<input />` 并且通过 ref 访问它的底层DOM节点。 Refs 是唯一一个可靠的完成这件事的实际方式。
130 -- Refs 是为你自动管理的!如果子级被销毁了,它的ref也同样为你销毁了。这里不用担心内存(除非你做了一些疯狂的事情来自己保持一份引用)。
131 -
132 -### 注意事项:
133 -
134 -- *绝不* 在任何组件的 render 方法中访问 refs - 或者当任何组件的render方法还在调用栈上的任何地方运行时。
135 -- 如果你想要保留Google Closure Compiler advanced-mode crushing resilience,务必不要以属性的方式访问指明为字符串的属性。这意味这你必须用`this.refs['myRefString']`访问,如果你的ref被定义为`ref="myRefString"`。
136 -- 如果你没有用React写过数个程序,你的第一反应通常是打算试着用refs来在你的应用里"让事情发生"。如果是这样,花一些时间并且更精密的思考`state`应该属于组件层级的哪个位置。常常,这会变得清晰:正确的"拥有"那个属性的地方应该在层级的更高层上。把state放在那里 往往消除了任何使用`ref`s 来 "让事情发生"的渴望 - 作为替代,数据流通常将完成你的目标。
137 -- Refs 不能连接到一个 [stateless function(无状态函数)](/react/docs/reusable-components.html#stateless-functions),因为这些组件没有支持实例。你总是可以包装一个无状态组件在一个标准复合组件里并且连接一个ref到这个复合组件。
docs/docs/09-tooling-integration.it-IT.md deleted
-74
@@ -1,74 +0,0 @@
1 ----
2 -id: tooling-integration-it-IT
3 -title: Integrazione con Strumenti
4 -permalink: docs/tooling-integration-it-IT.html
5 -prev: more-about-refs-it-IT.html
6 -next: addons-it-IT.html
7 ----
8 -
9 -Ciascun progetto utilizza un sistema differente per la build e il deploy di JavaScript. Abbiamo provato a rendere React il più possibile indipendente dall'ambiente di sviluppo.
10 -
11 -## React
12 -
13 -### React hosted su un CDN
14 -
15 -Offriamo versioni di React su CDN [nella nostra pagina dei download](/react/downloads.html). Questi file precompilati usano il formato dei moduli UMD. Inserirli con un semplice tag `<script>` inietterà una variabile globale `React` nel tuo ambiente. Questo approccio dovrebbe funzionare senza alcuna configurazione in ambienti CommonJS ed AMD.
16 -
17 -
18 -### Usare il ramo master
19 -
20 -Abbiamo istruzioni per compilare dal ramo `master` [nel nostro repositorio GitHub](https://github.com/facebook/react). Costruiamo un albero di moduli CommonJS sotto `build/modules` che puoi inserire in ogni ambiente o strumento di packaging che supporta CommonJS.
21 -
22 -## JSX
23 -
24 -### Trasformazione di JSX nel browser
25 -
26 -Se preferisci usare JSX, Babel fornisce un [trasformatore ES6 e JSX nel browser per lo sviluppo](http://babeljs.io/docs/usage/browser/) chiamato browser.js che può essere incluso da una release npm `babel-core` oppure da [CDNJS](http://cdnjs.com/libraries/babel-core). Includi un tag `<script type="text/babel">` per scatenare il trasformatore JSX.
27 -
28 -> Nota:
29 ->
30 -> Il trasformatore JSX nel browser è piuttosto grande e risulta in calcoli aggiuntivi lato client che possono essere evitati. Non utilizzare in produzione — vedi la sezione successiva.
31 -
32 -
33 -### In Produzione: JSX Precompilato
34 -
35 -Se hai [npm](https://www.npmjs.com/), puoi eseguire `npm install -g babel`. Babel include il supporto per React v0.12 e v0.13. I tag sono automaticamente trasformati negli equivalenti `React.createElement(...)`, `displayName` è automaticamente desunto e aggiunto a tutte le classi React.createClass.
36 -
37 -Questo strumento tradurrà i file che usano la sintassi JSX a file in semplice JavaScript che possono essere eseguiti direttamente dal browser. Inoltre, osserverà le directory per te e trasformerà automaticamente i file quando vengono modificati; ad esempio: `babel --watch src/ --out-dir lib/`.
38 -
39 -In maniera predefinita, vengono trasformati i file JSX con un'estensione `.js`. Esegui `babel --help` per maggiori informazioni su come usare Babel.
40 -
41 -Output di esempio:
42 -
43 -```
44 -$ cat test.jsx
45 -var HelloMessage = React.createClass({
46 - render: function() {
47 - return <div>Ciao {this.props.name}</div>;
48 - }
49 -});
50 -
51 -ReactDOM.render(<HelloMessage name="John" />, mountNode);
52 -$ babel test.jsx
53 -"use strict";
54 -
55 -var HelloMessage = React.createClass({
56 - displayName: "HelloMessage",
57 -
58 - render: function render() {
59 - return React.createElement(
60 - "div",
61 - null,
62 - "Hello ",
63 - this.props.name
64 - );
65 - }
66 -});
67 -
68 -ReactDOM.render(React.createElement(HelloMessage, { name: "John" }), mountNode);
69 -```
70 -
71 -
72 -### Progetti Open Source Utili
73 -
74 -La comunità open source ha creato strumenti che integrano JSX con diversi editor e sistemi di build. Consulta [integrazioni JSX ](https://github.com/facebook/react/wiki/Complementary-Tools#jsx-integrations) per una lista completa.
docs/docs/09-tooling-integration.ja-JP.md deleted
-41
@@ -1,41 +0,0 @@
1 ----
2 -id: tooling-integration
3 -title: インテグレーションツール
4 -permalink: docs/tooling-integration-ja-JP.html
5 -prev: more-about-refs-ja-JP.html
6 -next: addons-ja-JP.html
7 ----
8 -
9 -全てのプロジェクトがJavaScriptをビルドしたりデプロイするのに様々なシステムを使用しています。私たちはReactをできるだけ環境不問にしようとしています。
10 -
11 -## React
12 -
13 -### CDNにホストされたReact
14 -
15 -[ダウンロードページ](/react/downloads.html)でCDNにホストされたバージョンのReactが提供されています。それらの、事前にビルドされたファイルはUMDモジュールフォーマットを使用しています。簡単な `<script>` タグを使ってそれらを導入することで、あなたの環境でグローバルに `React` を使うことができます。CommonJSの外や、AMDの環境でも、それは動作するでしょう。
16 -
17 -### masterを使う
18 -
19 -[GitHubリポジトリに](https://github.com/facebook/react) `master` からビルドする説明が書いてあります。`build/modules` の下にCommonJSモジュールのツリーをビルドします。それらは、どんな環境やCommonJSがサポートされているパッケージングツールでも導入できます。
20 -
21 -## JSX
22 -
23 -### ブラウザ上でのJSXの変換
24 -
25 -JSXを使用したい場合、[ダウンロードページに](/react/downloads.html)開発のためにブラウザ上でのJSXトランスフォーマーを提供しています。単純に `<script type="text/jsx">` をインクルードすることでJSXトランスフォーマーを使用できます。
26 -
27 -> 注意:
28 -> ブラウザ上でのJSXトランスフォーマーをとても大きく、避けることのできるクライアントサイドの計算になりかねません。プロダクションでは使わないでください。詳細は次のセクションをご覧ください。
29 -
30 -### プロダクションで使う場合:事前にコンパイルされたJSX
31 -
32 -[npm](https://www.npmjs.com/)がインストールされている場合、コマンドラインの `jsx` ツールは単純に `npm install -g react-tools` コマンドを流せばインストールできます。このツールはJSXを使用しているファイルを直接ブラウザ上で動く生のJavaScriptファイルに変換します。また、ディレクトリをウォッチして、ファイルが変更されたら自動的に変換を行います。例えば、次のようなコマンドで。 `jsx --watch src/ build/`
33 -
34 -デフォルトで、拡張子が `.js` のJSXファイルは変換されます。拡張子が `.jsx` のファイルを変換するには `jsx --extension jsx src/ build/` コマンドを使用してください。
35 -
36 -このツールの使用方法についての詳細の情報については、 `jsx --help` コマンドを使用してください。
37 -
38 -
39 -### 役に立つオープンソースのプロジェクト
40 -
41 -オープンソースコミュニティがJSXをいくつかのエディタやビルドシステムで使用するためのツールを作成しました。一覧は[JSXのインテグレーション](https://github.com/facebook/react/wiki/Complementary-Tools#jsx-integrations)を参照してください。
docs/docs/09-tooling-integration.ko-KR.md deleted
-80
@@ -1,80 +0,0 @@
1 ----
2 -id: tooling-integration-ko-KR
3 -title: 툴 통합
4 -permalink: docs/tooling-integration-ko-KR.html
5 -prev: more-about-refs-ko-KR.html
6 -next: addons-ko-KR.html
7 ----
8 -
9 -모든 프로젝트는 JavaScript를 빌드, 배포할 때 다른 시스템을 사용합니다. 우리는 가능한 한 React를 환경에 구속받지 않도록 하려 노력했습니다.
10 -
11 -## React
12 -
13 -### CDN-호스트 React
14 -
15 -[다운로드 페이지](/react/downloads.html)에서 React의 CDN 호스트 버전을 제공합니다. 이 미리 빌드된 파일들은 UMD 모듈 포맷을 사용합니다. 간단한 `<script>` 태그로 넣어보면 `React` 글로벌이 환경으로 주입(inject)될 것입니다. CommonJS와 AMD환경에서 별도의 작업 없이도 동작해야 합니다.
16 -
17 -
18 -### master 사용하기
19 -
20 -[GitHub 저장소](https://github.com/facebook/react)의 `master`에 빌드 방법이 있습니다. 이는 `build/modules`에 CommonJS 모듈 트리를 빌드합니다. 이는 CommonJS를 지원하는 어떤 환경이나 패키징 툴에도 넣을 수 있습니다.
21 -
22 -## JSX
23 -
24 -### 브라우저에서 JSX 변환
25 -
26 -JSX를 사용하신다면, Babel에서 browser.js라는 [개발용 브라우저 ES6, JSX 변환기](http://babeljs.io/docs/usage/browser/)를 제공합니다. 이는 `babel-core`의 npm 릴리스나 [CDNJS](http://cdnjs.com/libraries/babel-core)로 넣을 수 있습니다. `<script type="text/babel">`를 넣으면 JSX 변환기가 작동합니다.
27 -
28 -> 주의:
29 ->
30 -> 브라우저 JSX 변환기는 꽤 크고 안 할 수도 있는 클라이언트 측 연산을 하게 됩니다. 프로덕션 환경에서 사용하지 마시고, 다음 단락을 보세요.
31 -
32 -
33 -### 상용화하기: 미리 컴파일된 JSX
34 -
35 -[npm](https://www.npmjs.com/) 모듈을 가지고 있다면, `npm install -g babel-cli`를 실행할 수 있습니다. Babel은 React v0.12이상을 내장 지원합니다. 태그는 자동적으로 동등한 `React.createElement(...)`로 변환되며, `displayName`은 모든 `React.createClass` 호출에 자동으로 추론, 추가됩니다.
36 -
37 -이 툴은 JSX 구문을 일반적인 JavaScript파일로 변환해 브라우져에서 바로 실행할 수 있도록 합니다. 디렉터리를 감시해 파일이 변경되었을 때 자동으로 변환하도록 할 수도 있습니다. 예를 들면 `babel --watch src/ --out-dir lib/` 이렇게요.
38 -
39 -Babel 6부터 기본값으로 변환기가 포함되지 않게 되었습니다. 이는 `babel` 명령을 실행할 때나 `.babelrc`에 반드시 옵션을 지정해야 한다는 뜻입니다. React를 사용할 때 가장 일반적인 방법은 `es2015`, `react` 프리셋을 사용하는 것입니다. Babel의 변경에 대한 좀 더 자세한 정보는 [블로그에 올라온 Babel 6 공지 글](http://babeljs.io/blog/2015/10/29/6.0.0/)을 읽어보세요.
40 -
41 -ES2015 문법과 React를 사용하려 할 경우의 예제입니다.
42 -
43 -```
44 -npm install babel-preset-es2015 babel-preset-react
45 -babel --presets es2015,react --watch src/ --out-dir lib/
46 -```
47 -
48 -기본적으로는 JSX 파일들은 `.js` 확장자로 변환됩니다. 바벨을 어떻게 사용하는지 더 자세하게 알고싶으시면 `babel --help`를 실행해 보세요.
49 -
50 -출력 예:
51 -
52 -```
53 -$ cat test.jsx
54 -var HelloMessage = React.createClass({
55 - render: function() {
56 - return <div>Hello {this.props.name}</div>;
57 - }
58 -});
59 -
60 -ReactDOM.render(<HelloMessage name="John" />, mountNode);
61 -$ babel test.jsx
62 -"use strict";
63 -var HelloMessage = React.createClass({
64 - displayName: "HelloMessage",
65 - render: function render() {
66 - return React.createElement(
67 - "div",
68 - null,
69 - "Hello ",
70 - this.props.name
71 - );
72 - }
73 -});
74 -
75 -ReactDOM.render(React.createElement(HelloMessage, { name: "John" }), mountNode);
76 -```
77 -
78 -### 도움되는 오픈소스 프로젝트들
79 -
80 -오픈 소스 커뮤니티는 JSX와 연동하는 여러 에디터와 빌드 시스템을 만들었습니다. 전 목록은 [JSX 연동](https://github.com/facebook/react/wiki/Complementary-Tools#jsx-integrations)에서 보세요.
docs/docs/09-tooling-integration.md deleted
-13
@@ -1,13 +0,0 @@
1 ----
2 -id: tooling-integration
3 -title: Tooling Integration
4 -permalink: docs/tooling-integration.html
5 -prev: more-about-refs.html
6 -next: language-tooling.html
7 ----
8 -
9 -We've tried to make React as environment-agnostic as possible. People use React in a variety of languages (JavaScript, TypeScript, ClojureScript, etc) and in a variety of environments (web, iOS, Android, NodeJS, Nashorn, etc). There are many tools to help you build great applications. In these sections we introduce some of the tools that are most commonly used together with React.
10 -
11 -* [Language Tooling](/react/docs/language-tooling.html) describes how to set up tools like Babel to transpile JSX for a better development experience.
12 -* [Package Management](/react/docs/package-management.html) describes how to configure React as a dependency of your project.
13 -* [Server-side Environments](/react/docs/environments.html) describes how to configure your environment for server-side rendering with React.
docs/docs/09-tooling-integration.zh-CN.md deleted
-13
@@ -1,13 +0,0 @@
1 ----
2 -id: tooling-integration-zh-CN
3 -title: 工具集成
4 -permalink: docs/tooling-integration-zh-CN.html
5 -prev: more-about-refs-zh-CN.html
6 -next: addons-zh-CN.html
7 ----
8 -
9 -我们尽可能使 React 与环境无关。大家可以在各种语言(JavaScript, TypeScript, ClojureScript, etc)与各种环境(web, iOS, Android, NodeJS, Nashorn, etc)中使用 React。这里有很多工具来帮助你创建优秀的应用。在这一节中我们介绍一些在 React 中最流行的工具。
10 -
11 -* [语言工具](/react/docs/language-tooling.html) 描述如何设置例如 Babel 的工具来编译 JSX。
12 -* [包管理](/react/docs/package-management.html) 讲述如何设置将 React 配置为项目中的依赖。
13 -* [服务端环境](/react/docs/environments.html) 讲述如何为 React 配置服务端渲染环境。
docs/docs/09.1-language-tooling.md deleted
-77
@@ -1,77 +0,0 @@
1 ----
2 -id: language-tooling
3 -title: Language Tooling
4 -permalink: docs/language-tooling.html
5 -prev: tooling-integration.html
6 -next: package-management.html
7 ----
8 -
9 -## ES2015 with JSX
10 -
11 -### In-browser JSX Transform
12 -
13 -If you like using JSX, Babel 5 provided an in-browser ES2015 and JSX transformer for development called browser.js that can be included from [CDNJS](https://cdnjs.com/libraries/babel-core/5.8.34). Include a `<script type="text/babel">` tag to engage the JSX transformer.
14 -
15 -> Note:
16 ->
17 -> The in-browser JSX transformer is fairly large and results in extraneous computation client-side that can be avoided. Do not use it in production — see the next section.
18 -
19 -### Productionizing: Precompiled JSX
20 -
21 -If you have [npm](https://www.npmjs.com/), you can run `npm install -g babel-cli`. Babel has built-in support for React v0.12+. Tags are automatically transformed to their equivalent `React.createElement(...)`, `displayName` is automatically inferred and added to all `React.createClass` calls.
22 -
23 -This tool will translate files that use JSX syntax to plain JavaScript files that can run directly in the browser. It will also watch directories for you and automatically transform files when they are changed; for example: `babel --watch src/ --out-dir lib/`.
24 -
25 -Beginning with Babel 6, there are no transforms included by default. This means that options must be specified when running the `babel` command, or a `.babelrc` must specify options. Additional packages must also be installed which bundle together a number of transforms, called presets. The most common use when working with React will be to include the `es2015` and `react` presets. More information about the changes to Babel can be found in [their blog post announcing Babel 6](http://babeljs.io/blog/2015/10/29/6.0.0).
26 -
27 -Here is an example of what you will do if using ES2015 syntax and React:
28 -
29 -```
30 -npm install babel-preset-es2015 babel-preset-react
31 -babel --presets es2015,react --watch src/ --out-dir lib/
32 -```
33 -
34 -By default JSX files with a `.js` extension are transformed. Run `babel --help` for more information on how to use Babel.
35 -
36 -Example output:
37 -
38 -```
39 -$ cat test.js
40 -function HelloMessage(props) {
41 - return <div>Hello {props.name}</div>;
42 -}
43 -
44 -ReactDOM.render(<HelloMessage name="John" />, mountNode);
45 -
46 -$ babel test.js
47 -"use strict";
48 -
49 -function HelloMessage(props) {
50 - return React.createElement(
51 - "div",
52 - null,
53 - "Hello ",
54 - props.name
55 - );
56 -}
57 -
58 -ReactDOM.render(React.createElement(HelloMessage, { name: "John" }), mountNode);
59 -```
60 -
61 -### Helpful Open-Source Projects
62 -
63 -The open-source community has built tools that integrate JSX with several editors and build systems. See [JSX integrations](https://github.com/facebook/react/wiki/Complementary-Tools#jsx-integrations) for the full list.
64 -
65 -## Flow
66 -
67 -Flow is a JavaScript type checker released by Facebook, and it supports JSX. For more info, checkout the [Flow homepage](http://flowtype.org/).
68 -
69 -
70 -## TypeScript
71 -
72 -TypeScript is a type-checker and transpiler that supports type-checking React and JSX.
73 -For more info, check out their guide on [getting started with React and Webpack](https://www.typescriptlang.org/docs/handbook/react-&-webpack.html), or learn more about [TypeScript's JSX support](https://www.typescriptlang.org/docs/handbook/jsx.html).
74 -
75 -To learn more about TypeScript in general, visit the [TypeScript homepage](https://www.typescriptlang.org/).
76 -
77 -
docs/docs/09.2-package-management.md deleted
-119
@@ -1,119 +0,0 @@
1 ----
2 -id: package-management
3 -title: Package Management
4 -permalink: docs/package-management.html
5 -prev: language-tooling.html
6 -next: environments.html
7 ----
8 -
9 -## CDN-hosted React
10 -
11 -We provide CDN-hosted versions of React [on our download page](/react/downloads.html). These pre-built files use the UMD module format. Dropping them in with a simple `<script>` tag will inject the `React` and `ReactDOM` globals into your environment. It should also work out-of-the-box in CommonJS and AMD environments.
12 -
13 -
14 -## Using React from npm
15 -
16 -You can use React with a CommonJS module system like [browserify](http://browserify.org/) or [webpack](https://webpack.github.io/). Use the [`react`](https://www.npmjs.com/package/react) and [`react-dom`](https://www.npmjs.com/package/react-dom) npm packages.
17 -
18 -```js
19 -// main.js
20 -var React = require('react');
21 -var ReactDOM = require('react-dom');
22 -
23 -ReactDOM.render(
24 - <h1>Hello, world!</h1>,
25 - document.getElementById('example')
26 -);
27 -```
28 -
29 -Configure [babel](https://babeljs.io/) with a `.babelrc` file:
30 -
31 - ```json
32 - { "presets": ["react"] }
33 - ```
34 -
35 - > Note:
36 - >
37 - > If you are using ES2015, you will want to also use the `babel-preset-es2015` package.
38 -
39 -
40 -To install React DOM and build your bundle with browserify:
41 -
42 -```sh
43 -$ npm install --save react react-dom babelify babel-preset-react
44 -$ browserify -t [ babelify ] main.js -o bundle.js
45 -```
46 -
47 -To install React DOM and build your bundle with webpack:
48 -
49 -```sh
50 -$ npm install --save react react-dom babel-preset-react babel-loader babel-core
51 -$ webpack main.js bundle.js --module-bind 'js=babel-loader'
52 -```
53 -
54 -> Note:
55 ->
56 -> If you are using ES2015, you will want to also use the `babel-preset-es2015` package.
57 -
58 -**Note:** by default, React will be in development mode, which is slower, and not advised for production. To use React in production mode, set the environment variable `NODE_ENV` to `production` (using envify or webpack's DefinePlugin). For example:
59 -
60 -```js
61 -new webpack.DefinePlugin({
62 - "process.env": {
63 - NODE_ENV: JSON.stringify("production")
64 - }
65 -});
66 -```
67 -
68 -Update your HTML file as below:
69 -
70 -```html{9}
71 -<!DOCTYPE html>
72 -<html>
73 - <head>
74 - <meta charset="UTF-8" />
75 - <title>Hello React!</title>
76 - </head>
77 - <body>
78 - <div id="example"></div>
79 - <script src="bundle.js"></script>
80 - </body>
81 -</html>
82 -```
83 -
84 -## Using React from Bower
85 -
86 -Bower is a package manager optimized for the front-end development. If multiple packages depend on a package - jQuery for example - Bower will download jQuery just once. This is known as a flat dependency graph and it helps reduce page load. For more info, visit [http://bower.io/](http://bower.io/).
87 -
88 -If you'd like to use bower, it's as easy as:
89 -
90 -```
91 -bower install --save react
92 -```
93 -
94 -```html
95 -<!DOCTYPE html>
96 -<html>
97 - <head>
98 - <meta charset="UTF-8" />
99 - <title>Hello React!</title>
100 - <script src="bower_components/react/react.js"></script>
101 - <script src="bower_components/react/react-dom.js"></script>
102 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
103 - </head>
104 - <body>
105 - <div id="example"></div>
106 - <script type="text/babel">
107 - ReactDOM.render(
108 - <h1>Hello, world!</h1>,
109 - document.getElementById('example')
110 - );
111 - </script>
112 - </body>
113 -</html>
114 -```
115 -
116 -
117 -## Using master
118 -
119 -We have instructions for building from `master` [in our GitHub repository](https://github.com/facebook/react).
docs/docs/09.3-environments.md deleted
-80
@@ -1,80 +0,0 @@
1 ----
2 -id: environments
3 -title: Server-side Environments
4 -permalink: docs/environments.html
5 -prev: package-management.html
6 -next: addons.html
7 ----
8 -
9 -One of the great things about React is that it doesn't require the DOM as a dependency, which means it is possible to render a React application on the server and send the HTML markup down to the client. There are a few things that React expects, so this guide will help you get started in your preferred environment.
10 -
11 -
12 -## Node.js
13 -
14 -[Node.js](http://nodejs.org/) is a popular JavaScript runtime that comes with an extensive core library and support for installing packages from npm to expand on the basic functionality. As we've described elsewhere in the documentation, you can install `react` and `react-dom` from npm.
15 -
16 -Example:
17 -
18 -```js
19 -var React = require('react');
20 -var ReactDOMServer = require('react-dom/server');
21 -
22 -var element = React.createElement('div', null, 'Hello World!');
23 -console.log(ReactDOMServer.renderToString(element));
24 -```
25 -
26 -If you use JSX, you may want to pre-compile your components. Alternatively you may want to consider using [Babel's require hook](https://babeljs.io/docs/usage/require/) or [`babel-node`](https://babeljs.io/docs/usage/cli/#babel-node).
27 -
28 -> Note:
29 ->
30 -> Some versions of Node.js have an `Object.assign` implementation that does not preserve key order. This can cause errors when validating the markup, creating a warning that says "React attempted to reuse markup in a container but the checksum was invalid". If you run into this issue, you can override `Object.assign` to use a polyfill that preserves key order. For more details, see [Issue #6451](https://github.com/facebook/react/issues/6451).
31 -
32 -C#
33 -==
34 -
35 -Support for server-side component rendering and JSX compilation (via Babel) in a .NET Framework / ASP.NET environment is provided through our [ReactJS.NET](http://reactjs.net/) project.
36 -
37 -
38 -## Nashorn
39 -
40 -Nashorn is a lightweight high-performance JavaScript runtime that runs within the JVM. React should run out of the box in Java 8+.
41 -
42 -Example:
43 -
44 -```java
45 -import java.io.IOException;
46 -import java.io.InputStream;
47 -import java.io.FileReader;
48 -
49 -import javax.script.ScriptEngine;
50 -import javax.script.ScriptEngineManager;
51 -import javax.script.ScriptException;
52 -
53 -public class ReactRender
54 -{
55 - public static void main(String[] args) throws ScriptException, IOException {
56 - ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn");
57 -
58 - // These files can be downloaded as a part of the starter kit
59 - // from https://facebook.github.io/react
60 - nashorn.eval(new FileReader("path/to/react.js"));
61 - nashorn.eval(new FileReader("path/to/react-dom-server.js"));
62 -
63 - System.out.println(nashorn.eval(
64 - "ReactDOMServer.renderToString(" +
65 - "React.createElement('div', null, 'Hello World!')" +
66 - ");"
67 - ));
68 - }
69 -}
70 -```
71 -
72 -If your application uses npm packages, or you want to transform JSX in Nashorn, you will need to do some additional environment setup. The following resources may be helpful in getting you started:
73 -
74 - * [http://winterbe.com/posts/2015/02/16/isomorphic-react-webapps-on-the-jvm/](http://winterbe.com/posts/2015/02/16/isomorphic-react-webapps-on-the-jvm/)
75 - * [https://github.com/nodyn/jvm-npm](https://github.com/nodyn/jvm-npm)
76 - * [https://gist.github.com/aesteve/883e0fd33390451cb8eb](https://gist.github.com/aesteve/883e0fd33390451cb8eb)
77 -
78 -> Note:
79 ->
80 -> Using Babel within Nashorn will require Java 8u72+, as update 72 fixed [JDK-8135190](https://bugs.openjdk.java.net/browse/JDK-8135190).
docs/docs/10-addons.it-IT.md deleted
-25
@@ -1,25 +0,0 @@
1 ----
2 -id: addons-it-IT
3 -title: Add-ons
4 -permalink: docs/addons-it-IT.html
5 -prev: tooling-integration-it-IT.html
6 -next: animation-it-IT.html
7 ----
8 -
9 -`React.addons` è il luogo in cui parcheggiamo utili strumenti per costruire applicazioni React. **Questi strumenti devono essere considerati sperimentali** ma saranno eventualmente inclusi nel nucleo o una libreria ufficiale di utilities:
10 -
11 -- [`TransitionGroup` e `CSSTransitionGroup`](animation-it-IT.html), per gestire animazioni e transizioni che sono solitamente difficili da implementare, come ad esempio prima della rimozione di un componente.
12 -- [`LinkedStateMixin`](two-way-binding-helpers-it-IT.html), per semplificare la coordinazione tra lo stato del componente e l'input dell'utente in un modulo.
13 -- [`cloneWithProps`](clone-with-props-it-IT.html), per eseguire una copia superficiale di componenti React e cambiare le loro proprietà.
14 -- [`createFragment`](create-fragment-it-IT.html), per creare un insieme di figli con chiavi esterne.
15 -- [`update`](update-it-IT.html), una funzione di utilità che semplifica la gestione di dati immutabili in JavaScript.
16 -- [`PureRenderMixin`](pure-render-mixin-it-IT.html), un aiuto per incrementare le prestazioni in certe situazioni.
17 -
18 -Gli add-ons elencati di seguito si trovano esclusivamente nella versione di sviluppo (non minificata) di React:
19 -
20 -- [`TestUtils`](test-utils-it-IT.html), semplici helper per scrivere dei test case (soltanto nella build non minificata).
21 -- [`Perf`](perf-it-IT.html), per misurare le prestazioni e fornirti suggerimenti per l'ottimizzazione.
22 -
23 -Per ottenere gli add-on, usa `react-with-addons.js` (e la sua controparte non minificata) anziché il solito `react.js`.
24 -
25 -Quandi si usa il pacchetto react di npm, richiedi semplicemente `require('react/addons')` anziché `require('react')` per ottenere React con tutti gli add-on.
docs/docs/10-addons.ja-JP.md deleted
-24
@@ -1,24 +0,0 @@
1 ----
2 -id: addons
3 -title: アドオン
4 -permalink: docs/addons-ja-JP.html
5 -prev: tooling-integration-ja-JP.html
6 -next: animation-ja-JP.html
7 ----
8 -
9 -`React.addons` はReactのアプリケーションを作成する上で便利なユーティリティを置いておくための場所です。 **それらは実験的なものであると考えられるべきです。** しかし、ゆくゆくはコアに入ってくるか、以下のような承認されたユーティリティとなるでしょう。
10 -
11 -- アニメーションや推移を扱う[`TransitionGroup` や `CSSTransitionGroup`](animation-ja-JP.html)は多くの場合実行するのが簡単ではありません。例えば、コンポーネントの削除の前などは。
12 -- [`LinkedStateMixin`](two-way-binding-helpers-ja-JP.html)はユーザのフォームの入力データとコンポーネントのstateの間の調整を単純化します。
13 -- [`cloneWithProps`](clone-with-props-ja-JP.html)はReactのコンポーネントのシャローコピーを作成したり、それらのpropsを変更したりします。
14 -- [`createFragment`](create-fragment-ja-JP.html)は外部のキー化された子要素のセットを作成します。
15 -- [`update`](update-ja-JP.html)はJavaScriptでイミュータブルなデータを扱うことを簡単にするヘルパーの関数です。
16 -- [`PureRenderMixin`](pure-render-mixin-ja-JP.html)は特定のシチュエーションでパフォーマンスを改善します。
17 -以下のアドオンはReactだけの開発版(縮小されていない版)です。
18 -
19 -- [`TestUtils`](test-utils-ja-JP.html)はテストケースを記述する単純なヘルパーです(縮小されていないビルドのみ)。
20 -- [`Perf`](perf-ja-JP.html)はパフォーマンスを測り、どこを最適化するかのヒントを与えます。
21 -
22 -アドオンを使うには、共通の `react.js` を使うよりも `react-with-addons.js` (とその縮小されたもの)を使ってください。
23 -
24 -npmからReactのパッケージを使う際には、Reactと全てのアドオンを使うために `require('react')` を使う代わりに、単純に `require('react/addons')` を使ってください。
docs/docs/10-addons.ko-KR.md deleted
-23
@@ -1,23 +0,0 @@
1 ----
2 -id: addons-ko-KR
3 -title: 애드온
4 -permalink: docs/addons-ko-KR.html
5 -prev: tooling-integration-ko-KR.html
6 -next: animation-ko-KR.html
7 ----
8 -
9 -React 애드온은 React 앱을 만드는 데 유용한 유틸리티의 모음입니다. **실험적인 기능으로 취급해야 하고** 코어보다 더 자주 변경될 수 있습니다.
10 -
11 -- [`TransitionGroup` 과 `CSSTransitionGroup`](animation-ko-KR.html)은 예를 들면 컴포넌트 삭제 직전의 트랜지션 처럼, 구현하기 까다로운 애니메이션과 트랜지션을 다룹니다.
12 -- [`LinkedStateMixin`](two-way-binding-helpers-ko-KR.html)는 사용자 입력과 컴포넌트의 state사이의 조정(coordination)을 단순화 합니다.
13 -- [`cloneWithProps`](clone-with-props-ko-KR.html)는 React 컴포넌트를 얕은 복사를 하고 props를 변경합니다.
14 -- [`createFragment`](create-fragment-ko-KR.html)는 외부에서 키가 할당된 자식들의 모음을 만듭니다.
15 -- [`update`](update-ko-KR.html)는 JavaScript안에서 불변 데이터를 다루기 쉽게하는 헬퍼 함수입니다.
16 -- [`PureRenderMixin`](pure-render-mixin-ko-KR.html)는 특정 상황에서 성능을 향상시켜 줍니다.
17 -
18 -밑에 있는 애드온은 React 개발 (압축되지 않은) 버전에서만 사용가능 합니다.
19 -
20 -- [`TestUtils`](test-utils-ko-KR.html)는 테스트 케이스를 적기 위한 간단한 헬퍼입니다. (압축되지 않은 빌드에서만 사용가능)
21 -- [`Perf`](perf-ko-KR.html)는 성능을 측정하고, 최적화를 위한 힌트를 제공합니다.
22 -
23 -애드온을 쓰려면, npm에서 각각 설치하세요.(예를 들면, `npm install react-addons-pure-render-mixin`) npm을 사용하지 않는 애드온 사용법에 대한 지원은 없습니다.
docs/docs/10-addons.md deleted
-24
@@ -1,24 +0,0 @@
1 ----
2 -id: addons
3 -title: Add-ons
4 -permalink: docs/addons.html
5 -prev: environments.html
6 -next: animation.html
7 ----
8 -
9 -The React add-ons are a collection of useful utility modules for building React apps. **These should be considered experimental** and tend to change more often than the core.
10 -
11 -- [`TransitionGroup` and `CSSTransitionGroup`](animation.html), for dealing with animations and transitions that are usually not simple to implement, such as before a component's removal.
12 -- [`LinkedStateMixin`](two-way-binding-helpers.html), to simplify the coordination between user's form input data and the component's state.
13 -- [`cloneWithProps`](clone-with-props.html), to make shallow copies of React components and change their props.
14 -- [`createFragment`](create-fragment.html), to create a set of externally-keyed children.
15 -- [`update`](update.html), a helper function that makes dealing with immutable data in JavaScript easier.
16 -- [`PureRenderMixin`](pure-render-mixin.html), a performance booster under certain situations.
17 -- [`shallowCompare`](shallow-compare.html), a helper function that performs a shallow comparison for props and state in a component to decide if a component should update.
18 -
19 -The add-ons below are in the development (unminified) version of React only:
20 -
21 -- [`TestUtils`](test-utils.html), simple helpers for writing test cases.
22 -- [`Perf`](perf.html), a performance profiling tool for finding optimization opportunities.
23 -
24 -To get the add-ons, install them individually from npm (e.g., `npm install react-addons-pure-render-mixin`). We don't support using the addons if you're not using npm.
docs/docs/10-addons.zh-CN.md deleted
-24
@@ -1,24 +0,0 @@
1 ----
2 -id: addons-zh-CN
3 -title: 插件
4 -permalink: docs/addons-zh-CN.html
5 -prev: tooling-integration-zh-CN.html
6 -next: animation-zh-CN.html
7 ----
8 -
9 -React插件是一系列的用来构建 React app的有用模块。 **这些应该被认为是实验性的** 并趋向于比core变动更频繁。
10 -
11 -- [`TransitionGroup` 和 `CSSTransitionGroup`](animation.html), 用来处理通常不能简单实现的动画和转换,比如在组件移除之前。
12 -- [`LinkedStateMixin`](two-way-binding-helpers.html), 简化用户的表单输入数据与组件状态的协调。
13 -- [`cloneWithProps`](clone-with-props.html), 创建React组件的浅拷贝并改变它们的props。
14 -- [`createFragment`](create-fragment.html), 创建一组外键的子级。
15 -- [`update`](update.html), 一个使不可变数据在JavaScript里更易处理的辅助函数。
16 -- [`PureRenderMixin`](pure-render-mixin.html), 一个特定情况下的性能优化器。
17 -- [`shallowCompare`](shallow-compare.html), 一个辅助函数,用来对 props 和 state在组件里 执行浅比较 以决定一个组件是否应该更新。
18 -
19 -下面的插件只存在开发版(未压缩)React中:
20 -
21 -- [`TestUtils`](test-utils.html), 用于写测试用例的简单的辅助工具。
22 -- [`Perf`](perf.html), 一个用于查找优化机会的性能分析工具。
23 -
24 -要获取插件,单独从npm安装他们(例如 `npm install react-addons-pure-render-mixin`).我们不支持使用插件如果你没有用npm.
docs/docs/10.1-animation.it-IT.md deleted
-261
@@ -1,261 +0,0 @@
1 ----
2 -id: animation-it-IT
3 -title: Animazioni
4 -permalink: docs/animation-it-IT.html
5 -prev: addons-it-IT.html
6 -next: two-way-binding-helpers-it-IT.html
7 ----
8 -
9 -React offre un componente addon `ReactTransitionGroup` come una API di basso livello per le animazioni, e un `ReactCSSTransitionGroup` per implementare facilmente animazioni e transizioni CSS di base.
10 -
11 -## API di Alto Livello: `ReactCSSTransitionGroup`
12 -
13 -`ReactCSSTransitionGroup` è basato su `ReactTransitionGroup` ed è una maniera semplice di effettuare transizioni e animazioni CSS quando un componente React viene aggiunto o rimosso dal DOM. È ispirato all'eccellente libreria [ng-animate](http://www.nganimate.org/).
14 -
15 -### Per Cominciare
16 -
17 -`ReactCSSTransitionGroup` è l'interfaccia a `ReactTransitions`. Questo è un semplice elemento che racchiude tutti i componenti che desideri animare. Ecco un esempio in cui facciamo apparire e scomparire gli elementi di una lista.
18 -
19 -```javascript{28-30}
20 -var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
21 -
22 -var TodoList = React.createClass({
23 - getInitialState: function() {
24 - return {items: ['ciao', 'mondo', 'clicca', 'qui']};
25 - },
26 - handleAdd: function() {
27 - var newItems =
28 - this.state.items.concat([prompt('Scrivi del testo')]);
29 - this.setState({items: newItems});
30 - },
31 - handleRemove: function(i) {
32 - var newItems = this.state.items;
33 - newItems.splice(i, 1);
34 - this.setState({items: newItems});
35 - },
36 - render: function() {
37 - var items = this.state.items.map(function(item, i) {
38 - return (
39 - <div key={item} onClick={this.handleRemove.bind(this, i)}>
40 - {item}
41 - </div>
42 - );
43 - }.bind(this));
44 - return (
45 - <div>
46 - <button onClick={this.handleAdd}>Aggiungi Elemento</button>
47 - <ReactCSSTransitionGroup
48 - transitionName="example"
49 - transitionEnterTimeout={500}
50 - transitionLeaveTimeout={300}>
51 - {items}
52 - </ReactCSSTransitionGroup>
53 - </div>
54 - );
55 - }
56 -});
57 -```
58 -> Nota:
59 ->
60 -> Devi fornire [l'attributo `key`](/react/docs/multiple-components.html#dynamic-children) per tutti i figli di `ReactCSSTransitionGroup`, anche quando stai visualizzando un singolo elemento. Questo è il modo in cui React determina quali figli sono stati aggiunti, rimossi, o sono rimasti.
61 -
62 -In questo componente, quando un nuovo elemento viene aggiunto a `ReactCSSTransitionGroup` riceverà la classe CSS `example-enter` e la classe CSS `example-enter-active` allo scatto successivo. Questa è una convenzione basata sul valore della proprietà `transitionName`.
63 -
64 -Puoi usare queste classi per scatenare una animazione o transizione CSS. Ad esempio, prova ad aggiungere questo CSS e aggiungere un nuovo elemento alla lista:
65 -
66 -```css
67 -.example-enter {
68 - opacity: 0.01;
69 -}
70 -
71 -.example-enter.example-enter-active {
72 - opacity: 1;
73 - transition: opacity 500ms ease-in;
74 -}
75 -
76 -.example-leave {
77 - opacity: 1;
78 -}
79 -
80 -.example-leave.example-leave-active {
81 - opacity: 0.01;
82 - transition: opacity 300ms ease-in;
83 -}
84 -```
85 -
86 -Ti accorgerai che la durata delle animazioni devono essere specificate sia nel CSS che nel metodo render; questo suggerisce a React quando rimuovere le classi di animazione dall'elemento e -- se sta venendo rimosso -- quando rimuovere l'elemento dal DOM.
87 -
88 -### Animare il Montaggio Iniziale
89 -
90 -`ReactCSSTransitionGroup` fornisce la proprietà opzionale `transitionAppear`, per aggiungere una fase aggiuntiva di transizione al montaggio iniziale del componente. In genere non c'è alcuna fase di transizione al montaggio iniziale in quanto il valore predefinito di `transitionAppear` è `false`. L'esempio seguente passa la proprietà `transitionAppear` con il valore `true`.
91 -
92 -```javascript{3-5}
93 - render: function() {
94 - return (
95 - <ReactCSSTransitionGroup
96 - transitionName="example"
97 - transitionAppear={true}
98 - transitionAppearTimeout={500}>
99 - <h1>Dissolvenza al Montaggio Iniziale</h1>
100 - </ReactCSSTransitionGroup>
101 - );
102 - }
103 -```
104 -
105 -Durante il montaggio iniziale `ReactCSSTransitionGroup` otterrà la classe CSS `example-appear` e la classe CSS `example-appear-active` allo scatto successivo.
106 -
107 -```css
108 -.example-appear {
109 - opacity: 0.01;
110 -}
111 -
112 -.example-appear.example-appear-active {
113 - opacity: 1;
114 - transition: opacity .5s ease-in;
115 -}
116 -```
117 -
118 -Al montaggio iniziale, tutti i figli di `ReactCSSTransitionGroup` saranno marcati come `appear` ma non `enter`. Tuttavia, tutti i figli aggiunti in seguito ad un `ReactCSSTransitionGroup` esistente saranno marcati come `enter` ma non `appear`.
119 -
120 -> Nota:
121 ->
122 -> La proprietà `transitionAppear` è stata aggiunta a `ReactCSSTransitionGroup` nella versione `0.13`. Per mantenere la compatibilità con le versioni precedenti, il valore predefinito è impostato a `false`.
123 -
124 -### Classi Personalizzate
125 -
126 -È anche possibile usare nomi di classi personalizzate per ciascuna delle fasi delle tue transizioni. Anziché passare una stringa come valore di `transitionName` puoi assegnare un oggetto che contiene i nomi delle classi `enter` o `leave`, oppure un oggetto contenente i nomi delle classi per `enter`, `enter-active`, `leave-active`e `leave`. Se vengono forniti soltanto i nomi delle classi enter e leave, le classi per enter-active e leave-active saranno determinate aggiungendo il suffisso '-active' ai rispettivi nomi delle classi. Ecco due esempi che usano le classi personalizzate:
127 -
128 -```javascript
129 - ...
130 - <ReactCSSTransitionGroup
131 - transitionName={ {
132 - enter: 'enter',
133 - enterActive: 'enterActive',
134 - leave: 'leave',
135 - leaveActive: 'leaveActive',
136 - appear: 'appear',
137 - appearActive: 'appearActive'
138 - } }>
139 - {item}
140 - </ReactCSSTransitionGroup>
141 -
142 - <ReactCSSTransitionGroup
143 - transitionName={ {
144 - enter: 'enter',
145 - leave: 'leave',
146 - appear: 'appear'
147 - } }>
148 - {item2}
149 - </ReactCSSTransitionGroup>
150 - ...
151 -```
152 -
153 -### I Gruppi di Animazioni Devono Essere Montati per Funzionare
154 -
155 -Per applicare le transizioni ai suoi figli, il `ReactCSSTransitionGroup` deve già essere montato nel DOM oppure la proprietà `transitionAppear` deve essere impostata a `true`. L'esempio seguente non funziona, poiché `ReactCSSTransitionGroup` sta venendo montato assieme al nuovo elemento, anziché il nuovo elemento venire montato dentro di esso. Confronta questo esempio con la sezione precedente [Per Cominciare](#getting-started) per notare la differenza.
156 -
157 -```javascript{12-15}
158 - render: function() {
159 - var items = this.state.items.map(function(item, i) {
160 - return (
161 - <div key={item} onClick={this.handleRemove.bind(this, i)}>
162 - <ReactCSSTransitionGroup transitionName="example">
163 - {item}
164 - </ReactCSSTransitionGroup>
165 - </div>
166 - );
167 - }, this);
168 - return (
169 - <div>
170 - <button onClick={this.handleAdd}>Aggiungi Elemento</button>
171 - {items}
172 - </div>
173 - );
174 - }
175 -```
176 -
177 -### Animare Uno o Nessun Elemento
178 -
179 -Nell'esempio precedente, abbiamo visualizzato una lista di elementi in `ReactCSSTransitionGroup`. Tuttavia, i figli di `ReactCSSTransitionGroup` possono anche essere un solo o nessun elemento. Questo rende possibile animare un singolo elemento che viene aggiunto o rimosso. Similarmente, puoi animare un nuovo elemento che sistituisce l'elemento corrente. Ad esempio, possiamo implementare un semplice carosello di immagini come segue:
180 -
181 -```javascript{10-12}
182 -var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
183 -
184 -var ImageCarousel = React.createClass({
185 - propTypes: {
186 - imageSrc: React.PropTypes.string.isRequired
187 - },
188 - render: function() {
189 - return (
190 - <div>
191 - <ReactCSSTransitionGroup
192 - transitionName="carousel"
193 - transitionEnterTimeout={300}
194 - transitionLeaveTimeout={300}>
195 - <img src={this.props.imageSrc} key={this.props.imageSrc} />
196 - </ReactCSSTransitionGroup>
197 - </div>
198 - );
199 - }
200 -});
201 -```
202 -
203 -### Disattivare le Animazioni
204 -
205 -Se lo desideri, puoi disattivare le animazioni `enter` o `leave`. Ad esempio, a volte potresti volere un'animazione per `enter` ma non una per `leave`, ma `ReactCSSTransitionGroup` attende che l'animazione sia completata prima di rimuovere il tuo nodo DOM. Puoi aggiungere le proprietà `transitionEnter={false}` o `transitionLeave={false}` a `ReactCSSTransitionGroup` per disattivare le rispettive animazioni.
206 -
207 -> Nota:
208 ->
209 -> Quando si usa `ReactCSSTransitionGroup`, non c'è alcun modo per cui i tuoi componenti vengano avvisati quando la transizione è terminata o per effettuare una logica complessa durante l'animazione. Se vuoi un controllo più fine, puoi usare la API di basso livello `ReactTransitionGroup` che fornisce degli hook che puoi utilizzare per effettuare transizioni personalizzate.
210 -
211 -## API di Basso Livello: `ReactTransitionGroup`
212 -
213 -`ReactTransitionGroup` è la base per le animazioni. È accessibile come `React.addons.TransitionGroup`. Quando vi sono aggiunti o rimossi dichiarativamente dei figli (come negli esempi precedenti) degli speciali hook del ciclo di vita sono invocati su di essi.
214 -
215 -### `componentWillAppear(callback)`
216 -
217 -Viene chiamato allo stesso momento di `componentDidMount()` per i componenti inizialmente montati in un `TransitionGroup`. Bloccherà l'esecuzione di altre animazioni finché `callback` non viene chiamata. Viene chiamata solo durante il rendering iniziale di un `TransitionGroup`.
218 -
219 -### `componentDidAppear()`
220 -
221 -Viene chiamato dopo che la funzione `callback` passata a `componentWillAppear` è stata chiamata.
222 -
223 -### `componentWillEnter(callback)`
224 -
225 -Viene chiamato allo stesso momento di `componentDidMount()` per i componenti aggiunti ad un `TransitionGroup` esistente. Bloccherà l'esecuzione di altre animazioni finché `callback` non viene chiamata. Non viene chiamata durante il rendering iniziale di un `TransitionGroup`.
226 -
227 -### `componentDidEnter()`
228 -
229 -Viene chiamato dopo che la funzione `callback` passata a `componentWillEnter` è stata chiamata.
230 -
231 -### `componentWillLeave(callback)`
232 -
233 -Viene chiamato quando il figlio è stato rimosso dal `ReactTransitionGroup`. Nonostante il figlio sia stato rimosso, `ReactTransitionGroup` lo manterrà nel DOM finché `callback` non viene chiamata.
234 -
235 -### `componentDidLeave()`
236 -
237 -Viene chiamato quando la `callback` `willLeave` viene chiamata (contemporaneamente a `componentWillUnmount`).
238 -
239 -### Rendering di un Componente Diverso
240 -
241 -In maniera predefinita, `ReactTransitionGroup` viene visualizzato come uno `span`. Puoi cambiare questo comportamento fornento una proprietà `component`. Ad esempio, ecco come puoi visualizzare un `<ul>`:
242 -
243 -```javascript{1}
244 -<ReactTransitionGroup component="ul">
245 - ...
246 -</ReactTransitionGroup>
247 -```
248 -
249 -È possibile utilizzare ciascun componente DOM che React può visualizzare. Tuttavia, `component` non deve necessariamente essere un componente DOM. Può infatti essere qualunque componente React; anche componenti scritti da te!
250 -
251 -> Nota:
252 ->
253 -> Prima della v0.12, quando venivano usati componenti DOM, la proprietà `component` doveva essere un riferimento a `React.DOM.*`. Dal momento che il componente è semplicemente passato a `React.createElement`, deve ora essere una stringa. Per componenti compositi si deve passare il metodo factory.
254 -
255 -Ciascuna proprietà aggiuntiva definita dall'utente diverrà una proprietà del componente visualizzato. Ad esempio, ecco come visualizzeresti un `<ul>` con una classe CSS:
256 -
257 -```javascript{1}
258 -<ReactTransitionGroup component="ul" className="animated-list">
259 - ...
260 -</ReactTransitionGroup>
261 -```
docs/docs/10.1-animation.ja-JP.md deleted
-230
@@ -1,230 +0,0 @@
1 ----
2 -id: animation
3 -title: アニメーション
4 -permalink: docs/animation-ja-JP.html
5 -prev: addons-ja-JP.html
6 -next: two-way-binding-helpers-ja-JP.html
7 ----
8 -
9 -ReactはアニメーションのためにローレベルAPIとして `ReactTransitionGroup` アドオンコンポーネントと、基本的なCSSアニメーションとトランジションを簡単に実行するために `ReactCSSTransitionGroup` を提供しています。
10 -
11 -## ハイレベルAPI: `ReactCSSTransitionGroup`
12 -
13 -`ReactCSSTransitionGroup` は `ReactTransitionGroup` に基づいており、ReactコンポーネントがDOMを作成したり、削除したりする際に、CSSのトランジションとアニメーションを行う簡単な方法です。これは、素晴らしい[ng-animate](http://www.nganimate.org/)ライブラリにインスパイアされています。
14 -
15 -### はじめに
16 -
17 -`ReactCSSTransitionGroup` は `ReactTransitions` のインターフェースです。アニメーションに関心がある全てのコンポーネントをラップする単純な要素です。以下が、リストのアイテムをフェードインやフェードアウトさせる例です。
18 -
19 -```javascript{28-30}
20 -var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
21 -
22 -var TodoList = React.createClass({
23 - getInitialState: function() {
24 - return {items: ['hello', 'world', 'click', 'me']};
25 - },
26 - handleAdd: function() {
27 - var newItems =
28 - this.state.items.concat([prompt('Enter some text')]);
29 - this.setState({items: newItems});
30 - },
31 - handleRemove: function(i) {
32 - var newItems = this.state.items;
33 - newItems.splice(i, 1);
34 - this.setState({items: newItems});
35 - },
36 - render: function() {
37 - var items = this.state.items.map(function(item, i) {
38 - return (
39 - <div key={item} onClick={this.handleRemove.bind(this, i)}>
40 - {item}
41 - </div>
42 - );
43 - }.bind(this));
44 - return (
45 - <div>
46 - <button onClick={this.handleAdd}>Add Item</button>
47 - <ReactCSSTransitionGroup
48 - transitionName="example"
49 - transitionEnterTimeout={500}
50 - transitionLeaveTimeout={300}>
51 - {items}
52 - </ReactCSSTransitionGroup>
53 - </div>
54 - );
55 - }
56 -});
57 -```
58 -> 注意:
59 -> もし子要素を1つだけレンダリングするとしても、 `ReactCSSTransitionGroup` の全ての子要素に提供しなければなりません。これが、Reactが、子要素が作成されているか、削除されたか、あるいはそのままであるか判断する方法です。
60 -
61 -このコンポーネントでは、 `ReactCSSTransitionGroup` に新しいアイテムが追加された次の瞬間に、 `example-enter` CSSクラスと `example-enter-active` CSSクラスを得ます。これは、 `transitionName` propに基づく習慣です。
62 -
63 -これらのクラスはCSSアニメーションやトランジションのトリガーとして使うことができます。例えば、以下のようにして、このCSSを加え、新しいリストアイテムを加えてみましょう。
64 -
65 -```css
66 -.example-enter {
67 - opacity: 0.01;
68 - transition: opacity .5s ease-in;
69 -}
70 -
71 -.example-enter.example-enter-active {
72 - opacity: 1;
73 -}
74 -```
75 -
76 -アイテムを削除しようとしたときに、 `ReactCSSTransitionGroup` がDOMの中にそれを保持していることに気づくでしょう。縮小化されていないReactのビルドとアドオンを使っているならば、Reactがアニメーションやトランジションが起こることを予期しているという警告が出るでしょう。これは、 `ReactCSSTransitionGroup` がアニメーションが終わるまでDOM要素をページに保持し続けるからです。以下のCSSを加えてみましょう。
77 -
78 -```css
79 -.example-leave {
80 - opacity: 1;
81 - transition: opacity .5s ease-in;
82 -}
83 -
84 -.example-leave.example-leave-active {
85 - opacity: 0.01;
86 -}
87 -```
88 -
89 -### 最初のマウントにおけるアニメーション
90 -
91 -`ReactCSSTransitionGroup` は `transitionAppear` というオプションのプロパティを提供します。コンポーネントの最初のマウントの際に、更なるトランジションのフェーズを加えるためです。一般的には、 `transitionAppear` が `false` である最初のマウントの際にはトランジションのフェーズはありません。 `transitionAppear` プロパティを値が `true` である状態で渡す以下の例を見てみましょう。
92 -
93 -```javascript{3-5}
94 - render: function() {
95 - return (
96 - <ReactCSSTransitionGroup
97 - transitionName="example"
98 - transitionAppear={true}
99 - transitionAppearTimeout={500}>
100 - <h1>Fading at Initial Mount</h1>
101 - </ReactCSSTransitionGroup>
102 - );
103 - }
104 -```
105 -
106 -最初のマウントの間、 `ReactCSSTransitionGroup` は `example-appear` CSSクラスを得て、次の瞬間に `example-appear-active` CSSクラスを加えます。
107 -
108 -```css
109 -.example-appear {
110 - opacity: 0.01;
111 - transition: opacity .5s ease-in;
112 -}
113 -
114 -.example-appear.example-appear-active {
115 - opacity: 1;
116 -}
117 -```
118 -
119 -最初のマウントの際には、 `ReactCSSTransitionGroup` の全ての子要素は `appear` しますが、 `enter` はしません。一方、存在する `ReactCSSTransitionGroup` に後から加えられた子要素は全て `enter` しますが、 `appear` はしません。
120 -
121 -> 注意:
122 -> `transitionAppear` プロパティはバージョン `0.13` で `ReactCSSTransitionGroup` に加えられました。後方互換性を維持するために、デフォルトの値は `false` に指定されています。
123 -
124 -### アニメーショングループを動かすためには、マウントされている必要があります
125 -
126 -子要素にトランジションを適用するためには、 `ReactCSSTransitionGroup` はすでにDOMにマウントされているか、 `transitionAppear` プロパティに `true` がセットされている必要があります。以下の例は動きません。 `ReactCSSTransitionGroup` が新しいアイテムとともにマウントされており、新しいマウントがマウントされていないからです。これと上の[はじめに](#はじめに) とで違いを比較してみてください。
127 -
128 -```javascript{12-15}
129 - render: function() {
130 - var items = this.state.items.map(function(item, i) {
131 - return (
132 - <div key={item} onClick={this.handleRemove.bind(this, i)}>
133 - <ReactCSSTransitionGroup transitionName="example">
134 - {item}
135 - </ReactCSSTransitionGroup>
136 - </div>
137 - );
138 - }, this);
139 - return (
140 - <div>
141 - <button onClick={this.handleAdd}>Add Item</button>
142 - {items}
143 - </div>
144 - );
145 - }
146 -```
147 -
148 -### 1個か0個のアイテムをアニメーションする
149 -
150 -上の例では、 `ReactCSSTransitionGroup` にアイテムのリストをレンダリングしました。しかし、 `ReactCSSTransitionGroup` の子要素は1個や0個のアイテムになり得ます。単一の要素が作成や削除のアニメーションを可能にします。同様に、現在の要素を置き換える新しい要素をアニメーションできます。例えば、以下のように、1つの画像でカルーセルを実行できます。
151 -
152 -```javascript{10-12}
153 -var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
154 -
155 -var ImageCarousel = React.createClass({
156 - propTypes: {
157 - imageSrc: React.PropTypes.string.isRequired
158 - },
159 - render: function() {
160 - return (
161 - <div>
162 - <ReactCSSTransitionGroup
163 - transitionName="carousel"
164 - transitionEnterTimeout={300}
165 - transitionLeaveTimeout={300}>
166 - <img src={this.props.imageSrc} key={this.props.imageSrc} />
167 - </ReactCSSTransitionGroup>
168 - </div>
169 - );
170 - }
171 -});
172 -```
173 -
174 -### アニメーションを作動させないようにする
175 -
176 -もししたいならば、 `enter` や `leave` のアニメーションを無効にすることもできます。例えば、 `enter` アニメーションは行いたいが、 `leave` のアニメーションは行いたくない場合があるでしょう。しかし、 `ReactCSSTransitionGroup` はDOMのノードが削除される前にアニメーションが終わるのを待ちます。`ReactCSSTransitionGroup` がそれらのアニメーションを無効化するために、 `transitionEnter={false}` や `transitionLeave={false}` といったプロパティを追加することができます。
177 -
178 -> 注意:
179 -> `ReactCSSTransitionGroup` を使う際には、コンポーネントがトランジションが終わったことを検知したり、アニメーション関連でさらに複雑なロジックを実行するといったことはできません。更に細かな制御を求める場合は、トランジションをカスタムするために必要なフックを提供するローレベルの `ReactTransitionGroup` APIを使用できます。
180 -
181 -## ローレベルAPI: `ReactTransitionGroup`
182 -
183 -`ReactTransitionGroup` はアニメーションの基盤です。 `React.addons.TransitionGroup` と同じくらい簡単に使用できます。これによって(上記の例のように)、宣言的に子要素が追加されたり削除されたりするときに、それらの上で特別なライフサイクルのフックが呼ばれます。
184 -
185 -### `componentWillAppear(callback)`
186 -
187 -このメソッドは `TransitionGroup` の中で最初にマウントされるコンポーネントのために `componentDidMount()` と同時に呼ばれます。これは、 `callback` が呼ばれるまで、他のアニメーションが発生するのをブロックします。これは、 `TransitionGroup` の最初のレンダリングのときにのみ呼ばれます。
188 -
189 -### `componentDidAppear()`
190 -
191 - `componentWillAppear` が呼ばれて渡される `callback` 関数の後に呼ばれます。
192 -
193 -### `componentWillEnter(callback)`
194 -
195 -これは、存在する `TransitionGroup` に追加されるコンポーネントのために、 `componentDidMount()` と同時に呼ばれます。これは、 `callback` が呼ばれるまで、他のアニメーションが発生するのをブロックします。これは、 `TransitionGroup` の最初のレンダリングのときには呼ばれません。
196 -
197 -### `componentDidEnter()`
198 -
199 -`componentWillEnter` が呼ばれて渡される `callback` 関数の後に呼ばれます。
200 -
201 -### `componentWillLeave(callback)`
202 -
203 -これは、 `ReactTransitionGroup` から子要素が削除されたときに呼ばれます。子要素が削除されても、 `ReactTransitionGroup` は `callback` が呼ばれるまでDOMの中に子要素を保持し続けます。
204 -
205 -### `componentDidLeave()`
206 -
207 -これは、 `willLeave` の `callback` が呼ばれた際に呼ばれます( `componentWillUnmount` と同時です)。
208 -
209 -### 異なるコンポーネントをレンダリングする
210 -
211 -デフォルトで、 `ReactTransitionGroup` は `span` としてレンダリングされます。この動きは、 `component` プロパティによって変更できます。例えば、 `<ul>` をレンダリングしたい場合は以下のようになります。
212 -
213 -```javascript{1}
214 -<ReactTransitionGroup component="ul">
215 - ...
216 -</ReactTransitionGroup>
217 -```
218 -
219 -Reactがレンダリングできる全てのDOMコンポーネントが使用できます。しかし、 `component` はDOMコンポーネントである必要はありません。あなたが求めているどんなReactのコンポーネントにもなり得ます。あなた自身が記述したものにもです!
220 -
221 -> 注意:
222 -> v0.12以前では、DOMのコンポーネントを使用する際には、 `component` プロパティが `React.DOM.*` を参照している必要がありました。コンポーネントが単純に `React.createElement`から渡されていたからです。これは今は文字列である必要があります。複合的なコンポーネントは複合的なものを渡す必要があります。
223 -
224 -全ての付加的な、ユーザー定義のプロパティはレンダリングされたコンポーネントのプロパティになります。例えば、以下はCSSクラスとともに `<ul>` をレンダリングする方法です。
225 -
226 -```javascript{1}
227 -<ReactTransitionGroup component="ul" className="animated-list">
228 - ...
229 -</ReactTransitionGroup>
230 -```
docs/docs/10.1-animation.ko-KR.md deleted
-258
@@ -1,258 +0,0 @@
1 ----
2 -id: animation-ko-KR
3 -title: 애니메이션
4 -permalink: docs/animation-ko-KR.html
5 -prev: addons-ko-KR.html
6 -next: two-way-binding-helpers-ko-KR.html
7 ----
8 -
9 -React에는 애니메이션을 위한 저 수준 API로 `ReactTransitionGroup` 애드온 컴포넌트가 있고 간단히 기초 CSS 애니메이션과 트랜지션을 구현할 수 있는 `ReactCSSTransitionGroup`가 있습니다.
10 -
11 -## 고 레벨 API: `ReactCSSTransitionGroup`
12 -
13 -`ReactCSSTransitionGroup`는 `ReactTransitionGroup`를 기반으로 React 컴포넌트가 DOM에 들어가거나 나올때의 CSS의 트랜지션과 애니메이션을 구현하기 쉽게합니다. 이는 [ng-animate](http://www.nganimate.org/) 라이브러리에 영향을 받았습니다.
14 -
15 -### 시작하기
16 -
17 -`ReactCSSTransitionGroup`은 `ReactTransitions`을 위한 인터페이스입니다. 이는 애니메이션을 제어할 모든 컴포넌트를 감싸는 하나의 엘리먼트 입니다. 아래는 목록의 아이템을 페이드 인/아웃하는 간단한 예제입니다.
18 -
19 -```javascript{28-30}
20 -var ReactCSSTransitionGroup = require('react-addons-css-transition-group');
21 -
22 -var TodoList = React.createClass({
23 - getInitialState: function() {
24 - return {items: ['hello', 'world', 'click', 'me']};
25 - },
26 - handleAdd: function() {
27 - var newItems =
28 - this.state.items.concat([prompt('Enter some text')]);
29 - this.setState({items: newItems});
30 - },
31 - handleRemove: function(i) {
32 - var newItems = this.state.items;
33 - newItems.splice(i, 1);
34 - this.setState({items: newItems});
35 - },
36 - render: function() {
37 - var items = this.state.items.map(function(item, i) {
38 - return (
39 - <div key={item} onClick={this.handleRemove.bind(this, i)}>
40 - {item}
41 - </div>
42 - );
43 - }.bind(this));
44 - return (
45 - <div>
46 - <button onClick={this.handleAdd}>Add Item</button>
47 - <ReactCSSTransitionGroup
48 - transitionName="example"
49 - transitionEnterTimeout={500}
50 - transitionLeaveTimeout={300}>
51 - {items}
52 - </ReactCSSTransitionGroup>
53 - </div>
54 - );
55 - }
56 -});
57 -```
58 -
59 -> 주의:
60 ->
61 -> `ReactCSSTransitionGroup`의 모든 자식은 [`key` 어트리뷰트](/react/docs/multiple-components-ko-KR.html#동적-자식)를 반드시 만들어야 합니다. 한 아이템을 렌더할 때도 예외는 아닙니다. 키는 React가 어떤 자식이 들어오고, 나가고, 머무르는지 파악할 때 사용합니다.
62 -
63 -이 컴포넌트에서 새로운 아이템이 `ReactCSSTransitionGroup`에 추가되면 `example-enter` 아이템은 CSS 클래스를 가지게 되고 다음 순간에 `example-enter-active` CSS 클래스가 추가됩니다. 이는 `transitionName` prop을 기반으로 한 관례입니다.
64 -
65 -이 클래스들은 CSS 애니메이션이나 트랜지션을 일으키는데 사용할 수 있습니다. 예를 들어, 이 CSS를 넣은 후 아이템을 추가해 보세요.
66 -
67 -```css
68 -.example-enter {
69 - opacity: 0.01;
70 -}
71 -
72 -.example-enter.example-enter-active {
73 - opacity: 1;
74 - transition: opacity 500ms ease-in;
75 -}
76 -
77 -.example-leave {
78 - opacity: 1;
79 -}
80 -
81 -.example-leave.example-leave-active {
82 - opacity: 0.01;
83 - transition: opacity 300ms ease-in;
84 -}
85 -```
86 -
87 -에니메이션 기간이 CSS와 렌더 메소드 양쪽에 지정될 필요가 있다는 것에 주의하셔야 합니다. 이는 엘리먼트에서 애니메이션 클래스를 제거할 때 (만약 남아있다면) DOM에서 엘리먼트를 제거할 때 React에 알려줍니다.
88 -
89 -### 처음 마운트에서 애니메이션 하기
90 -
91 -`ReactCSSTransitionGroup`은 컴포넌트를 처음 마운트할 때 추가 트렌지션 단계를 추가하기 위해, 선택적인 prop `transitionAppear`를 제공합니다. 일반적으로 처음 마운트할 때 트렌지션 단계를 넣지 않기 때문에 `transitionAppear`의 기본 값은 `false`입니다. 뒤의 예제는 `transitionAppear` prop에 `true` 값을 넘기고 있습니다.
92 -
93 -```javascript{3-5}
94 - render: function() {
95 - return (
96 - <ReactCSSTransitionGroup
97 - transitionName="example"
98 - transitionAppear={true}
99 - transitionAppearTimeout={500}>
100 - <h1>Fading at Initial Mount</h1>
101 - </ReactCSSTransitionGroup>
102 - );
103 - }
104 -```
105 -
106 -처음 마운트할 때 `ReactCSSTransitionGroup`은 `example-appear` CSS 클래스를 받고 그 다음에 `example-appear-active` CSS 클래스가 추가됩니다.
107 -
108 -```css
109 -.example-appear {
110 - opacity: 0.01;
111 -}
112 -
113 -.example-appear.example-appear-active {
114 - opacity: 1;
115 - transition: opacity .5s ease-in;
116 -}
117 -```
118 -
119 -처음 마운트할 때, `ReactCSSTransitionGroup`의 모든 자식은 `appear`하지만 `enter`하지 않습니다. 하지만, 존재하는 `ReactCSSTransitionGroup`에 추가되는 모든 자식은 `enter`하지만 `appear`하지 않습니다.
120 -
121 -> 주의:
122 ->
123 -> `transitionAppear` prop은 버전 `0.13`에서 `ReactCSSTransitionGroup`에 추가되었습니다. 하위 호환성을 생각해서, 기본 값은 `false`로 설정되어 있습니다.
124 -
125 -### 커스텀 클래스
126 -
127 -트렌지션의 각 단계에서 커스텀 클래스 이름을 사용할 수도 있습니다. transitionName에 문자열을 넘기는 대신 `enter`, `leave` 같은 클래스 이름의 객체나 `enter`, `enter-active`, `leave-active`, `leave`같은 클래스 이름의 객체를 넘길 수 있습니다. enter, leave 클래스만 있다면, enter-active, leave-active 클래스는 클래스 이름 뒤에 '-active'를 붙여서 정할 수 있습니다. 커스텀 클래스를 사용한 예제입니다.
128 -
129 -```javascript
130 - ...
131 - <ReactCSSTransitionGroup
132 - transitionName={ {
133 - enter: 'enter',
134 - enterActive: 'enterActive',
135 - leave: 'leave',
136 - leaveActive: 'leaveActive',
137 - appear: 'appear',
138 - appearActive: 'appearActive'
139 - } }>
140 - {item}
141 - </ReactCSSTransitionGroup>
142 -
143 - <ReactCSSTransitionGroup
144 - transitionName={ {
145 - enter: 'enter',
146 - leave: 'leave',
147 - appear: 'appear'
148 - } }>
149 - {item2}
150 - </ReactCSSTransitionGroup>
151 - ...
152 -```
153 -
154 -### 애니메이션 그룹이 작동하려면 마운트가 필요
155 -
156 -자식들에게 트랜지션을 적용하려면 `ReactCSSTransitionGroup`은 이미 DOM에 마운트되어 있거나 prop `transitionAppear`가 `true`로 설정되어야만 합니다. 예를 들어, 밑의 코드는 동작하지 않을 것입니다. 왜냐하면 `ReactCSSTransitionGroup` 안에서 새 아이템을 마운트하는 대신 새 아이템과 같이 `ReactCSSTransitionGroup`를 마운트했기 때문입니다. 이 것을 위에 있는 [시작하기](#시작하기) 항목과 비교해보세요.
157 -
158 -```javascript{12-15}
159 - render: function() {
160 - var items = this.state.items.map(function(item, i) {
161 - return (
162 - <div key={item} onClick={this.handleRemove.bind(this, i)}>
163 - <ReactCSSTransitionGroup transitionName="example">
164 - {item}
165 - </ReactCSSTransitionGroup>
166 - </div>
167 - );
168 - }, this);
169 - return (
170 - <div>
171 - <button onClick={this.handleAdd}>Add Item</button>
172 - {items}
173 - </div>
174 - );
175 - }
176 -```
177 -
178 -### 아이템 하나이거나 없을 때의 애니메이션
179 -
180 -위의 예제에서 `ReactCSSTransitionGroup`에 아이템 목록을 렌더했지만, `ReactCSSTransitionGroup`의 자식은 하나이거나 없을 수도 있습니다. 이는 한 엘리먼트가 들어오고 나가는 것의 애니메이션을 가능하게 합니다. 비슷하게, 현재 엘리먼트가 나가는 동안 새 앨리먼트의 애니메이션을 하면, 새 엘리먼트가 현재 엘리먼트를 교체하는 애니메이션을 만들 수 있습니다. 예를 들어 이렇게 간단한 이미지 회전 베너(carousel)를 구현할 수 있습니다.
181 -
182 -```javascript{10-12}
183 -var ReactCSSTransitionGroup = require('react-addons-css-transition-group');
184 -
185 -var ImageCarousel = React.createClass({
186 - propTypes: {
187 - imageSrc: React.PropTypes.string.isRequired
188 - },
189 - render: function() {
190 - return (
191 - <div>
192 - <ReactCSSTransitionGroup
193 - transitionName="carousel"
194 - transitionEnterTimeout={300}
195 - transitionLeaveTimeout={300}>
196 - <img src={this.props.imageSrc} key={this.props.imageSrc} />
197 - </ReactCSSTransitionGroup>
198 - </div>
199 - );
200 - }
201 -});
202 -```
203 -
204 -### 애니메이션 비활성화
205 -
206 -원한다면 `enter`나 `leave` 애니메이션을 비활성화 할 수 있습니다. 예를 들어, `enter` 애니메이션만 필요하고 `leave` 애니메이션은 필요없지만, `ReactCSSTransitionGroup`이 DOM 노드를 없애기 전 애니메이션이 완료되길 기다리고 있는 경우에 사용할 수 있습니다. `ReactCSSTransitionGroup`에 `transitionEnter={false}`나 `transitionLeave={false}` props를 추가하면 그 애니메이션을 비활성화 할 수 있습니다.
207 -
208 -> 주의:
209 ->
210 -> `ReactCSSTransitionGroup`를 사용할 때는, 트랜지션이 종료되었을 때나 애니메이션 근처에서 더 복잡한 로직을 실행할 때 컴포넌트에 통지할 방법이 없습니다. 보다 세밀하게 제어하고 싶다면, 커스텀 트랜지션에 필요한 훅을 제공하는 저수준 `ReactTransitionGroup` API를 이용할 수 있습니다.
211 -
212 -## 저수준 API: `ReactTransitionGroup`
213 -
214 -`ReactTransitionGroup`은 애니메이션의 기초입니다. 이는 `require('react-addons-transition-group')`으로 접근할 수 있습니다. 위의 예제처럼 자식들이 선언적으로 여기에 추가되거나 삭제되는 경우, 특별한 훅이 이 생명주기에서 호출됩니다.
215 -
216 -### `componentWillAppear(callback)`
217 -
218 -이미 있는 `TransitionGroup`에 컴포넌트를 추가할 때 호출되는 `componentDidMount()`와 같이 호출됩니다. 이는 `callback`이 호출될 때까지 다른 애니메이션을 막습니다. `TransitionGroup`의 최초 렌더에서만 호출됩니다.
219 -
220 -### `componentDidAppear()`
221 -
222 -이는 `componentWillAppear`에 넘겨졌던 `callback` 함수가 호출된 다음에 호출됩니다.
223 -
224 -### `componentWillEnter(callback)`
225 -
226 -이미 있는 `TransitionGroup`에 컴포넌트를 추가할 때 호출되는 `componentDidMount()`와 같이 호출됩니다. 이는 `callback`이 호출될 때까지 다른 애니메이션을 막습니다. `TransitionGroup`의 최조 렌더에서는 불려지지 않습니다.
227 -
228 -### `componentDidEnter()`
229 -
230 -이는 `componentWillEnter`에 넘겨주었던 `callback` 함수가 호출된 다음에 호출됩니다.
231 -
232 -### `componentWillLeave(callback)`
233 -
234 -이는 `ReactTransitionGroup`에서 자식이 제거되었을 때 호출됩니다. 자식이 제거되었다고 해도 `ReactTransitionGroup`는 `callback`이 호출될 때까지 DOM에 자식을 남겨둡니다.
235 -
236 -### `componentDidLeave()`
237 -
238 -이는 `willLeave` `callback`이 호출될 때 호출됩니다. (`componentWillUnmount`와 같은 타이밍)
239 -
240 -### 다른 컴포넌트 렌더하기
241 -
242 -기본적으로 `ReactTransitionGroup`은 `span`으로 렌더합니다. `component` prop으로 이 행동을 바꿀 수 있습니다. 예를 들어, `<ul>`을 렌더하고 싶다면 이렇게 하면 됩니다.
243 -
244 -```javascript{1}
245 -<ReactTransitionGroup component="ul">
246 - ...
247 -</ReactTransitionGroup>
248 -```
249 -
250 -React가 렌더할 수 있는 DOM 컴포넌트는 전부 사용할 수 있습니다. 하지만 `component`가 DOM 컴포넌트일 필요는 없습니다. React 컴포넌트라면 무엇이든 넣을 수 있습니다. 직접 구현한 컴포넌트여도 됩니다! 그냥 `component={List}`를 적으면 컴포넌트는 `this.props.children`로 받을 수 있습니다.
251 -
252 -사용자 정의를 포함한 어떤 프로퍼티도 렌더된 컴포넌트의 프로퍼티가 됩니다. 예를 들어, `<ul>`에 CSS 클래스를 넣어서 렌더하려면 이렇게 하면 됩니다.
253 -
254 -```javascript{1}
255 -<ReactTransitionGroup component="ul" className="animated-list">
256 - ...
257 -</ReactTransitionGroup>
258 -```
docs/docs/10.1-animation.zh-CN.md deleted
-258
@@ -1,258 +0,0 @@
1 ----
2 -id: animation-zh-CN
3 -title: 动画
4 -permalink: docs/animation-zh-CN.html
5 -prev: addons-zh-CN.html
6 -next: two-way-binding-helpers-zh-CN.html
7 ----
8 -
9 -React 提供了一个 `ReactTransitionGroup` 插件作为动画的底层API,和一个 `ReactCSSTransitionGroup` 用于轻松实现基础的CSS动画和过渡。
10 -
11 -## 高级 API: `ReactCSSTransitionGroup`
12 -
13 -`ReactCSSTransitionGroup` 基于 `ReactTransitionGroup` 是一个当React组件进入或离开DOM时,执行CSS动画和过渡的简单方法。它的灵感来自于杰出的 [ng-animate](http://www.nganimate.org/) 库。
14 -
15 -### 入门指南
16 -
17 -`ReactCSSTransitionGroup` 是 `ReactTransitions` 的接口。这是一个简单的元素,包裹了所有你感兴趣的动画组件。这里是一个淡入和淡出列表项目的例子。
18 -
19 -```javascript{28-30}
20 -var ReactCSSTransitionGroup = require('react-addons-css-transition-group');
21 -
22 -var TodoList = React.createClass({
23 - getInitialState: function() {
24 - return {items: ['hello', 'world', 'click', 'me']};
25 - },
26 - handleAdd: function() {
27 - var newItems =
28 - this.state.items.concat([prompt('Enter some text')]);
29 - this.setState({items: newItems});
30 - },
31 - handleRemove: function(i) {
32 - var newItems = this.state.items.slice();
33 - newItems.splice(i, 1);
34 - this.setState({items: newItems});
35 - },
36 - render: function() {
37 - var items = this.state.items.map(function(item, i) {
38 - return (
39 - <div key={item} onClick={this.handleRemove.bind(this, i)}>
40 - {item}
41 - </div>
42 - );
43 - }.bind(this));
44 - return (
45 - <div>
46 - <button onClick={this.handleAdd}>Add Item</button>
47 - <ReactCSSTransitionGroup
48 - transitionName="example"
49 - transitionEnterTimeout={500}
50 - transitionLeaveTimeout={300}>
51 - {items}
52 - </ReactCSSTransitionGroup>
53 - </div>
54 - );
55 - }
56 -});
57 -```
58 -> 注意:
59 ->
60 -> 你必须为`ReactCSSTransitionGroup`的所有子级提供 [ `key` 属性](/react/docs/multiple-components.html#dynamic-children),即使只渲染一个项目。这就是React将决定哪一个子级进入,离开,或者停留
61 -
62 -在这个组件,当一个新的项目被添加到 `ReactCSSTransitionGroup` ,他将得到`example-enter` CSS类 并且在下一刻`example-enter-active` CSS类被添加。这是一个基于`transitionName` prop 的约定。
63 -
64 -你可以使用这些类来触发CSS动画和过渡。比如,尝试添加这个CSS和添加一个新的列表项:
65 -
66 -```css
67 -.example-enter {
68 - opacity: 0.01;
69 -}
70 -
71 -.example-enter.example-enter-active {
72 - opacity: 1;
73 - transition: opacity 500ms ease-in;
74 -}
75 -
76 -.example-leave {
77 - opacity: 1;
78 -}
79 -
80 -.example-leave.example-leave-active {
81 - opacity: 0.01;
82 - transition: opacity 300ms ease-in;
83 -}
84 -```
85 -
86 -你会注意到动画持续时间需要被同时在CSS和渲染方法里被指定;这告诉React什么时候从元素中移除动画类,并且 -- 如果它正在离开 -- 何时从DOM移除元素。
87 -
88 -### 让初始化挂载动画
89 -
90 -`ReactCSSTransitionGroup` 提供了可选的prop `transitionAppear`,来为在组件初始挂载添加一个额外的过渡阶段。 通常在初始化挂载时没有过渡阶段因为`transitionAppear` 的默认值为`false`。下面是一个传递`transitionAppear` 为值`true`的例子。
91 -
92 -```javascript{3-5}
93 - render: function() {
94 - return (
95 - <ReactCSSTransitionGroup
96 - transitionName="example"
97 - transitionAppear={true}
98 - transitionAppearTimeout={500}>
99 - <h1>Fading at Initial Mount</h1>
100 - </ReactCSSTransitionGroup>
101 - );
102 - }
103 -```
104 -
105 -在初始化挂载时 `ReactCSSTransitionGroup` 将获得`example-appear` CSS类 并且`example-appear-active` CSS 类在下一刻被添加。
106 -
107 -```css
108 -.example-appear {
109 - opacity: 0.01;
110 -}
111 -
112 -.example-appear.example-appear-active {
113 - opacity: 1;
114 - transition: opacity .5s ease-in;
115 -}
116 -```
117 -
118 -在初始化挂载,所有的 `ReactCSSTransitionGroup` 子级将会 `appear` 但不 `enter`。然而,所有后来添加到已存在的 `ReactCSSTransitionGroup` 的子级将 `enter` 但不 `appear`。
119 -
120 -> 注意:
121 ->
122 -> prop `transitionAppear` 在版本 `0.13` 被添加到 `ReactCSSTransitionGroup`。为了保持向后兼容,默认值被设置为 `false`。
123 -
124 -### 制定类
125 -
126 -可以为你的每一步过渡使用制定类名字。代理传递一个字符串到transitionName,你可以传递一个含有`enter` 或者`leave` 类名的对象,或者一个含有 `enter`, `enter-active`, `leave-active`, 和 `leave` 类名的对象。只要提供了enter 和 leave 的类,enter-active 和 leave-active 类会被决定为后缀'-active' 到类名的尾部。这里是两个使用制定类的例子:
127 -
128 -```javascript
129 - ...
130 - <ReactCSSTransitionGroup
131 - transitionName={ {
132 - enter: 'enter',
133 - enterActive: 'enterActive',
134 - leave: 'leave',
135 - leaveActive: 'leaveActive',
136 - appear: 'appear',
137 - appearActive: 'appearActive'
138 - } }>
139 - {item}
140 - </ReactCSSTransitionGroup>
141 -
142 - <ReactCSSTransitionGroup
143 - transitionName={ {
144 - enter: 'enter',
145 - leave: 'leave',
146 - appear: 'appear'
147 - } }>
148 - {item2}
149 - </ReactCSSTransitionGroup>
150 - ...
151 -```
152 -
153 -### 动画组必须挂载才工作
154 -
155 -为了使过渡效果应用到子级上,`ReactCSSTransitionGroup`必须已经挂载到了DOM或者 prop `transitionAppear` 必须被设置为 `true`。下面的例子不会工作,因为 `ReactCSSTransitionGroup` 随同新项目被挂载,而不是新项目在它内部被挂载。将这与上面的[入门指南](#入门指南)部分比较一下,看看不同。
156 -
157 -```javascript{12-15}
158 - render: function() {
159 - var items = this.state.items.map(function(item, i) {
160 - return (
161 - <div key={item} onClick={this.handleRemove.bind(this, i)}>
162 - <ReactCSSTransitionGroup transitionName="example">
163 - {item}
164 - </ReactCSSTransitionGroup>
165 - </div>
166 - );
167 - }, this);
168 - return (
169 - <div>
170 - <button onClick={this.handleAdd}>Add Item</button>
171 - {items}
172 - </div>
173 - );
174 - }
175 -```
176 -
177 -### 动画一个或者零个项目 Animating One or Zero Items
178 -
179 -在上面的例子中,我们渲染了一系列的项目到`ReactCSSTransitionGroup`里。然而 `ReactCSSTransitionGroup` 的子级同样可以是一个或零个项目。这使它能够动画化单个元素的进入和离开。同样,你可以动画化一个新的元素替换当前元素。例如,我们可以像这样实现一个简单的图片轮播器:
180 -
181 -```javascript{10-12}
182 -var ReactCSSTransitionGroup = require('react-addons-css-transition-group');
183 -
184 -var ImageCarousel = React.createClass({
185 - propTypes: {
186 - imageSrc: React.PropTypes.string.isRequired
187 - },
188 - render: function() {
189 - return (
190 - <div>
191 - <ReactCSSTransitionGroup
192 - transitionName="carousel"
193 - transitionEnterTimeout={300}
194 - transitionLeaveTimeout={300}>
195 - <img src={this.props.imageSrc} key={this.props.imageSrc} />
196 - </ReactCSSTransitionGroup>
197 - </div>
198 - );
199 - }
200 -});
201 -```
202 -
203 -### 禁用动画
204 -
205 -如果你想,你可以禁用 `enter` 或者 `leave` 动画。例如,有时你可能想要一个 `enter` 动画,不要 `leave` 动画,但是 `ReactCSSTransitionGroup` 会在移除你的DOM节点之前等待一个动画完成。你可以添加`transitionEnter={false}` 或者 `transitionLeave={false}` props 到 `ReactCSSTransitionGroup` 来禁用这些动画。
206 -
207 -> 注意:
208 ->
209 -> 当使用 `ReactCSSTransitionGroup` 时,没有办法通知你的组件何时过渡效果结束或者在动画时执行任何复杂的逻辑运算。如果你想要更多细粒度的控制,你可以使用底层的 `ReactTransitionGroup` API,它提供了你自定义过渡效果所需要的挂钩。
210 -
211 -## 底层 API: `ReactTransitionGroup`
212 -
213 -`ReactTransitionGroup`是动画的基础。它通过 `require('react-addons-transition-group')` 访问。当子级被声明式的从其中添加或移除(就像上面的例子)时,特殊的生命周期挂钩会在它们上面被调用。
214 -
215 -### `componentWillAppear(callback)`
216 -
217 -对于被初始化挂载到 `TransitionGroup` 的组件,它和 `componentDidMount()` 在相同时间被调用 。它将会阻塞其它动画发生,直到`callback`被调用。它只会在 `TransitionGroup` 初始化渲染时被调用。
218 -
219 -### `componentDidAppear()`
220 -
221 -在 传给`componentWillAppear` 的 `回调` 函数被调用后调用。
222 -
223 -### `componentWillEnter(callback)`
224 -
225 -对于被添加到已存在的 `TransitionGroup` 的组件,它和 `componentDidMount()` 在相同时间被调用 。它将会阻塞其它动画发生,直到`callback`被调用。它不会在 `TransitionGroup` 初始化渲染时被调用。
226 -
227 -### `componentDidEnter()`
228 -
229 -在传给 `componentWillEnter` 的`回调`函数被调用之后调用。
230 -
231 -### `componentWillLeave(callback)`
232 -
233 -在子级从 `ReactTransitionGroup` 中移除时调用。虽然子级被移除了,`ReactTransitionGroup` 将会保持它在DOM中,直到`callback`被调用。
234 -
235 -### `componentDidLeave()`
236 -
237 -在`willLeave` `callback` 被调用的时候调用(与 `componentWillUnmount` 同一时间)。
238 -
239 -### 渲染一个不同的组件
240 -
241 -默认情况下 `ReactTransitionGroup` 渲染为一个 `span`。你可以通过提供一个 `component` prop 来改变这种行为。例如,下面是你将如何渲染一个`<ul>`:
242 -
243 -```javascript{1}
244 -<ReactTransitionGroup component="ul">
245 - ...
246 -</ReactTransitionGroup>
247 -```
248 -
249 -每一个React能渲染的DOM组件都是可用的。然而,`组件`不需要是一个DOM组件。它可以是任何你想要的React组件;甚至是你自己已经写好的!只要写 `component={List}` 你的组件会收到 `this.props.children`
250 -
251 -
252 -任何额外的、用户定义的属性将会成为已渲染的组件的属性。例如,以下是你将如何渲染一个带有css类的 `<ul>`:
253 -
254 -```javascript{1}
255 -<ReactTransitionGroup component="ul" className="animated-list">
256 - ...
257 -</ReactTransitionGroup>
258 -```
docs/docs/10.10-shallow-compare.zh-CN.md deleted
-32
@@ -1,32 +0,0 @@
1 ----
2 -id: shallow-compare-zh-CN
3 -title: 浅比较
4 -permalink: docs/shallow-compare-zh-CN.html
5 -prev: perf-zh-CN.html
6 -next: advanced-performance-zh-CN.html
7 ----
8 -
9 -`shallowCompare` 是一个辅助函数 在以ES6类使用React时,完成和 `PureRenderMixin` 相同的功能。
10 -
11 -如果你的React组件的绘制函数是 “干净的” (换句话说,它在给定的 props 和 state 下绘制相同的结果),你可以使用这个辅助函数以在某些情况下提升性能。
12 -
13 -例如:
14 -
15 -```js
16 -var shallowCompare = require('react-addons-shallow-compare');
17 -export class SampleComponent extends React.Component {
18 - shouldComponentUpdate(nextProps, nextState) {
19 - return shallowCompare(this, nextProps, nextState);
20 - }
21 -
22 - render() {
23 - return <div className={this.props.className}>foo</div>;
24 - }
25 -}
26 -```
27 -
28 -`shallowCompare` 对当前的 `props` 和 `nextProps`对象 执行一个浅的相等检查,同样对于 `state` 和 `nextState`对象。
29 -它 通过迭代比较对象的keys 并在 对象的key值不严格相等时返回false 实现此功能.
30 -
31 -`shallowCompare` 返回 `true` 如果对 props 或 state的浅比较失败,因此组件应该更新。
32 -`shallowCompare` 返回 `false` 如果对 props 或 state的浅比较都通过了,因此组件不应该更新。
docs/docs/10.2-form-input-binding-sugar.it-IT.md deleted
-114
@@ -1,114 +0,0 @@
1 ----
2 -id: two-way-binding-helpers-it-IT
3 -title: Helper Per Binding Bidirezionali
4 -permalink: docs/two-way-binding-helpers-it-IT.html
5 -prev: animation-it-IT.html
6 -next: test-utils-it-IT.html
7 ----
8 -
9 -`ReactLink` è una maniera semplice di esprimere binding bidirezionali con React.
10 -
11 -> Nota:
12 ->
13 -> Se hai poca esperienza del framework, nota che `ReactLink` non è necessario per molte applicazioni e dovrebbe essere utilizzato con cautela.
14 -
15 -In React, i dati fluiscono in una direzione: dal proprietario ai figli. Questo poiché i dati fluiscono in una sola direzione nel [modello di computazione di Von Neumann](https://en.wikipedia.org/wiki/Von_Neumann_architecture). Puoi pensare ad esso come "binding unidirezionale dei dati."
16 -
17 -Tuttavia, esistono parecchie applicazioni che richiedono di leggere dati e farli fluire nuovamente nel tuo programma. Ad esempio, quando sviluppi dei moduli, vorrai spesso aggiornare uno `state` di React quando ricevi un input dall'utente. O forse vuoi effettuare il layout in JavaScript e reagire ai cambiamenti nelle dimensioni di alcuni elementi DOM.
18 -
19 -In React, questo verrebbe implementato ascoltando un evento "change", leggendo la tua fonte di dati (solitamente il DOM) e chiamando `setState()` su uno dei tuoi componenti. "Chiudere il ciclo del flusso dei dati" esplicitamente conduce a programmi più comprensibili e mantenibili. Consulta [la nostra documentazione sui moduli](/react/docs/forms.html) per maggiori informazioni.
20 -
21 -Il binding bidirezionale -- assicurarsi implicitamente che alcuni valori nel DOM siano sempre consistenti con degli `state` in React -- è più conciso e supporta un'ampia varietà di applicazioni. Abbiamo fornito `ReactLink`: zucchero sintattico per impostare il pattern del ciclo del flusso di dati descritto in predecenza, ovvero "collegare" una fonte di dati con lo `state` di React.
22 -
23 -> Nota:
24 ->
25 -> `ReactLink` è soltanto uno strato di astrazione e convenzioni attorno al pattern `onChange`/`setState()`. Non cambia fondamentalmente la maniera in cui i dati fluiscono all'interno della tua applicazione React.
26 -
27 -## ReactLink: Prima e Dopo
28 -
29 -Ecco un semplice esempio di modulo che non utilizza `ReactLink`:
30 -
31 -```javascript
32 -var NoLink = React.createClass({
33 - getInitialState: function() {
34 - return {message: 'Ciao!'};
35 - },
36 - handleChange: function(event) {
37 - this.setState({message: event.target.value});
38 - },
39 - render: function() {
40 - var message = this.state.message;
41 - return <input type="text" value={message} onChange={this.handleChange} />;
42 - }
43 -});
44 -```
45 -
46 -Ciò funziona molto bene e il flusso di dati è molto chiaro. Tuttavia, in presenza di un gran numero di campi del modulo può risultare assai prolisso. Utilizziamo `ReactLink` per risparmiarci la scrittura di un po' di codice:
47 -
48 -```javascript{2,7}
49 -var WithLink = React.createClass({
50 - mixins: [React.addons.LinkedStateMixin],
51 - getInitialState: function() {
52 - return {message: 'Ciao!'};
53 - },
54 - render: function() {
55 - return <input type="text" valueLink={this.linkState('message')} />;
56 - }
57 -});
58 -```
59 -
60 -`LinkedStateMixin` aggiunge un metodo chiamato `linkState()` al tuo componente React. `linkState()` restituisce un oggetto `ReactLink` contenente il valore attuae dello stato React e una callback per cambiarlo.
61 -
62 -Gli oggetti `ReactLink` possono essere passati su e giù nell'albero come proprietà, quindi è facile (ed esplicito) impostare un binding bidirezionale tra un componente in profondità nella gerarchia e dello stato che si trova più in alto nella gerarchia.
63 -
64 -Nota che i checkbox hanno un comportamento speciale riguardo il loro attributo `value`, che è il valore che sarà inviato all'inoltro del modulo se il checkbox è spuntato (il valore predefinito è `on`). L'attributo `value` non è aggiornato quando il checkbox viene spuntato o deselezionato. Per i checkbox occorre usare `checkedLink` anziché `valueLink`:
65 -```
66 -<input type="checkbox" checkedLink={this.linkState('booleanValue')} />
67 -```
68 -
69 -
70 -## Dietro le Quinte
71 -
72 -Ci sono due ambiti in `ReactLink`: il posto in cui crei l'istanza di `ReactLink` e il posto in cui la utilizzi. Per dimostrare quanto sia semplice usare `ReactLink`, riscriviamo ciascun ambito separatamente perché sia più esplicito.
73 -
74 -### ReactLink Senza LinkedStateMixin
75 -
76 -```javascript{5-7,9-12}
77 -var WithoutMixin = React.createClass({
78 - getInitialState: function() {
79 - return {message: 'Ciao!'};
80 - },
81 - handleChange: function(newValue) {
82 - this.setState({message: newValue});
83 - },
84 - render: function() {
85 - var valueLink = {
86 - value: this.state.message,
87 - requestChange: this.handleChange
88 - };
89 - return <input type="text" valueLink={valueLink} />;
90 - }
91 -});
92 -```
93 -
94 -Come puoi vedere, gli oggetti `ReactLink` sono semplici oggetti che hanno due proprietà: `value` e `requestChange`. `LinkedStateMixin` è altrettanto semplice: popola semplicemente questi campi con un valore da `this.state` e una callback che invoca `this.setState()`.
95 -
96 -### ReactLink Senza valueLink
97 -
98 -```javascript
99 -var WithoutLink = React.createClass({
100 - mixins: [React.addons.LinkedStateMixin],
101 - getInitialState: function() {
102 - return {message: 'Ciao!'};
103 - },
104 - render: function() {
105 - var valueLink = this.linkState('message');
106 - var handleChange = function(e) {
107 - valueLink.requestChange(e.target.value);
108 - };
109 - return <input type="text" value={valueLink.value} onChange={handleChange} />;
110 - }
111 -});
112 -```
113 -
114 -La proprietà `valueLink` è anche abbastanza semplice. Gestisce semplicemente l'evento `onChange` e invoca `this.props.valueLink.requestChange()`, e inoltre utilizza `this.props.valueLink.value` anziché `this.props.value`. Tutto qua!
docs/docs/10.2-form-input-binding-sugar.ja-JP.md deleted
-114
@@ -1,114 +0,0 @@
1 ----
2 -id: two-way-binding-helpers
3 -title: 2ウェイバインディングのヘルパ
4 -permalink: docs/two-way-binding-helpers-ja-JP.html
5 -prev: animation-ja-JP.html
6 -next: test-utils-ja-JP.html
7 ----
8 -
9 -`ReactLink` はReactで2ウェイバインディングを表現する簡単な方法です。
10 -
11 -> 注意:
12 -> もしあなたがフレームワークについてあまりよく知らないのであれば、 `ReactLink` は多くのアプリケーションには必要なく、慎重に使うべきであることに注意してください。
13 -
14 -Reactでは所有者から子要素へと、データの流れは一方向です。これはデータが[Von Neumannのコンピューティングモデル](https://en.wikipedia.org/wiki/Von_Neumann_architecture)によって一方向にのみ流れるからです。これを「1ウェイデータバインディング」だと考えることができます。
15 -
16 -しかし、データやプログラムに戻る流れを読む必要が有るアプリケーションもたくさんあります。例えば、フォームを作る際に、ユーザのインプットを受け取った時には、Reactの `state` を更新したいと思うことはよくあるでしょう。または、JavaScriptでレイアウトを形作ったり、DOM要素のサイズの変化に反応したいと思うでしょう。
17 -
18 -Reactでは、「変更」のイベントを検知し、データソース(普通はDOMです)を読み、コンポーネントのうちの1つの上で `setState()` を呼ぶことでこの要求を満たすことができます。「データフローのループを止めること」は理解しやすく、維持しやすいプログラムを明確に導きます。詳細な情報については、[フォームのドキュメント](/react/docs/forms-ja-JP.html)をご覧ください。
19 -
20 -2ウェイバインディングはDOMの値が常にReactの `state` と一致していることを暗黙に強制しますが、簡潔で、多くの種類のアプリケーションをサポートします。上で説明されているような共通のデータフローループパターンのセットアップや、データソースをReactの `state` に「接続する」ための糖衣構文である `ReactLink` が提供されています。
21 -
22 -> 注意:
23 -> `ReactLink` は薄いラッパーであり、 `onChange`/`setState()` パターンにおける習慣です。Reactアプリケーションのデータフローの方法を根本から変えるようなものではありません。
24 -
25 -## ReactLink: ビフォーアフター
26 -
27 -以下が、 `ReactLink` を使用しない単純なフォームの例です。
28 -
29 -```javascript
30 -var NoLink = React.createClass({
31 - getInitialState: function() {
32 - return {message: 'Hello!'};
33 - },
34 - handleChange: function(event) {
35 - this.setState({message: event.target.value});
36 - },
37 - render: function() {
38 - var message = this.state.message;
39 - return <input type="text" value={message} onChange={this.handleChange} />;
40 - }
41 -});
42 -```
43 -
44 -これはとてもよく動き、データがどう流れているかとても明確です。しかし、たくさんのフォームのフィールドがあった場合、少し冗長になります。以下のように、 `ReactLink` を使うことでタイピング量が少なくて済みます。
45 -
46 -```javascript{2,7}
47 -var WithLink = React.createClass({
48 - mixins: [React.addons.LinkedStateMixin],
49 - getInitialState: function() {
50 - return {message: 'Hello!'};
51 - },
52 - render: function() {
53 - return <input type="text" valueLink={this.linkState('message')} />;
54 - }
55 -});
56 -```
57 -
58 -`LinkedStateMixin` は `linkState()` と呼ばれるReactコンポーネントにメソッドを追加します。
59 -`linkState()` はReactのステータスの現在の値と、それを変更するコールバックを持った `ReactLink` オブジェクトを返します。
60 -
61 -`ReactLink` オブジェクトはプロパティとして、木構造の上や下に渡される可能性があります。だから、階層の深い位置にいるコンポーネントと階層の高い位置にいるステータスの間の2ウェイバインディングをセットアップすることは簡単(で、明確)です。
62 -
63 -チェックボックスはその `value` 属性に対しての特別な態度を持っていることに注意してください。それは、チェックボックスがチェックされている(デフォルトで `on` )場合にフォームのサブミットで送信される値です。 `value` 属性はチェックボックスがチェックされていても、チェックされていなくても、更新されません。チェックボックスについては、`valueLink` の代わりに、 `checkedLink` を使うべきです。以下のように。
64 -
65 -```
66 -<input type="checkbox" checkedLink={this.linkState('booleanValue')} />
67 -```
68 -
69 -
70 -## フードの下
71 -
72 -`ReactLink` には2つの側面があります。 `ReactLink` のインスタンスを作成する場所と、それを使う場所です。 `ReactLink` がどれだけ単純か証明するために、それぞれの側面を分けて、明確に再度記述してみましょう。
73 -
74 -### LinkedStateMixinを使わないReactLink
75 -
76 -```javascript{5-7,9-12}
77 -var WithoutMixin = React.createClass({
78 - getInitialState: function() {
79 - return {message: 'Hello!'};
80 - },
81 - handleChange: function(newValue) {
82 - this.setState({message: newValue});
83 - },
84 - render: function() {
85 - var valueLink = {
86 - value: this.state.message,
87 - requestChange: this.handleChange
88 - };
89 - return <input type="text" valueLink={valueLink} />;
90 - }
91 -});
92 -```
93 -
94 -今まで見てきたように `ReactLink` オブジェクトは `value` と `requestChange` プロパティだけを持ったとても単純なオブジェクトです。そして、 `LinkedStateMixin` も同様に単純です。それらのフィールドを `this.state` の値と、 `this.setState()` を呼ぶコールバックで満たします。
95 -
96 -### valueLinkを使わないReactLink
97 -
98 -```javascript
99 -var WithoutLink = React.createClass({
100 - mixins: [React.addons.LinkedStateMixin],
101 - getInitialState: function() {
102 - return {message: 'Hello!'};
103 - },
104 - render: function() {
105 - var valueLink = this.linkState('message');
106 - var handleChange = function(e) {
107 - valueLink.requestChange(e.target.value);
108 - };
109 - return <input type="text" value={valueLink.value} onChange={handleChange} />;
110 - }
111 -});
112 -```
113 -
114 -`valueLink` プロパティも同様にとても単純です。単純に `onChange` イベントをハンドルし、 `this.props.valueLink.requestChange()` を呼び、 `this.props.value` の代わりに `this.props.valueLink.value` を使用します。それだけです!
docs/docs/10.2-form-input-binding-sugar.ko-KR.md deleted
-117
@@ -1,117 +0,0 @@
1 ----
2 -id: two-way-binding-helpers-ko-KR
3 -title: 양방향 바인딩 핼퍼
4 -permalink: docs/two-way-binding-helpers-ko-KR.html
5 -prev: animation-ko-KR.html
6 -next: test-utils-ko-KR.html
7 ----
8 -
9 -`ReactLink`는 React에서 양방향 바인딩을 표현하는 쉬운 방법입니다.
10 -
11 -> 주의:
12 ->
13 -> 프레임워크를 새로 접하신다면, 대부분의 애플리케이션에서 `ReactLink`는 필요없고 신중히 사용하셔야 함을 알려드립니다.
14 -
15 -React에서 데이터 흐름은 소유주에서 자식으로의 단방향입니다. 이는 [폰 노이만 컴퓨팅 모델](http://ko.wikipedia.org/wiki/%ED%8F%B0_%EB%85%B8%EC%9D%B4%EB%A7%8C_%EA%B5%AC%EC%A1%B0)의 데이터가 단방향으로 흐르기 때문입니다. 이것을 "단방향 데이터 바인딩"으로 생각하셔도 됩니다.
16 -
17 -하지만 많은 애플리케이션에서 데이터를 요청해서 프로그램으로 돌려줍니다. 예를 들어, 폼을 개발한다면, 사용자 입력을 받았을 때 `state`를 바꾸거나, JavaScript안에서 레이아웃을 바꾸고 그에 따라 어떤 DOM 엘리먼트의 크기를 바꾸게 하고 싶을 수도 있습니다.
18 -
19 -React에서 이는 "change" 이벤트를 감시하고 데이터 소스(보통 DOM)에서 읽어 컴포넌트에서 `setState()`를 호출하는 식으로 할 수 있습니다. "데이터 흐름 반복을 제한"하면 더 이해하기 편하고, 쉽게 유지보수할 수 있는 프로그램이 만들어지는 것은 명확합니다. 더 자세한 내용은 [폼 문서](/react/docs/forms-ko-KR.html)를 확인하세요.
20 -
21 -양방향 바인딩(묵시적으로 DOM의 어떤 값은 React `state`와 일치하도록 강제하는 것)은 간결하기도 하고 다양한 애플리케이션을 지원 할 수 있습니다. React는 `ReactLink`를 제공합니다. 이는 위에서 설명한 일반적인 데이터 흐름 반복 패턴을 설정하거나, 어떤 데이터 소스를 React `state`로 "링크하는" 편의 문법입니다.
22 -
23 -> 주의:
24 ->
25 -> `ReactLink`는 얇은 레퍼고 `onChange`/`setState()`패턴 부분의 관례일 뿐입니다. React 애플리케이션에서의 데이터 흐름을 근본적으로 바꾸지는 않습니다.
26 -
27 -## ReactLink: 적용 전후
28 -
29 -`ReactLink`를 사용하지 않는 간단한 폼 예제입니다.
30 -
31 -```javascript
32 -var NoLink = React.createClass({
33 - getInitialState: function() {
34 - return {message: '안녕!'};
35 - },
36 - handleChange: function(event) {
37 - this.setState({message: event.target.value});
38 - },
39 - render: function() {
40 - var message = this.state.message;
41 - return <input type="text" value={message} onChange={this.handleChange} />;
42 - }
43 -});
44 -```
45 -
46 -이것은 정말 잘 동작하고, 데이터가 어떻게 흐르는지 매우 명확하게 보여지지만, 폼필드가 많을 경우 약간 장황해 질 수 있습니다. 타이핑을 줄이기 위해 `ReactLink`를 사용해 보겠습니다.
47 -
48 -```javascript{4,9}
49 -var LinkedStateMixin = require('react-addons-linked-state-mixin');
50 -
51 -var WithLink = React.createClass({
52 - mixins: [LinkedStateMixin],
53 - getInitialState: function() {
54 - return {message: 'Hello!'};
55 - },
56 - render: function() {
57 - return <input type="text" valueLink={this.linkState('message')} />;
58 - }
59 -});
60 -```
61 -
62 -`LinkedStateMixin`는 React 컴포넌트에 `linkState()`라는 메서드를 추가합니다. `linkState()`는 React state의 현재 값과 그것을 변경할 때의 콜백을 가지는 `ReactLink` 객체를 리턴합니다.
63 -
64 -`ReactLink` 객체는 props로 트리의 위나 아래로 넘길 수 있어서, 쉽고 명확하게 계층구조에서 깊이 있는 컴포넌트와 높이 있는 state 사이의 양방향 바인딩을 설정할 수 있습니다.
65 -
66 -checkbox의 `value` 어트리뷰트는 다른 것과 다르게 checkbox가 체크되었을 때 폼 submit에 값이 전달되는 것에 주의하세요.(기본값 `on`) 그래서 `value` 어트리뷰트는 checkbox가 체크되거나 해제될 때 업데이트되지 않습니다. checkbox에서는 `valueLink`대신 `checkedLink`를 사용하셔야 합니다.
67 -```
68 -<input type="checkbox" checkedLink={this.linkState('booleanValue')} />
69 -```
70 -
71 -## 내부 구조
72 -
73 -`ReactLink`에는 크게 인스턴스를 생성하는 면과 사용하는 면이 있습니다. `ReactLink`가 얼마나 간단한지 확인하기 위해, 이 부분들을 보다 명시적으로 고쳐 봅시다.
74 -
75 -### LinkedStateMixin 없이 ReactLink 쓰기
76 -
77 -```javascript{5-7,9-12}
78 -var WithoutMixin = React.createClass({
79 - getInitialState: function() {
80 - return {message: 'Hello!'};
81 - },
82 - handleChange: function(newValue) {
83 - this.setState({message: newValue});
84 - },
85 - render: function() {
86 - var valueLink = {
87 - value: this.state.message,
88 - requestChange: this.handleChange
89 - };
90 - return <input type="text" valueLink={valueLink} />;
91 - }
92 -});
93 -```
94 -
95 -보시다시피, `ReactLink` 객체는 `value`와 `requestChange` prop만 가지는 매우 간단한 객체입니다. `LinkedStateMixin`도 간단합니다. 그냥 `this.state`의 값과 `this.setState()`에서 호출되는 콜백을 필드로 가질 뿐입니다.
96 -
97 -### valueLink 없이 ReactLink 쓰기
98 -
99 -```javascript
100 -var LinkedStateMixin = require('react-addons-linked-state-mixin');
101 -
102 -var WithoutLink = React.createClass({
103 - mixins: [LinkedStateMixin],
104 - getInitialState: function() {
105 - return {message: 'Hello!'};
106 - },
107 - render: function() {
108 - var valueLink = this.linkState('message');
109 - var handleChange = function(e) {
110 - valueLink.requestChange(e.target.value);
111 - };
112 - return <input type="text" value={valueLink.value} onChange={handleChange} />;
113 - }
114 -});
115 -```
116 -
117 -`valueLink` prop도 간단합니다. 단순히 `onChange` 이벤트를 처리하고 `this.props.valueLink.requestChange()`를 호출하고 `this.props.value`대신 `this.props.valueLink.value`를 사용합니다. 그게 다에요!
docs/docs/10.2-form-input-binding-sugar.zh-CN.md deleted
-117
@@ -1,117 +0,0 @@
1 ----
2 -id: two-way-binding-helpers-zh-CN
3 -title: 双向绑定辅助
4 -permalink: docs/two-way-binding-helpers-zh-CN.html
5 -prev: animation-zh-CN.html
6 -next: test-utils-zh-CN.html
7 ----
8 -
9 -`ReactLink` 是一个用React表达双向绑定的简单方法。
10 -
11 -> 注意:
12 ->
13 -> 在 React v15 中 ReactLink 被弃用了。推荐明确的设置值和变动的处理,而不是使用 ReactLink。
14 -
15 -在React里,数据单向流动: 从拥有者到子级。这是因为数据只单向流动[the Von Neumann model of computing](https://en.wikipedia.org/wiki/Von_Neumann_architecture)。你可以把它想象为 “单向数据绑定”。
16 -
17 -然而,有很多应用需要你去读某些数据并回流他们到你的程序。例如,当开发forms,你会常常想更新一些React `state` 当你收到用户输入的时候。或者也许你想在JavaScript完成布局并相应一些DOM元素大小的变化。
18 -
19 -在React里,你可以用监听 "change" 事件来实现它,从你的数据源(通常是DOM)读取并在你的某个组件调用 `setState()` 。明确的"Closing the data flow loop" 致使了更容易理解和维护的程序。更多信息见[our forms documentation](/react/docs/forms.html).
20 -
21 -双向绑定 -- 隐含的强迫DOM里的某些值总是和某些React `state` 同步 -- 简洁并支持大量多样的应用。 我们提供了 `ReactLink`:设置如上描述的通用数据回流模式的语法糖,或者 "linking" 某些数据结构到 React `state`.
22 -
23 -> 注意:
24 ->
25 -> `ReactLink` 只是一层对 `onChange`/`setState()` 模式的薄包装。它没有根本性的改变你的React应用里数据如何流动。
26 -
27 -## ReactLink: 之前和之后
28 -
29 -这里有一个简单的 不用 `ReactLink` 的 form 例子:
30 -
31 -```javascript
32 -var NoLink = React.createClass({
33 - getInitialState: function() {
34 - return {message: 'Hello!'};
35 - },
36 - handleChange: function(event) {
37 - this.setState({message: event.target.value});
38 - },
39 - render: function() {
40 - var message = this.state.message;
41 - return <input type="text" value={message} onChange={this.handleChange} />;
42 - }
43 -});
44 -```
45 -
46 -这个工作的很好并且数据如何流动很清晰,然而,当有大量的 form fields时,可能会有些冗长。让我们使用 `ReactLink` 来节省我们的输入:
47 -
48 -```javascript{4,9}
49 -var LinkedStateMixin = require('react-addons-linked-state-mixin');
50 -
51 -var WithLink = React.createClass({
52 - mixins: [LinkedStateMixin],
53 - getInitialState: function() {
54 - return {message: 'Hello!'};
55 - },
56 - render: function() {
57 - return <input type="text" valueLink={this.linkState('message')} />;
58 - }
59 -});
60 -```
61 -
62 -`LinkedStateMixin` 添加了一个 `linkState()` 方法到你的React组件。`linkState()` 返回一个 `ReactLink` 包含当前React state值的对象和一个改变它的回调函数。
63 -
64 -`ReactLink` 对象可以作为props在树中上下传递,所以很容易(显示的)在深层次的组件和高层次的state之间 设置双向绑定。
65 -
66 -注意 checkboxes 有一个关于他们 `value` 属性的特殊行为,这个行为是 如果checkbox被选中 值会在表单提交时被发送。 `value` 不会 checkbox 选中或是不选中时更新。对于checkboxes,你应该用`checkedLink` 代替 `valueLink`:
67 -```
68 -<input type="checkbox" checkedLink={this.linkState('booleanValue')} />
69 -```
70 -
71 -## 引擎盖下
72 -
73 -这里对 `ReactLink`有两方面:创建`ReactLink`的实例以及使用它的地方。为了证明`ReactLink`有多简单,让我们重写两方面一边更好的理解。
74 -
75 -### ReactLink Without LinkedStateMixin
76 -
77 -```javascript{5-7,9-12}
78 -var WithoutMixin = React.createClass({
79 - getInitialState: function() {
80 - return {message: 'Hello!'};
81 - },
82 - handleChange: function(newValue) {
83 - this.setState({message: newValue});
84 - },
85 - render: function() {
86 - var valueLink = {
87 - value: this.state.message,
88 - requestChange: this.handleChange
89 - };
90 - return <input type="text" valueLink={valueLink} />;
91 - }
92 -});
93 -```
94 -
95 -正如你所见,`ReactLink`对象是非常简单,只有`value`和`requestChange`属性.并且`LinkStateMixin`也很简单:它只是作用(populates)于`this.state`的元素值并且回调名为`this.setState()`的函数.
96 -
97 -### ReactLink Without valueLink
98 -
99 -```javascript
100 -var LinkedStateMixin = require('react-addons-linked-state-mixin');
101 -
102 -var WithoutLink = React.createClass({
103 - mixins: [LinkedStateMixin],
104 - getInitialState: function() {
105 - return {message: 'Hello!'};
106 - },
107 - render: function() {
108 - var valueLink = this.linkState('message');
109 - var handleChange = function(e) {
110 - valueLink.requestChange(e.target.value);
111 - };
112 - return <input type="text" value={valueLink.value} onChange={handleChange} />;
113 - }
114 -});
115 -```
116 -
117 -对于`valueLink`的属性同样也很简单,它只是简单的处理`onChange`事件,调用`this.props.valueLink.requestChange()`的时候也使用`this.props.valueLink.requestChange()`代替`this.props.value`.这就是双向绑定!
docs/docs/10.3-class-name-manipulation.it-IT.md deleted
-62
@@ -1,62 +0,0 @@
1 ----
2 -id: class-name-manipulation-it-IT
3 -title: Manipolazione del Nome di Classe
4 -permalink: docs/class-name-manipulation-it-IT.html
5 -prev: two-way-binding-helpers-it-IT.html
6 -next: test-utils-it-IT.html
7 ----
8 -
9 -> NOTA:
10 ->
11 -> Questo modulo esiste adesso in forma separata come [JedWatson/classnames](https://github.com/JedWatson/classnames) ed è indipendente da React. Questo add-on verrà quindi rimosso nell'immediato futuro.
12 -
13 -`classSet()` è una elegante utility per manipolare facilmente la stringa dell'attributo `class` del DOM.
14 -
15 -Ecco uno scenario comune e la sua soluzione senza `classSet()`:
16 -
17 -```javascript
18 -// all'interno di un componente React `<Message />`
19 -render: function() {
20 - var classString = 'message';
21 - if (this.props.isImportant) {
22 - classString += ' message-important';
23 - }
24 - if (this.props.isRead) {
25 - classString += ' message-read';
26 - }
27 - // 'message message-important message-read'
28 - return <div className={classString}>Fantastico, vediamoci lì.</div>;
29 -}
30 -```
31 -
32 -Questo può facilmente diventare noioso, in quanto assegnare stringhe per nomi di classi può essere difficile da leggere e soggetto ad errori. `classSet()` risolve questo problema:
33 -
34 -```javascript
35 -render: function() {
36 - var cx = React.addons.classSet;
37 - var classes = cx({
38 - 'message': true,
39 - 'message-important': this.props.isImportant,
40 - 'message-read': this.props.isRead
41 - });
42 - // same final string, but much cleaner
43 - return <div className={classes}>Fantastico, vediamoci lì.</div>;
44 -}
45 -```
46 -
47 -Quando usi `classSet()`, passa un oggetto le cui chiavi sono i nomi di classe CSS di cui potresti o meno avere bisogno. Valori di verità risulteranno nell'inclusione della chiave nella stringa risultante.
48 -
49 -`classSet()` ti permette inoltre di passare nomi di classe che devono essere concatenati come argomenti:
50 -
51 -```javascript
52 -render: function() {
53 - var cx = React.addons.classSet;
54 - var importantModifier = 'message-important';
55 - var readModifier = 'message-read';
56 - var classes = cx('message', importantModifier, readModifier);
57 - // Final string is 'message message-important message-read'
58 - return <div className={classes}>Fantastico, vediamoci lì.</div>;
59 -}
60 -```
61 -
62 -Niente più hack per concatenare le stringhe!
docs/docs/10.3-class-name-manipulation.ja-JP.md deleted
-61
@@ -1,61 +0,0 @@
1 ----
2 -id: class-name-manipulation
3 -title: クラス名の操作
4 -permalink: docs/class-name-manipulation-ja-JP.html
5 -prev: two-way-binding-helpers-ja-JP.html
6 -next: test-utils-ja-JP.html
7 ----
8 -
9 -> 注意:
10 -> このモジュールは現在[JedWatson/classnames](https://github.com/JedWatson/classnames)に独立して存在しており、Reactは変更を検知していません。したがって、こちらは将来削除される予定です。
11 -
12 -`classSet()` はDOMの `class` 文字列を簡単に操作するすっきりとしたユーティリティです。
13 -
14 -以下は、 `classSet()` を使用しない共通なシナリオと解決策です。
15 -
16 -```javascript
17 -// `<Message />` などの中のReactコンポーネント
18 -render: function() {
19 - var classString = 'message';
20 - if (this.props.isImportant) {
21 - classString += ' message-important';
22 - }
23 - if (this.props.isRead) {
24 - classString += ' message-read';
25 - }
26 - // 'message message-important message-read'
27 - return <div className={classString}>Great, I'll be there.</div>;
28 -}
29 -```
30 -
31 -上記は、クラス名を文字列として渡しているので、面倒で、読みにくく、エラーが発生しやすくなります。以下のように、 `classSet()` を使用するとこの問題が解決します。
32 -
33 -```javascript
34 -render: function() {
35 - var cx = React.addons.classSet;
36 - var classes = cx({
37 - 'message': true,
38 - 'message-important': this.props.isImportant,
39 - 'message-read': this.props.isRead
40 - });
41 - // 同様に最終的には文字列になりますが、クリアにはなります
42 - return <div className={classes}>Great, I'll be there.</div>;
43 -}
44 -```
45 -
46 - `classSet()` を使用する際には、キーと、必要であったり、必要でないCSSのクラス名をオブジェクトとして渡してください。値が真であるものはキーとなり、最終的には文字列の一部になります。
47 -
48 -`classSet()` もまた、以下のように連結した文字列の引数としてクラス名を渡します。
49 -
50 -```javascript
51 -render: function() {
52 - var cx = React.addons.classSet;
53 - var importantModifier = 'message-important';
54 - var readModifier = 'message-read';
55 - var classes = cx('message', importantModifier, readModifier);
56 - // 最終的な文字列は 'message message-important message-read'
57 - return <div className={classes}>Great, I'll be there.</div>;
58 -}
59 -```
60 -
61 -文字列の連結を手で書くのはやめましょう!
docs/docs/10.3-class-name-manipulation.ko-KR.md deleted
-62
@@ -1,62 +0,0 @@
1 ----
2 -id: class-name-manipulation-ko-KR
3 -title: 클래스 이름 조작
4 -permalink: docs/class-name-manipulation-ko-KR.html
5 -prev: two-way-binding-helpers-ko-KR.html
6 -next: test-utils-ko-KR.html
7 ----
8 -
9 -> 주의:
10 ->
11 -> 이 모듈은 폐기예정입니다. 대신 [JedWatson/classnames](https://github.com/JedWatson/classnames)를 사용하세요.
12 -
13 -`classSet()`은 간단히 DOM `class` 문자열을 조작하는 편리한 도구입니다.
14 -
15 -일반적으로 있을법한 경우와 `classSet()`을 사용하지 않았을 때의 처리법을 보시죠.
16 -
17 -```javascript
18 -// 어떤 `<Message />` React 컴포넌트의 안쪽
19 -render: function() {
20 - var classString = 'message';
21 - if (this.props.isImportant) {
22 - classString += ' message-important';
23 - }
24 - if (this.props.isRead) {
25 - classString += ' message-read';
26 - }
27 - // 'message message-important message-read'
28 - return <div className={classString}>좋아요, 거기서 봅시다.</div>;
29 -}
30 -```
31 -
32 -이것은 순식간에 장황해질 수 있습니다. 클래스 이름 문자열은 읽기 어렵고 에러가 발생하기도 쉽죠. `classSet()`가 이 문제를 해결할 수 있습니다.
33 -
34 -```javascript
35 -render: function() {
36 - var cx = React.addons.classSet;
37 - var classes = cx({
38 - 'message': true,
39 - 'message-important': this.props.isImportant,
40 - 'message-read': this.props.isRead
41 - });
42 - // 최종 문자열은 동일하지만, 훨씬 깔끔함
43 - return <div className={classes}>좋아요, 거기서 봅시다.</div>;
44 -}
45 -```
46 -
47 -`classSet()`을 사용할 때 사용할지 안할지 잘 모르는 CSS 클래스 이름 키와 함께 객체를 전달합니다. true로 간주되는(Truthy) 값은 키를 결과 문자열의 일부로 만듭니다.
48 -
49 -`classSet()`은 클래스 이름을 인자로 넘겨 연결되게 할 수도 있습니다.
50 -
51 -```javascript
52 -render: function() {
53 - var cx = React.addons.classSet;
54 - var importantModifier = 'message-important';
55 - var readModifier = 'message-read';
56 - var classes = cx('message', importantModifier, readModifier);
57 - // 최종 문자열은 'message message-important message-read'
58 - return <div className={classes}>좋아요, 거기서 봅시다.</div>;
59 -}
60 -```
61 -
62 -복잡한 문자열 연결은 이제 안하셔도 됩니다!
docs/docs/10.3-class-name-manipulation.md deleted
-11
@@ -1,11 +0,0 @@
1 ----
2 -id: class-name-manipulation
3 -title: Class Name Manipulation
4 -permalink: docs/class-name-manipulation.html
5 -prev: two-way-binding-helpers.html
6 -next: test-utils.html
7 ----
8 -
9 -> NOTE:
10 ->
11 -> This module has been deprecated; use [JedWatson/classnames](https://github.com/JedWatson/classnames) instead.
docs/docs/10.3-class-name-manipulation.zh-CN.md deleted
-11
@@ -1,11 +0,0 @@
1 ----
2 -id: class-name-manipulation-zh-CN
3 -title: 类名操纵
4 -permalink: docs/class-name-manipulation-zh-CN.html
5 -prev: two-way-binding-helpers-zh-CN.html
6 -next: test-utils-zh-CN.html
7 ----
8 -
9 -> NOTE:
10 ->
11 -> 此模块已被弃用; 用 [JedWatson/classnames](https://github.com/JedWatson/classnames) 替代.
docs/docs/10.4-test-utils.it-IT.md deleted
-233
@@ -1,233 +0,0 @@
1 ----
2 -id: test-utils-it-IT
3 -title: Utilità di Test
4 -permalink: docs/test-utils-it-IT.html
5 -prev: two-way-binding-helpers-it-IT.html
6 -next: clone-with-props-it-IT.html
7 ----
8 -
9 -`React.addons.TestUtils` semplifica la validazione dei componenti React nel framework di test di tua scelta (noi utilizziamo [Jest](https://facebook.github.io/jest/)).
10 -
11 -### Simulate
12 -
13 -```javascript
14 -Simulate.{eventName}(
15 - DOMElement element,
16 - [object eventData]
17 -)
18 -```
19 -
20 -Simula l'inoltro di un evento su un nodo DOM con dei dati dell'evento opzionali `eventData`. **Questa è probabilmente l'utilità più essenziale in `ReactTestUtils`.**
21 -
22 -**Cliccare un elemento**
23 -
24 -```javascript
25 -var node = ReactDOM.findDOMNode(this.refs.button);
26 -React.addons.TestUtils.Simulate.click(node);
27 -```
28 -
29 -**Cambiare il valore di un campo di input e in seguito premere INVIO**
30 -
31 -```javascript
32 -var node = ReactDOM.findDOMNode(this.refs.input);
33 -node.value = 'giraffe';
34 -React.addons.TestUtils.Simulate.change(node);
35 -React.addons.TestUtils.Simulate.keyDown(node, {key: "Enter", keyCode: 13, which: 13});
36 -```
37 -
38 -*nota che dovrai fornire tu stesso ciascuna proprietà dell'evento utilizzata nel tuo componente (ad es. keyCode, which, etc...) in quanto React non crea alcuna di esse per te*
39 -
40 -`Simulate` possiede un metodo per ciascun evento che React comprende.
41 -
42 -### renderIntoDocument
43 -
44 -```javascript
45 -ReactComponent renderIntoDocument(
46 - ReactElement instance
47 -)
48 -```
49 -
50 -Effettua il rendering di un componente in un nodo DOM staccato dal documento. **Questa funzione richiede la presenza del DOM.**
51 -
52 -### mockComponent
53 -
54 -```javascript
55 -object mockComponent(
56 - function componentClass,
57 - [string mockTagName]
58 -)
59 -```
60 -
61 -Passa il mock di un componente a questo metodo per aumentarlo con metodi utili che gli permettono di essere utilizzato come un componente React fantoccio. Anziché essere visualizzato come al solito, il componente diventerà un semplice `<div>` (o qualsiasi altro tag se fornito come valore di `mockTagName`) contenente ciascun figlio fornito.
62 -
63 -### isElement
64 -
65 -```javascript
66 -boolean isElement(
67 - ReactElement element
68 -)
69 -```
70 -
71 -Restituisce `true` se `element` è un qualunque ReactElement.
72 -
73 -### isElementOfType
74 -
75 -```javascript
76 -boolean isElementOfType(
77 - ReactElement element,
78 - function componentClass
79 -)
80 -```
81 -
82 -Restituisce `true` se `element` è un ReactElement il cui tipo è la classe React `componentClass`.
83 -
84 -### isDOMComponent
85 -
86 -```javascript
87 -boolean isDOMComponent(
88 - ReactComponent instance
89 -)
90 -```
91 -
92 -Restituisce `true` se `instance` è un componente DOM (come ad esempio `<div>` o `<span>`).
93 -
94 -### isCompositeComponent
95 -
96 -```javascript
97 -boolean isCompositeComponent(
98 - ReactComponent instance
99 -)
100 -```
101 -
102 -Restituisce `true` se `instance` è un componente composito (creato tramite `React.createClass()`).
103 -
104 -### isCompositeComponentWithType
105 -
106 -```javascript
107 -boolean isCompositeComponentWithType(
108 - ReactComponent instance,
109 - function componentClass
110 -)
111 -```
112 -
113 -Restituisce `true` se `instance` è un componente composito (creato tramite `React.createClass()`) il cui tipo è una classe React dal nome `componentClass`.
114 -
115 -### findAllInRenderedTree
116 -
117 -```javascript
118 -array findAllInRenderedTree(
119 - ReactComponent tree,
120 - function test
121 -)
122 -```
123 -
124 -Attraversa tutti i componenti in `tree` e accumula tutti i componenti per i quali `test(component)` è `true`. Non è molto utile usata da sola, ma diventa ptente se usata come primitiva per altre utilità di test.
125 -
126 -### scryRenderedDOMComponentsWithClass
127 -
128 -```javascript
129 -array scryRenderedDOMComponentsWithClass(
130 - ReactComponent tree, string className
131 -)
132 -```
133 -
134 -Trova tutte le istanze di componenti nell'albero visualizzato che sono componenti DOM il cui nome di classe corrisponde a `className`.
135 -
136 -### findRenderedDOMComponentWithClass
137 -
138 -```javascript
139 -ReactComponent findRenderedDOMComponentWithClass(
140 - ReactComponent tree,
141 - string className
142 -)
143 -```
144 -
145 -Simile a `scryRenderedDOMComponentsWithClass()` ma si aspetta di trovare un solo risultato, e restituisce quel solo risultato, oppure lancia un'eccezione se viene trovato qualunque altro numero di occorrenze diverso da uno.
146 -
147 -### scryRenderedDOMComponentsWithTag
148 -
149 -```javascript
150 -array scryRenderedDOMComponentsWithTag(
151 - ReactComponent tree,
152 - string tagName
153 -)
154 -```
155 -
156 -Trova tutte le istanze di componenti nell'albero visualizzato che sono componenti DOM il cui nome di tag corrisponde a `tagName`.
157 -
158 -### findRenderedDOMComponentWithTag
159 -
160 -```javascript
161 -ReactComponent findRenderedDOMComponentWithTag(
162 - ReactComponent tree,
163 - string tagName
164 -)
165 -```
166 -
167 -Simile a `scryRenderedDOMComponentsWithTag()` ma si aspetta di trovare un solo risultato, e restituisce quel solo risultato, oppure lancia un'eccezione se viene trovato qualunque altro numero di occorrenze diverso da uno.
168 -
169 -### scryRenderedComponentsWithType
170 -
171 -```javascript
172 -array scryRenderedComponentsWithType(
173 - ReactComponent tree,
174 - function componentClass
175 -)
176 -```
177 -
178 -Trova tutte le istanze di componenti il cui tipo corrisponde a `componentClass`.
179 -
180 -### findRenderedComponentWithType
181 -
182 -```javascript
183 -ReactComponent findRenderedComponentWithType(
184 - ReactComponent tree, function componentClass
185 -)
186 -```
187 -
188 -Simile a `scryRenderedComponentsWithType()` si aspetta di trovare un solo risultato, oppure lancia un'eccezione se viene trovato qualunque altro numero di occorrenze diverso da uno.
189 -
190 -
191 -## Rendering superficiale
192 -
193 -Il rendering superficiale è una caratteristica sperimentale che ti permette di effettuare il rendering di un componente "ad un livello di profondità" e asserire dei fatti su ciò che viene restituito dal suo metodo render, senza preoccuparti del comportamento dei componenti figli, i quali non sono né istanziati né viene effettuato il rendering. Questo non richiede la presenza di un DOM.
194 -
195 -```javascript
196 -ReactShallowRenderer createRenderer()
197 -```
198 -
199 -Chiama questo metodo nei tuoi test per creare un renderer superficiale. Puoi pensare ad esso come un "luogo" in cui effettuare il rendering del componente che stai validando, dove può rispondere ad eventi e aggiornarsi.
200 -
201 -```javascript
202 -shallowRenderer.render(
203 - ReactElement element
204 -)
205 -```
206 -
207 -Simile a `ReactDOM.render`.
208 -
209 -```javascript
210 -ReactComponent shallowRenderer.getRenderOutput()
211 -```
212 -
213 -Dopo che `render` è stato chiamato, restituisce un output di cui è stato effettuato un rendering superficiale. Puoi quindi iniziare ad asserire fatti sull'output. Ad esempio, se il metodo render del tuo componente resituisce:
214 -
215 -```javascript
216 -<div>
217 - <span className="heading">Titolo</span>
218 - <Subcomponent foo="bar" />
219 -</div>
220 -```
221 -
222 -Allora puoi asserire:
223 -
224 -```javascript
225 -result = renderer.getRenderOutput();
226 -expect(result.type).toBe('div');
227 -expect(result.props.children).toEqual([
228 - <span className="heading">Titolo</span>,
229 - <Subcomponent foo="bar" />
230 -]);
231 -```
232 -
233 -La validazione superficiale ha al momento alcune limitazioni, in particolare non supporta i riferimenti. Stiamo rilasciando questa caratteristica in anticipo e gradiremmo ascoltare il parere della comunità React per la direzione in cui debba evolvere.
docs/docs/10.4-test-utils.ja-JP.md deleted
-183
@@ -1,183 +0,0 @@
1 ----
2 -id: test-utils
3 -title: テストユーティリティ
4 -permalink: docs/test-utils-ja-JP.html
5 -prev: two-way-binding-helpers-ja-JP.html
6 -next: clone-with-props-ja-JP.html
7 ----
8 -
9 -`React.addons.TestUtils` は選んだテストフレームワーク(私たちは[Jest](https://facebook.github.io/jest/)を使っています)において、Reactのコンポーネントをテストすることを簡単にします。
10 -
11 -### Simulate
12 -
13 -```javascript
14 -Simulate.{eventName}(DOMElement element, object eventData)
15 -```
16 -
17 -オプションの `eventData` であるイベントデータと共に、DOMノードの上でイベントのディスパッチをシミュレートします。 **これは `ReactTestUtils` の中で最も有用なユーティリティでしょう。**
18 -
19 -使用例:
20 -
21 -```javascript
22 -var node = ReactDOM.findDOMNode(this.refs.input);
23 -React.addons.TestUtils.Simulate.click(node);
24 -React.addons.TestUtils.Simulate.change(node, {target: {value: 'Hello, world'}});
25 -React.addons.TestUtils.Simulate.keyDown(node, {key: "Enter"});
26 -```
27 -
28 -`Simulate` はReactが理解出来る全てのイベントのためのメソッドを持っています。
29 -
30 -### renderIntoDocument
31 -
32 -```javascript
33 -ReactComponent renderIntoDocument(ReactElement instance)
34 -```
35 -
36 -コンポーネントをドキュメントの中で分離したDOMノードにレンダリングします。 **この関数はDOMを必要とします。**
37 -
38 -
39 -### mockComponent
40 -
41 -```javascript
42 -object mockComponent(function componentClass, string? mockTagName)
43 -```
44 -
45 -有効なダミーのReactのコンポーネントとして使われることを許可するメソッドと共にこれを増強させるためにモックとなったコンポーネントモジュールをこのメソッドに渡してください。いつものようにレンダリングされる代わりに、コンポーネントは単純で、提供された子要素はどんなものでも含む `<div>` (`mockTagName` が提供されている場合はそのタグ)になるでしょう。
46 -
47 -### isElement
48 -
49 -```javascript
50 -boolean isElement(ReactElement element)
51 -```
52 -
53 -`element` が何かしらのReactElementだった場合に `true` を返します。
54 -
55 -### isElementOfType
56 -
57 -```javascript
58 -boolean isElementOfType(ReactElement element, function componentClass)
59 -```
60 -
61 -`element` がReactの `componentClass` 型であるReactElementだった場合に `true` を返します。
62 -
63 -### isDOMComponent
64 -
65 -```javascript
66 -boolean isDOMComponent(ReactComponent instance)
67 -```
68 -
69 -`instance` がDOMのコンポーネントだった場合に `true` を返します( `<div>` や `<span>` のように)。
70 -
71 -### isCompositeComponent
72 -
73 -```javascript
74 -boolean isCompositeComponent(ReactComponent instance)`
75 -```
76 -
77 -`instance` が複合的なコンポーネントだった場合に `true` を返します(`React.createClass()` で作成されるような)。
78 -
79 -### isCompositeComponentWithType
80 -
81 -```javascript
82 -boolean isCompositeComponentWithType(ReactComponent instance, function componentClass)
83 -```
84 -
85 -`instance` が複合的なコンポーネントだった場合に `true` を返します(`React.createClass()` で作成され、型がReactの `componentClass` であるような)。
86 -
87 -### findAllInRenderedTree
88 -
89 -```javascript
90 -array findAllInRenderedTree(ReactComponent tree, function test)
91 -```
92 -
93 -`tree` の中の全てのコンポーネントや `test(component)` が `true` となる蓄積された全てのコンポーネントを検討します。これはこれだけでは有用ではありませんが、他のテストユーティリティの根本として使われます。
94 -
95 -### scryRenderedDOMComponentsWithClass
96 -
97 -```javascript
98 -array scryRenderedDOMComponentsWithClass(ReactComponent tree, string className)
99 -```
100 -
101 -レンダリングされたツリーの中で、DOMコンポーネントであり、クラス名が `className` にマッチする、コンポーネントの全てのインスタンスを見つけます。
102 -
103 -### findRenderedDOMComponentWithClass
104 -
105 -```javascript
106 -ReactComponent findRenderedDOMComponentWithClass(ReactComponent tree, string className)
107 -```
108 -
109 -`scryRenderedDOMComponentsWithClass()` に似ていますが、結果が1つであること、それを返すこと、またはマッチする個数が1個以外だった場合に例外を投げることを予期します。
110 -
111 -### scryRenderedDOMComponentsWithTag
112 -
113 -```javascript
114 -array scryRenderedDOMComponentsWithTag(ReactComponent tree, string tagName)
115 -```
116 -
117 -レンダリングされたツリーの中で、DOMコンポーネントであり、タグ名が `tagName` にマッチする、コンポーネントの全てのインスタンスを見つけます。
118 -
119 -### findRenderedDOMComponentWithTag
120 -
121 -```javascript
122 -ReactComponent findRenderedDOMComponentWithTag(ReactComponent tree, string tagName)
123 -```
124 -
125 -`scryRenderedDOMComponentsWithTag()` に似ていますが、結果が1つであること、それを返すこと、またはマッチする個数が1個以外だった場合に例外を投げることを予期します。
126 -
127 -### scryRenderedComponentsWithType
128 -
129 -```javascript
130 -array scryRenderedComponentsWithType(ReactComponent tree, function componentClass)
131 -```
132 -
133 -型名が `componentClass` と同様である、コンポーネントの全てのインスタンスを見つけます。
134 -
135 -### findRenderedComponentWithType
136 -
137 -```javascript
138 -ReactComponent findRenderedComponentWithType(ReactComponent tree, function componentClass)
139 -```
140 -
141 -`scryRenderedComponentsWithType()` と同じですが、結果が1つであること、それを返すこと、またはマッチする個数が1個以外だった場合に例外を投げることを予期します。
142 -
143 -## Shallow rendering
144 -
145 -シャローレンダリングは"第一段階の深さ"であるコンポーネントをレンダリングすることを強制し、レンダリングメソッドが返すものについての事実をアサートし、インスタンスを生成したり、レンダリングされたりしない子のコンポーネントの振る舞いについては関心しない実験的な特徴です。これはDOMを必要としません。
146 -
147 -```javascript
148 -ReactShallowRenderer createRenderer()
149 -```
150 -
151 -シャローレンダラーを作成するにはこれをテストの中で呼んでください。これをあなたがテストするコンポーネントをレンダリングする場所であると考えることができます。この場所はイベントに返答したり、これ自身を更新したりできます。
152 -
153 -```javascript
154 -shallowRenderer.render(ReactElement element)
155 -```
156 -
157 -`ReactDOM.render` に同様。
158 -
159 -```javascript
160 -ReactComponent shallowRenderer.getRenderOutput()
161 -```
162 -
163 -`render` が呼ばれた後、浅くレンダリングされた出力を返します。その後、その出力に関しての事実をアサートすることができます。例えば、以下のように、コンポーネントのレンダリングメソッドが返してきた場合は、
164 -
165 -```javascript
166 -<div>
167 - <span className="heading">Title</span>
168 - <Subcomponent foo="bar" />
169 -</div>
170 -```
171 -
172 -以下のように、アサートできます。
173 -
174 -```javascript
175 -result = renderer.getRenderOutput();
176 -expect(result.type).toBe('div');
177 -expect(result.props.children).toEqual([
178 - <span className="heading">Title</span>,
179 - <Subcomponent foo="bar" />
180 -]);
181 -```
182 -
183 -シャローテスティングは現在、制限があります。はっきり言うと、参照をサポートしていません。私たちは、この特徴を早めにリリースし、これが、どのように進化していくか、Reactのコミュニティのフィードバックを評価するつもりです。
docs/docs/10.4-test-utils.ko-KR.md deleted
-236
@@ -1,236 +0,0 @@
1 ----
2 -id: test-utils-ko-KR
3 -title: 테스트 유틸리티
4 -permalink: docs/test-utils-ko-KR.html
5 -prev: two-way-binding-helpers-ko-KR.html
6 -next: clone-with-props-ko-KR.html
7 ----
8 -
9 -`ReactTestUtils`는 선택한 테스트 프레임워크(React는 [Jest](https://facebook.github.io/jest/)를 사용)에서 React 컴포넌트를 테스트하기 쉽게 합니다.
10 -
11 -```
12 -var ReactTestUtils = require('react-addons-test-utils');
13 -```
14 -
15 -### Simulate
16 -
17 -```javascript
18 -Simulate.{eventName}(
19 - DOMElement element,
20 - [object eventData]
21 -)
22 -```
23 -
24 -DOM 노드에 이벤트 디스패치하는 것을 시뮬레이트합니다. 선택적으로 `eventData`를 통해 이벤트 데이터도 처리할 수 있습니다. **아마 `ReactTestUtils`에서 가장 유용한 유틸리티일 것 입니다.**
25 -
26 -**엘리먼트 클릭**
27 -
28 -```javascript
29 -// <button ref="button">...</button>
30 -var node = this.refs.button;
31 -ReactTestUtils.Simulate.click(node);
32 -```
33 -
34 -**입력 필드의 값을 변경하고 엔터 누르기.**
35 -
36 -```javascript
37 -// <input ref="input" />
38 -var node = this.refs.input;
39 -node.value = 'giraffe';
40 -ReactTestUtils.Simulate.change(node);
41 -ReactTestUtils.Simulate.keyDown(node, {key: "Enter", keyCode: 13, which: 13});
42 -```
43 -
44 -*컴포넌트에서 사용할 이벤트 프로퍼티(예를 들어 keyCode, which, 등등...)는 React에서 만들어 주지 않으므로 직접 제공해야 합니다.*
45 -
46 -`Simulate`에는 React가 이해하는 모든 이벤트에 대해 메소드가 있습니다.
47 -
48 -### renderIntoDocument
49 -
50 -```javascript
51 -ReactComponent renderIntoDocument(
52 - ReactElement instance
53 -)
54 -```
55 -
56 -문서의 detach된 DOM 노드에 컴포넌트를 렌더합니다. **이 기능은 DOM을 필요로 합니다.**
57 -
58 -> 주의:
59 ->
60 -> React를 임포트하기 **전에** `window`, `window.document`, `window.document.createElement`을 전역적으로 사용가능하게 해두어야 합니다. 아니면 React는 DOM과 `setState`같은 메소드가 동작하지 않는다고 생각할 수 있습니다.
61 -
62 -### mockComponent
63 -
64 -```javascript
65 -object mockComponent(
66 - function componentClass,
67 - [string mockTagName]
68 -)
69 -```
70 -
71 -목 컴포넌트 모듈을 이 메소드에 넘겨 더미 React 컴포넌트로 사용할 수 있도록 합니다. 이 더미는 유용한 메소드와 함께 사용해 기능을 보강할 수 있습니다. 일반적인 렌더링과는 다르게, 컴포넌트는 제공된 자식을 포함하는 평범한 `<div>`가 됩니다. (`mockTagName`을 통해 div가 아닌 다른 태그를 지정해 줄 수도 있습니다.)
72 -
73 -### isElement
74 -
75 -```javascript
76 -boolean isElement(
77 - ReactElement element
78 -)
79 -```
80 -
81 -`element`가 ReactElement면 `true`를 리턴합니다.
82 -
83 -### isElementOfType
84 -
85 -```javascript
86 -boolean isElementOfType(
87 - ReactElement element,
88 - function componentClass
89 -)
90 -```
91 -
92 -`element`가 React `componentClass` 타입인 ReactElement면 `true`를 리턴합니다.
93 -
94 -### isDOMComponent
95 -
96 -```javascript
97 -boolean isDOMComponent(
98 - ReactComponent instance
99 -)
100 -```
101 -
102 -`instance`가 (`<div>`나 `<span>`같은) DOM 컴포넌트면 `true`를 리턴합니다.
103 -
104 -### isCompositeComponent
105 -
106 -```javascript
107 -boolean isCompositeComponent(ReactComponent instance)`
108 -```
109 -
110 -`instance`가 (`React.createClass()`로 생성된) 복합 컴포넌트면 `true`를 리턴합니다.
111 -
112 -### isCompositeComponentWithType
113 -
114 -```javascript
115 -boolean isCompositeComponentWithType(
116 - ReactComponent instance,
117 - function componentClass
118 -)
119 -```
120 -
121 -`instance`가 (`React.createClass()`로 생성된) 복합 컴포넌트고 React `componentClass` 타입이면 `true`를 리턴합니다.
122 -
123 -### findAllInRenderedTree
124 -
125 -```javascript
126 -array findAllInRenderedTree(
127 - ReactComponent tree,
128 - function test
129 -)
130 -```
131 -
132 -`tree`안의 모든 컴포넌트에서 `test(component)`가 `true`인 모든 컴포넌트를 모읍니다. 이것만으로는 그렇게 유용하지 않습니다만, 다른 테스트 유틸와 같이 사용합니다.
133 -
134 -### scryRenderedDOMComponentsWithClass
135 -
136 -```javascript
137 -array scryRenderedDOMComponentsWithClass(
138 - ReactComponent tree, string className
139 -)
140 -```
141 -렌더된 트리의 모든 컴포넌트 인스턴스 중에서 클래스 이름이 `className`인 DOM 컴포넌트들을 찾습니다.
142 -
143 -### findRenderedDOMComponentWithClass
144 -
145 -```javascript
146 -ReactComponent findRenderedDOMComponentWithClass(ReactComponent tree, string className)
147 -```
148 -
149 -`scryRenderedDOMComponentsWithClass()`와 비슷하지만 하나의 결과만 기대될 때 사용합니다. 하나의 결과를 리턴하거나 한개 이상의 결과가 나온 경우에는 예외를 던집니다.
150 -
151 -### scryRenderedDOMComponentsWithTag
152 -
153 -```javascript
154 -array scryRenderedDOMComponentsWithTag(
155 - ReactComponent tree,
156 - string tagName
157 -)
158 -```
159 -
160 -렌더된 트리의 모든 컴포넌트 인스턴스중에서 태그 이름이 `tagName`인 DOM 컴포넌트들을 찾습니다.
161 -
162 -### findRenderedDOMComponentWithTag
163 -
164 -```javascript
165 -ReactComponent findRenderedDOMComponentWithTag(
166 - ReactComponent tree,
167 - string tagName
168 -)
169 -```
170 -
171 -`scryRenderedDOMComponentsWithTag()`와 비슷하지만 하나의 결과만 기대될 때 사용합니다. 하나의 결과를 리턴하거나 한개 이상의 결과가 나온 경우에는 예외를 던집니다.
172 -
173 -### scryRenderedComponentsWithType
174 -
175 -```javascript
176 -array scryRenderedComponentsWithType(
177 - ReactComponent tree,
178 - function componentClass
179 -)
180 -```
181 -
182 -타입이 `componentClass`인 모든 컴포넌트 인스턴스를 찾습니다.
183 -
184 -### findRenderedComponentWithType
185 -
186 -```javascript
187 -ReactComponent findRenderedComponentWithType(
188 - ReactComponent tree, function componentClass
189 -)
190 -```
191 -
192 -`scryRenderedComponentsWithType()`와 비슷하지만 하나의 결과만 기대될 때 사용합니다. 하나의 결과를 리턴하거나 한개 이상의 결과가 나온 경우에는 예외를 던집니다.
193 -
194 -## 얕은 렌더링
195 -
196 -얕은 렌더링은 "한 단계 깊이의" 컴포넌트를 렌더할 수 있는 실험적인 기능입니다. 자식 컴포넌트가 인스턴스화 되거나 렌더되는 등의 동작에 대한 걱정 없이 렌더 메소드가 반환하는 것만 검증합니다. 이 기능은 DOM이 필요하지 않습니다.
197 -
198 -```javascript
199 -ReactShallowRenderer createRenderer()
200 -```
201 -
202 -테스트에서 얕은 렌더러를 생성하고자 할때 호출합니다. 이를 이벤트와 업데이트에 스스로 반응하는 컴포넌트를 렌더하기 위한 "장소"라고 생각할 수 있습니다.
203 -
204 -```javascript
205 -shallowRenderer.render(
206 - ReactElement element
207 -)
208 -```
209 -
210 -`ReactDOM.render`와 유사합니다.
211 -
212 -```javascript
213 -ReactElement shallowRenderer.getRenderOutput()
214 -```
215 -
216 -`render`가 호출 된 후, 얕게 렌더된 결과물을 반환합니다. 그 후엔 결과물에 대한 검증을 시작할 수 있습니다. 예를 들어 컴포넌트의 렌더 메소드가 다음을 반환한다면:
217 -
218 -```javascript
219 -<div>
220 - <span className="heading">Title</span>
221 - <Subcomponent foo="bar" />
222 -</div>
223 -```
224 -
225 -그 후에는 검증할 수 있습니다:
226 -
227 -```javascript
228 -result = renderer.getRenderOutput();
229 -expect(result.type).toBe('div');
230 -expect(result.props.children).toEqual([
231 - <span className="heading">Title</span>,
232 - <Subcomponent foo="bar" />
233 -]);
234 -```
235 -
236 -현재 얕은 테스트는 refs를 지원하지 않는 등 몇가지 제약사항이 있습니다. 우리는 이 기능을 빠르게 먼저 배포하고 React 커뮤니티의 피드백을 받아 나아갈 방향을 찾고자 합니다.
docs/docs/10.4-test-utils.md deleted
-250
@@ -1,250 +0,0 @@
1 ----
2 -id: test-utils
3 -title: Test Utilities
4 -permalink: docs/test-utils.html
5 -prev: two-way-binding-helpers.html
6 -next: clone-with-props.html
7 ----
8 -
9 -`ReactTestUtils` makes it easy to test React components in the testing framework of your choice. At Facebook we use [Jest](https://facebook.github.io/jest/) for painless JavaScript testing. Learn how to get started with Jest through the Jest website's [React Tutorial](http://facebook.github.io/jest/docs/tutorial-react.html#content).
10 -
11 -```
12 -var ReactTestUtils = require('react-addons-test-utils');
13 -```
14 -
15 -> Note:
16 ->
17 -> Airbnb has released a testing utility called Enzyme, which makes it easy to assert, manipulate, and traverse your React Components' output. If you're deciding on a unit testing utility to use together with Jest, or any other test runner, it's worth checking out: [http://airbnb.io/enzyme/](http://airbnb.io/enzyme/)
18 -
19 -### Simulate
20 -
21 -```javascript
22 -Simulate.{eventName}(
23 - DOMElement element,
24 - [object eventData]
25 -)
26 -```
27 -
28 -Simulate an event dispatch on a DOM node with optional `eventData` event data. **This is possibly the single most useful utility in `ReactTestUtils`.**
29 -
30 -**Clicking an element**
31 -
32 -```javascript
33 -// <button ref="button">...</button>
34 -var node = this.refs.button;
35 -ReactTestUtils.Simulate.click(node);
36 -```
37 -
38 -**Changing the value of an input field and then pressing ENTER.**
39 -
40 -```javascript
41 -// <input ref="input" />
42 -var node = this.refs.input;
43 -node.value = 'giraffe';
44 -ReactTestUtils.Simulate.change(node);
45 -ReactTestUtils.Simulate.keyDown(node, {key: "Enter", keyCode: 13, which: 13});
46 -```
47 -
48 -*Note that you will have to provide any event property that you're using in your component (e.g. keyCode, which, etc...) as React is not creating any of these for you.*
49 -
50 -`Simulate` has a method for [every event that React understands](/react/docs/events.html#supported-events).
51 -
52 -### renderIntoDocument
53 -
54 -```javascript
55 -ReactComponent renderIntoDocument(
56 - ReactElement instance
57 -)
58 -```
59 -
60 -Render a component into a detached DOM node in the document. **This function requires a DOM.**
61 -
62 -> Note:
63 ->
64 -> You will need to have `window`, `window.document` and `window.document.createElement`
65 - globally available **before** you import React. Otherwise React will think it can't access the DOM and methods like `setState` won't work.
66 -
67 -### mockComponent
68 -
69 -```javascript
70 -object mockComponent(
71 - function componentClass,
72 - [string mockTagName]
73 -)
74 -```
75 -
76 -Pass a mocked component module to this method to augment it with useful methods that allow it to be used as a dummy React component. Instead of rendering as usual, the component will become a simple `<div>` (or other tag if `mockTagName` is provided) containing any provided children.
77 -
78 -### isElement
79 -
80 -```javascript
81 -boolean isElement(
82 - ReactElement element
83 -)
84 -```
85 -
86 -Returns `true` if `element` is any ReactElement.
87 -
88 -### isElementOfType
89 -
90 -```javascript
91 -boolean isElementOfType(
92 - ReactElement element,
93 - function componentClass
94 -)
95 -```
96 -
97 -Returns `true` if `element` is a ReactElement whose type is of a React `componentClass`.
98 -
99 -### isDOMComponent
100 -
101 -```javascript
102 -boolean isDOMComponent(
103 - ReactComponent instance
104 -)
105 -```
106 -
107 -Returns `true` if `instance` is a DOM component (such as a `<div>` or `<span>`).
108 -
109 -### isCompositeComponent
110 -
111 -```javascript
112 -boolean isCompositeComponent(
113 - ReactComponent instance
114 -)
115 -```
116 -
117 -Returns `true` if `instance` is a composite component (created with `React.createClass()`).
118 -
119 -### isCompositeComponentWithType
120 -
121 -```javascript
122 -boolean isCompositeComponentWithType(
123 - ReactComponent instance,
124 - function componentClass
125 -)
126 -```
127 -
128 -Returns `true` if `instance` is a composite component (created with `React.createClass()`) whose type is of a React `componentClass`.
129 -
130 -### findAllInRenderedTree
131 -
132 -```javascript
133 -array findAllInRenderedTree(
134 - ReactComponent tree,
135 - function test
136 -)
137 -```
138 -
139 -Traverse all components in `tree` and accumulate all components where `test(component)` is `true`. This is not that useful on its own, but it's used as a primitive for other test utils.
140 -
141 -### scryRenderedDOMComponentsWithClass
142 -
143 -```javascript
144 -array scryRenderedDOMComponentsWithClass(
145 - ReactComponent tree,
146 - string className
147 -)
148 -```
149 -
150 -Finds all DOM elements of components in the rendered tree that are DOM components with the class name matching `className`.
151 -
152 -### findRenderedDOMComponentWithClass
153 -
154 -```javascript
155 -DOMElement findRenderedDOMComponentWithClass(
156 - ReactComponent tree,
157 - string className
158 -)
159 -```
160 -
161 -Like `scryRenderedDOMComponentsWithClass()` but expects there to be one result, and returns that one result, or throws exception if there is any other number of matches besides one.
162 -
163 -### scryRenderedDOMComponentsWithTag
164 -
165 -```javascript
166 -array scryRenderedDOMComponentsWithTag(
167 - ReactComponent tree,
168 - string tagName
169 -)
170 -```
171 -
172 -Finds all DOM elements of components in the rendered tree that are DOM components with the tag name matching `tagName`.
173 -
174 -### findRenderedDOMComponentWithTag
175 -
176 -```javascript
177 -DOMElement findRenderedDOMComponentWithTag(
178 - ReactComponent tree,
179 - string tagName
180 -)
181 -```
182 -
183 -Like `scryRenderedDOMComponentsWithTag()` but expects there to be one result, and returns that one result, or throws exception if there is any other number of matches besides one.
184 -
185 -### scryRenderedComponentsWithType
186 -
187 -```javascript
188 -array scryRenderedComponentsWithType(
189 - ReactComponent tree,
190 - function componentClass
191 -)
192 -```
193 -
194 -Finds all instances of components with type equal to `componentClass`.
195 -
196 -### findRenderedComponentWithType
197 -
198 -```javascript
199 -ReactComponent findRenderedComponentWithType(
200 - ReactComponent tree,
201 - function componentClass
202 -)
203 -```
204 -
205 -Same as `scryRenderedComponentsWithType()` but expects there to be one result and returns that one result, or throws exception if there is any other number of matches besides one.
206 -
207 -## Shallow rendering
208 -
209 -Shallow rendering is an experimental feature that lets you render a component "one level deep" and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered. This does not require a DOM.
210 -
211 -```javascript
212 -ReactShallowRenderer createRenderer()
213 -```
214 -
215 -Call this in your tests to create a shallow renderer. You can think of this as a "place" to render the component you're testing, where it can respond to events and update itself.
216 -
217 -```javascript
218 -shallowRenderer.render(
219 - ReactElement element
220 -)
221 -```
222 -
223 -Similar to `ReactDOM.render`.
224 -
225 -```javascript
226 -ReactElement shallowRenderer.getRenderOutput()
227 -```
228 -
229 -After `render` has been called, returns shallowly rendered output. You can then begin to assert facts about the output. For example, if your component's render method returns:
230 -
231 -```javascript
232 -<div>
233 - <span className="heading">Title</span>
234 - <Subcomponent foo="bar" />
235 -</div>
236 -```
237 -
238 -Then you can assert:
239 -
240 -```javascript
241 -var renderer = ReactTestUtils.createRenderer();
242 -result = renderer.getRenderOutput();
243 -expect(result.type).toBe('div');
244 -expect(result.props.children).toEqual([
245 - <span className="heading">Title</span>,
246 - <Subcomponent foo="bar" />
247 -]);
248 -```
249 -
250 -Shallow testing currently has some limitations, namely not supporting refs. We're releasing this feature early and would appreciate the React community's feedback on how it should evolve.
docs/docs/10.4-test-utils.zh-CN.md deleted
-244
@@ -1,244 +0,0 @@
1 ----
2 -id: test-utils-zh-CN
3 -title: 测试工具
4 -permalink: docs/test-utils-zh-CN.html
5 -prev: two-way-binding-helpers-zh-CN.html
6 -next: clone-with-props-zh-CN.html
7 ----
8 -
9 -`ReactTestUtils` 使你在你选择的测试框架中 (我们使用 [Jest](https://facebook.github.io/jest/)) 测试 React 组件变得容易。
10 -
11 -```
12 -var ReactTestUtils = require('react-addons-test-utils');
13 -```
14 -
15 -### Simulate
16 -
17 -```javascript
18 -Simulate.{eventName}(
19 - DOMElement element,
20 - [object eventData]
21 -)
22 -```
23 -
24 -模拟一个在 DOM 节点上带有可选 `eventData` 事件数据的事件派遣(event dispatch)。**这可能是 `ReactTestUtils` 里单独最有用的工具。**
25 -
26 -**点击一个元素**
27 -
28 -```javascript
29 -// <button ref="button">...</button>
30 -var node = this.refs.button;
31 -ReactTestUtils.Simulate.click(node);
32 -```
33 -
34 -**改变 input 域的值然后点击 回车。**
35 -
36 -```javascript
37 -// <input ref="input" />
38 -var node = this.refs.input;
39 -node.value = 'giraffe';
40 -ReactTestUtils.Simulate.change(node);
41 -ReactTestUtils.Simulate.keyDown(node, {key: "Enter", keyCode: 13, which: 13});
42 -```
43 -
44 -*注意你将必须提供任何你在你的组件里使用的事件属性(例如 keyCode, which, 等等)因为React没有为你创建任何这类东西。*
45 -
46 -`Simulate` has a method for [every event that React understands](/react/docs/events.html#supported-events).
47 -
48 -### renderIntoDocument
49 -
50 -```javascript
51 -ReactComponent renderIntoDocument(
52 - ReactElement instance
53 -)
54 -```
55 -
56 -渲染一个组件到 document 里的 detached DOM 节点。**这个函数需要一个 DOM。**
57 -
58 -> 注意:
59 ->
60 -> 在你 import React **之前**,你需要让 `window`, `window.document` 和 `window.document.createElement` 全局可用。
61 -不然 React 会认为它不能访问 DOM 然后类似 `setState` 的方法会不工作。
62 -
63 -### mockComponent
64 -
65 -```javascript
66 -object mockComponent(
67 - function componentClass,
68 - [string mockTagName]
69 -)
70 -```
71 -
72 -传入一个 mocked 组件模块到这个方法来给它增加有用的方法,使它可以被用作 dummy React 组件。代替像通常一样的渲染,组件会成为一个简单的包含了任意被提供的子级的 `<div>` (或者其他 tag 名,如果提供了 `mockTagName`)
73 -
74 -### isElement
75 -
76 -```javascript
77 -boolean isElement(
78 - ReactElement element
79 -)
80 -```
81 -
82 -返回 `true` 如果 `element` 是任意的 ReactElement。
83 -
84 -### isElementOfType
85 -
86 -```javascript
87 -boolean isElementOfType(
88 - ReactElement element,
89 - function componentClass
90 -)
91 -```
92 -
93 -返回 `true` 如果 `element` 是一个类型是 React `componentClass` 的 ReactElement。
94 -
95 -### isDOMComponent
96 -
97 -```javascript
98 -boolean isDOMComponent(
99 - ReactComponent instance
100 -)
101 -```
102 -
103 -返回 `true` 如果 `instance` 是一个 DOM 组件 (比如一个 `<div>` 或者 `<span>`)。
104 -
105 -### isCompositeComponent
106 -
107 -```javascript
108 -boolean isCompositeComponent(
109 - ReactComponent instance
110 -)
111 -```
112 -
113 -返回 `true` 如果 `instance` 是一个复合组件 (由 `React.createClass()` 创建)。
114 -
115 -### isCompositeComponentWithType
116 -
117 -```javascript
118 -boolean isCompositeComponentWithType(
119 - ReactComponent instance,
120 - function componentClass
121 -)
122 -```
123 -
124 -返回 `true` 如果 `instance` 是一个类型为 React `componentClass` 的复合组件 (由 `React.createClass()` 创建)。
125 -
126 -### findAllInRenderedTree
127 -
128 -```javascript
129 -array findAllInRenderedTree(
130 - ReactComponent tree,
131 - function test
132 -)
133 -```
134 -
135 -遍历 `tree` 里所有的组件,并累积所有 `test(component)` 为 `true` 的组件。它本身并没有什么用,但是它被用作其他测试工具的基本元素。
136 -
137 -### scryRenderedDOMComponentsWithClass
138 -
139 -```javascript
140 -array scryRenderedDOMComponentsWithClass(
141 - ReactComponent tree, string className
142 -)
143 -```
144 -
145 -在渲染的树中查找所有 DOM组件的类名匹配`className` 的组件实例。
146 -
147 -### findRenderedDOMComponentWithClass
148 -
149 -```javascript
150 -ReactComponent findRenderedDOMComponentWithClass(
151 - ReactComponent tree,
152 - string className
153 -)
154 -```
155 -
156 -类似 `scryRenderedDOMComponentsWithClass()` 除了只有一个返回结果,并且要么返回这个结果,要么如果还有其他的匹配项就抛出一个异常。
157 -
158 -### scryRenderedDOMComponentsWithTag
159 -
160 -```javascript
161 -array scryRenderedDOMComponentsWithTag(
162 - ReactComponent tree,
163 - string tagName
164 -)
165 -```
166 -
167 -在渲染的树中查找所有 DOM 组件的 tag 名匹配 `tagName` 的组件实例。
168 -
169 -### findRenderedDOMComponentWithTag
170 -
171 -```javascript
172 -ReactComponent findRenderedDOMComponentWithTag(
173 - ReactComponent tree,
174 - string tagName
175 -)
176 -```
177 -
178 -类似 `scryRenderedDOMComponentsWithTag()` 除了只有一个返回结果,并且要么返回这个结果,要么如果还有其他的匹配项就抛出一个异常。
179 -
180 -### scryRenderedComponentsWithType
181 -
182 -```javascript
183 -array scryRenderedComponentsWithType(
184 - ReactComponent tree,
185 - function componentClass
186 -)
187 -```
188 -
189 -查找所有类型等于 `componentClass` 的组件实例。
190 -
191 -### findRenderedComponentWithType
192 -
193 -```javascript
194 -ReactComponent findRenderedComponentWithType(
195 - ReactComponent tree, function componentClass
196 -)
197 -```
198 -
199 -类似 `scryRenderedComponentsWithType()` 除了只有一个返回结果,并且要么返回这个结果,要么如果还有其他的匹配项就抛出一个异常。
200 -
201 -## Shallow rendering(浅渲染)
202 -
203 -浅渲染是一个实验性特性,让你渲染一个组件为 "one level deep" 并且断言渲染方法返回的内容,不用担心子组件的行为,它们没有被实例化或者渲染。这个方式不需要一个 DOM。
204 -
205 -```javascript
206 -ReactShallowRenderer createRenderer()
207 -```
208 -
209 -在你的测试里调用它来创建一个浅渲染器。你可以把它想做是一个你渲染你要测试的组件的 "地方",它可以自己响应事件并更新。
210 -
211 -```javascript
212 -shallowRenderer.render(
213 - ReactElement element
214 -)
215 -```
216 -
217 -类似于 `ReactDOM.render`。
218 -
219 -```javascript
220 -ReactElement shallowRenderer.getRenderOutput()
221 -```
222 -
223 -在 `render` 被调用后,返回一个浅渲染的输出。你可以接着断言输出的内容。例如,如果你的组件的渲染方法返回:
224 -
225 -```javascript
226 -<div>
227 - <span className="heading">Title</span>
228 - <Subcomponent foo="bar" />
229 -</div>
230 -```
231 -
232 -然后你可以断言:
233 -
234 -```javascript
235 -var renderer = ReactTestUtils.createRenderer();
236 -result = renderer.getRenderOutput();
237 -expect(result.type).toBe('div');
238 -expect(result.props.children).toEqual([
239 - <span className="heading">Title</span>,
240 - <Subcomponent foo="bar" />
241 -]);
242 -```
243 -
244 -浅测试现在有一些限制,即不支持 refs。我们在早期发布这个特性,并感激 React 社区关于它应该如何演化的反馈。
docs/docs/10.5-clone-with-props.it-IT.md deleted
-34
@@ -1,34 +0,0 @@
1 ----
2 -id: clone-with-props-it-IT
3 -title: Clonare ReactElements
4 -permalink: docs/clone-with-props-it-IT.html
5 -prev: test-utils-it-IT.html
6 -next: create-fragment-it-IT.html
7 ----
8 -
9 -> Nota:
10 -> `cloneWithProps` è deprecato. Usa [React.cloneElement](top-level-api.html#react.cloneelement) al suo posto.
11 -
12 -In rare condizioni, potresti voler creare una copia di un elemento React con proprietà diverse da quelle dell'elemento originale. Un esempio è clonare gli elementi passati come `this.props.children` ed effettuarne il rendering con proprietà diverse:
13 -
14 -```js
15 -var _makeBlue = function(element) {
16 - return React.addons.cloneWithProps(element, {style: {color: 'blue'}});
17 -};
18 -
19 -var Blue = React.createClass({
20 - render: function() {
21 - var blueChildren = React.Children.map(this.props.children, _makeBlue);
22 - return <div>{blueChildren}</div>;
23 - }
24 -});
25 -
26 -ReactDOM.render(
27 - <Blue>
28 - <p>Questo testo è blu.</p>
29 - </Blue>,
30 - document.getElementById('container')
31 -);
32 -```
33 -
34 -`cloneWithProps` non trasferisce gli attributi `key` o `ref` agli elementi clonati. Le proprietà `className` e `style` sono automaticamente riunite.
docs/docs/10.5-clone-with-props.ja-JP.md deleted
-34
@@ -1,34 +0,0 @@
1 ----
2 -id: clone-with-props
3 -title: ReactElementsをクローンすること
4 -permalink: docs/clone-with-props-ja-JP.html
5 -prev: test-utils-ja-JP.html
6 -next: create-fragment-ja-JP.html
7 ----
8 -
9 -> 注意:
10 -> `cloneWithProps` は使用不可になりました。[React.cloneElement](top-level-api-ja-JP.html#react.cloneelement)を代わりに使用してください。
11 -
12 -元のReact要素とは異なるプロパティを持った要素のコピーを作成したいと考える稀なケースがあるかと思います。1つの例としては、以下のように、 `this.props.children` に渡すように要素をクローンし、異なるプロパティを持つようそれらをレンダリングするものです。
13 -
14 -```js
15 -var _makeBlue = function(element) {
16 - return React.addons.cloneWithProps(element, {style: {color: 'blue'}});
17 -};
18 -
19 -var Blue = React.createClass({
20 - render: function() {
21 - var blueChildren = React.Children.map(this.props.children, _makeBlue);
22 - return <div>{blueChildren}</div>;
23 - }
24 -});
25 -
26 -ReactDOM.render(
27 - <Blue>
28 - <p>This text is blue.</p>
29 - </Blue>,
30 - document.getElementById('container')
31 -);
32 -```
33 -
34 -`cloneWithProps` は `key` や `ref` をクローンされた要素に渡すことはありません。 `className` や `style` は自動的にマージされます。
docs/docs/10.5-clone-with-props.ko-KR.md deleted
-36
@@ -1,36 +0,0 @@
1 ----
2 -id: clone-with-props-ko-KR
3 -title: ReactElement 클론하기
4 -permalink: docs/clone-with-props-ko-KR.html
5 -prev: test-utils-ko-KR.html
6 -next: create-fragment-ko-KR.html
7 ----
8 -
9 -> 주의:
10 -> `cloneWithProps`는 비추천입니다. 대신 [React.cloneElement](top-level-api.html#react.cloneelement)를 사용하세요.
11 -
12 -드문 경우긴 하지만 원래 엘리먼트와 다른 prop을 가진 React 엘리먼트의 복사본을 만들고 싶을 때가 있습니다. 예를 들면 `this.props.children`에 클론한 엘리먼트를 넘기고 다른 prop으로 렌더링하는 경우 입니다.
13 -
14 -```js
15 -var cloneWithProps = require('react-addons-clone-with-props');
16 -
17 -var _makeBlue = function(element) {
18 - return cloneWithProps(element, {style: {color: 'blue'}});
19 -};
20 -
21 -var Blue = React.createClass({
22 - render: function() {
23 - var blueChildren = React.Children.map(this.props.children, _makeBlue);
24 - return <div>{blueChildren}</div>;
25 - }
26 -});
27 -
28 -ReactDOM.render(
29 - <Blue>
30 - <p>This text is blue.</p>
31 - </Blue>,
32 - document.getElementById('container')
33 -);
34 -```
35 -
36 -`cloneWithProps`는 `key`나 `ref`를 클론된 엘리먼트에 전달하지 않습니다. `className`, `style` prop은 자동으로 머지됩니다.
docs/docs/10.5-clone-with-props.md deleted
-36
@@ -1,36 +0,0 @@
1 ----
2 -id: clone-with-props
3 -title: Cloning ReactElements
4 -permalink: docs/clone-with-props.html
5 -prev: test-utils.html
6 -next: create-fragment.html
7 ----
8 -
9 -> Note:
10 -> `cloneWithProps` is deprecated. Use [React.cloneElement](top-level-api.html#react.cloneelement) instead.
11 -
12 -In rare situations, you may want to create a copy of a React element with different props from those of the original element. One example is cloning the elements passed into `this.props.children` and rendering them with different props:
13 -
14 -```js
15 -var cloneWithProps = require('react-addons-clone-with-props');
16 -
17 -var _makeBlue = function(element) {
18 - return cloneWithProps(element, {style: {color: 'blue'}});
19 -};
20 -
21 -var Blue = React.createClass({
22 - render: function() {
23 - var blueChildren = React.Children.map(this.props.children, _makeBlue);
24 - return <div>{blueChildren}</div>;
25 - }
26 -});
27 -
28 -ReactDOM.render(
29 - <Blue>
30 - <p>This text is blue.</p>
31 - </Blue>,
32 - document.getElementById('container')
33 -);
34 -```
35 -
36 -`cloneWithProps` does not transfer `key` or `ref` to the cloned element. `className` and `style` props are automatically merged.
docs/docs/10.5-clone-with-props.zh-CN.md deleted
-36
@@ -1,36 +0,0 @@
1 ----
2 -id: clone-with-props-zh-CN
3 -title: 克隆 ReactElements
4 -permalink: docs/clone-with-props-zh-CN.html
5 -prev: test-utils-zh-CN.html
6 -next: create-fragment-zh-CN.html
7 ----
8 -
9 -> 注意:
10 -> `cloneWithProps` 被弃用了. 用 [React.cloneElement](top-level-api.html#react.cloneelement) 代替.
11 -
12 -在很罕见的情况下,你可能需要创建一个 React 元素的拷贝,它与初始的元素有不同的 props。一个例子是克隆这些传递到 `this.props.children` 的元素并用不同的 props 渲染他们。
13 -
14 -```js
15 -var cloneWithProps = require('react-addons-clone-with-props');
16 -
17 -var _makeBlue = function(element) {
18 - return cloneWithProps(element, {style: {color: 'blue'}});
19 -};
20 -
21 -var Blue = React.createClass({
22 - render: function() {
23 - var blueChildren = React.Children.map(this.props.children, _makeBlue);
24 - return <div>{blueChildren}</div>;
25 - }
26 -});
27 -
28 -ReactDOM.render(
29 - <Blue>
30 - <p>This text is blue.</p>
31 - </Blue>,
32 - document.getElementById('container')
33 -);
34 -```
35 -
36 -`cloneWithProps` 不传递 `key` 或者 `ref` 到被克隆的元素。`className` 和 `style` props 被自动合并。
docs/docs/10.6-create-fragment.it-IT.md deleted
-73
@@ -1,73 +0,0 @@
1 ----
2 -id: create-fragment-it-IT
3 -title: Frammenti con Chiave
4 -permalink: docs/create-fragment-it-IT.html
5 -prev: clone-with-props-it-IT.html
6 -next: update-it-IT.html
7 ----
8 -
9 -In molti casi, puoi utilizzare la proprietà `key` per specificare chiavi sugli elementi che restituisci da `render`. Tuttavia, questo approccio fallisce in una situazione: se hai due insiemi di figli che devi riordinare, non esiste alcun modo di assegnare una chiave a ciascuno di essi senza aggiungere un elemento contenitore.
10 -
11 -Ovvero, se hai un componente come il seguente:
12 -
13 -```js
14 -var Swapper = React.createClass({
15 - propTypes: {
16 - // `leftChildren` e `rightChildren` possono essere una stringa, un elemento, un array, etc.
17 - leftChildren: React.PropTypes.node,
18 - rightChildren: React.PropTypes.node,
19 -
20 - swapped: React.PropTypes.bool
21 - }
22 - render: function() {
23 - var children;
24 - if (this.props.swapped) {
25 - children = [this.props.rightChildren, this.props.leftChildren];
26 - } else {
27 - children = [this.props.leftChildren, this.props.rightChildren];
28 - }
29 - return <div>{children}</div>;
30 - }
31 -});
32 -```
33 -
34 -I figli saranno smontati e rimontati nel momento in cui cambi la proprietà `swapped` poiché non ci sono chiavi che marcano i due insiemi di figli.
35 -
36 -Per risolvere questo problema, puoi utilizzare `React.addons.createFragment` per dare una chiave a ciascun insieme di figli.
37 -
38 -#### `ReactFragment React.addons.createFragment(object children)`
39 -
40 -Anziché creare array, scriviamo:
41 -
42 -```js
43 -if (this.props.swapped) {
44 - children = React.addons.createFragment({
45 - right: this.props.rightChildren,
46 - left: this.props.leftChildren
47 - });
48 -} else {
49 - children = React.addons.createFragment({
50 - left: this.props.leftChildren,
51 - right: this.props.rightChildren
52 - });
53 -}
54 -```
55 -
56 -Le chiavi degli oggetti passati (ovvero, `left` e `right`) sono usate come chiavi per l'intero insieme di figli, e l'ordine delle chiavi dell'oggetto è utilizzato per determinare l'ordine dei figli visualizzati. Con questo cambiamento, i due insiemi di figli saranno correttamente riordinati nel DOM senza bisogno di smontaggio.
57 -
58 -Il valore di ritorno di `createFragment` deve essere trattato come un oggetto opaco; puoi usare gli helper `React.Children` per iterare su un frammento ma non dovresti accedervi direttamente. Nota anche che ci stiamo affidando al motore JavaScript per preservare l'ordine dell'enumerazione degli oggetti, che non viene garantito dalla specifica ma è implementato dai principali browser e macchine virtuali per oggetti con chiavi non numeriche.
59 -
60 -> **Nota:**
61 ->
62 -> In un futuro, `createFragment` potrebbe essere sostituito da una API quale
63 ->
64 -> ```js
65 -> return (
66 -> <div>
67 -> <x:frag key="right">{this.props.rightChildren}</x:frag>,
68 -> <x:frag key="left">{this.props.leftChildren}</x:frag>
69 -> </div>
70 -> );
71 -> ```
72 ->
73 -> che ti permette di assegnare chiavi direttamente in JSX senza aggiungere elementi contenitore.
docs/docs/10.6-create-fragment.ja-JP.md deleted
-72
@@ -1,72 +0,0 @@
1 ----
2 -id: create-fragment
3 -title: キー付けされたフラグメント
4 -permalink: docs/create-fragment-ja-JP.html
5 -prev: clone-with-props-ja-JP.html
6 -next: update-ja-JP.html
7 ----
8 -
9 -多くの場合、 `render` から返された要素のキーを特定するために、 `key` プロパティを使用します。しかし、以下のような特定の状況では、こういったことを行うことはできません。何度も並び替える必要のある2つの子要素を持っているときには、ラッパーの要素を加える以外にそれぞれのセットのキーを追加する方法はありません。
10 -
11 -これは、以下のようなコンポーネントがある場合には、
12 -
13 -```js
14 -var Swapper = React.createClass({
15 - propTypes: {
16 - // `leftChildren` と `rightChildren` は文字列や、要素や、配列などになり得ます。
17 - leftChildren: React.PropTypes.node,
18 - rightChildren: React.PropTypes.node,
19 -
20 - swapped: React.PropTypes.bool
21 - }
22 - render: function() {
23 - var children;
24 - if (this.props.swapped) {
25 - children = [this.props.rightChildren, this.props.leftChildren];
26 - } else {
27 - children = [this.props.leftChildren, this.props.rightChildren];
28 - }
29 - return <div>{children}</div>;
30 - }
31 -});
32 -```
33 -
34 -2つの子要素のセットを表すキーがないため、 `swapped` プロパティを変更するたびに子要素はアンマウントされ、再度マウントされます。
35 -
36 -この問題を解決するために、子要素のセットのキーを与える `React.addons.createFragment` を使用することができます。
37 -
38 -#### `ReactFragment React.addons.createFragment(object children)`
39 -
40 -配列を作成する代わりに、以下のように記述することができます。
41 -
42 -```js
43 -if (this.props.swapped) {
44 - children = React.addons.createFragment({
45 - right: this.props.rightChildren,
46 - left: this.props.leftChildren
47 - });
48 -} else {
49 - children = React.addons.createFragment({
50 - left: this.props.leftChildren,
51 - right: this.props.rightChildren
52 - });
53 -}
54 -```
55 -
56 -渡されたオブジェクトのキー(`left` や `right` のことです)は子要素のセット全体のキーとして使用され、そのオブジェクトのキーの順序はレンダリングされた子要素の順序を決める際に使用されます。この変更により、2つの子要素のセットはアンマウントされることなく、DOMの中で適切に順序立てられます。
57 -
58 -`createFragment` の戻り値は、不透明なオブジェクトとして扱われるべきです。つまり、 `React.Children` ヘルパーを、フラグメントのなかでループするために使用することはできますが、直接アクセスするべきではないということです。私たちはいまオブジェクトの一覧における順序を保存するのにJavaScriptのエンジンに頼っていることに注意してください。それは、仕様が保証されているわけではありませんが、数に関するものではないキーとオブジェクトは全てのメジャーなブラウザやVMで実行されます。
59 -
60 -> **注意:**
61 -> 将来、 `createFragment` は以下のようなAPIに変わるでしょう。
62 ->
63 -> ```js
64 -> return (
65 -> <div>
66 -> <x:frag key="right">{this.props.rightChildren}</x:frag>,
67 -> <x:frag key="left">{this.props.leftChildren}</x:frag>
68 -> </div>
69 -> );
70 -> ```
71 ->
72 -> ラッパーの要素を加えることなく、JSXの中に直接キーをアサインすることができます。
docs/docs/10.6-create-fragment.ko-KR.md deleted
-75
@@ -1,75 +0,0 @@
1 ----
2 -id: create-fragment-ko-KR
3 -title: 키가 할당된 프래그먼트
4 -permalink: docs/create-fragment-ko-KR.html
5 -prev: clone-with-props-ko-KR.html
6 -next: update-ko-KR.html
7 ----
8 -
9 -대부분의 경우는 `key` prop으로 `render`에서 반환된 엘리먼트에 키를 명시할 수 있습니다. 하지만 말썽을 부리는 경우가 한가지 있습니다: 재정렬을 할 두개의 자식 집합을 가지고 있는 경우, 감싸는 엘리먼트 없이 각각의 집합에 키를 부여하는 것은 불가능 합니다.
10 -
11 -이 말은, 만약 다음과 같은 컴포넌트가 있다면:
12 -
13 -```js
14 -var Swapper = React.createClass({
15 - propTypes: {
16 - // `leftChildren`과 `rightChildren`은 문자열, 엘리먼트, 배열 혹은 다른 무언가 일 수 있음.
17 - leftChildren: React.PropTypes.node,
18 - rightChildren: React.PropTypes.node,
19 -
20 - swapped: React.PropTypes.bool
21 - },
22 - render: function() {
23 - var children;
24 - if (this.props.swapped) {
25 - children = [this.props.rightChildren, this.props.leftChildren];
26 - } else {
27 - children = [this.props.leftChildren, this.props.rightChildren];
28 - }
29 - return <div>{children}</div>;
30 - }
31 -});
32 -```
33 -
34 -`swapped` prop을 변경할 경우 자식은 마운트 해제되거나 다시 마운트 될 수 있습니다. 두 자식 집합에 키가 할당되지 않았기 때문입니다.
35 -
36 -이 문제를 해결하기 위해서 `createFragment`를 사용해 자식 집합에 키를 부여할 수 있습니다.
37 -
38 -#### `Array<ReactNode> createFragment(object children)`
39 -
40 -배열을 만드는 대신에 다음과 같이 해볼 수 있습니다:
41 -
42 -```js
43 -var createFragment = require('react-addons-create-fragment');
44 -
45 -if (this.props.swapped) {
46 - children = createFragment({
47 - right: this.props.rightChildren,
48 - left: this.props.leftChildren
49 - });
50 -} else {
51 - children = createFragment({
52 - left: this.props.leftChildren,
53 - right: this.props.rightChildren
54 - });
55 -}
56 -```
57 -
58 -전달된 객체의 키(`left`, `right`)는 모든 자식 집합의 키로 사용됩니다. 그리고 객체에서 키들의 순서는 렌더된 자식들의 순서를 결정하는데 사용됩니다. 이러한 변경으로 두 자식 집합은 언마운팅하지 않고도 DOM에서 적절하게 재정렬 됩니다.
59 -
60 -`createFragment`의 반환값은 불명확한 객체로 취급되어야 합니다; `React.Children` 헬퍼를 사용해 프래그먼트를 순환할 수 있지만 직접 접근해서는 안됩니다. 명세에는 없지만 모든 주요 브라우저와 VM들에서 JavaScript 엔진이 숫자가 아닌 키에 대해서도 객체 목록 순서를 보존한다는 점을 주의하세요.
61 -
62 -> **주의:**
63 ->
64 -> 미래에 `createFragment`는 대략 다음과 같은 API로 교체될 것입니다
65 ->
66 -> ```js
67 -> return (
68 -> <div>
69 -> <x:frag key="right">{this.props.rightChildren}</x:frag>,
70 -> <x:frag key="left">{this.props.leftChildren}</x:frag>
71 -> </div>
72 -> );
73 -> ```
74 ->
75 -> JSX에서 엘리먼트로 감싸지 않고도 key를 바로 선언할 수 있게 될 것입니다.
docs/docs/10.6-create-fragment.zh-CN.md deleted
-75
@@ -1,75 +0,0 @@
1 ----
2 -id: create-fragment-zh-CN
3 -title: Keyed Fragments
4 -permalink: docs/create-fragment-zh-CN.html
5 -prev: clone-with-props-zh-CN.html
6 -next: update-zh-CN.html
7 ----
8 -
9 -在大多数情况下,你可以使用 `key` prop 指定你从 `render` 返回的元素的 keys。然而,这在一个情况下会失败:如果你有两组你需要记录的子级,将没有办法在不使用包裹元素的情况下放置一个 key 到每组上。
10 -
11 -即是,如果你有一个像这样的组件:
12 -
13 -```js
14 -var Swapper = React.createClass({
15 - propTypes: {
16 - // `leftChildren` and `rightChildren` can be a string, element, array, etc.
17 - leftChildren: React.PropTypes.node,
18 - rightChildren: React.PropTypes.node,
19 -
20 - swapped: React.PropTypes.bool
21 - },
22 - render: function() {
23 - var children;
24 - if (this.props.swapped) {
25 - children = [this.props.rightChildren, this.props.leftChildren];
26 - } else {
27 - children = [this.props.leftChildren, this.props.rightChildren];
28 - }
29 - return <div>{children}</div>;
30 - }
31 -});
32 -```
33 -
34 -这些子级会在当你改变 `swapped` prop 时加载和卸载,因为没有任何的 key 标记在这两组子级上。
35 -
36 -要解决这个问题,你可以使用 `createFragment` 插件来给予这两组子级 keys.
37 -
38 -#### `Array<ReactNode> createFragment(object children)`
39 -
40 -代替创建数组,我们这样写:
41 -
42 -```js
43 -var createFragment = require('react-addons-create-fragment');
44 -
45 -if (this.props.swapped) {
46 - children = createFragment({
47 - right: this.props.rightChildren,
48 - left: this.props.leftChildren
49 - });
50 -} else {
51 - children = createFragment({
52 - left: this.props.leftChildren,
53 - right: this.props.rightChildren
54 - });
55 -}
56 -```
57 -
58 -被传入对象的 keys (即 `left` 和 `right`)被用作为整组子级的 keys,并且对象 keys 的顺序被用于决定渲染子级的顺序。通过这个改变,这两个子级将会恰当的在 DOM 里排序,而不被卸载。
59 -
60 -`createFragment` 的返回值应该被对待为一个不透明的对象;你可以使用 `React.Children` 来遍历一个 fragment 但是不应该直接访问它。同样注意,我们依赖于 JavaScript 引擎保留了对象的枚举顺序,这点在 spec 上是不保证的,但是所有主要的浏览器和 VMs 都对非数字键的对象实现了这个特性。
61 -
62 -> **注意:**
63 ->
64 -> 将来,`createFragment` 也许会被替换为如下的API:
65 ->
66 -> ```js
67 -> return (
68 -> <div>
69 -> <x:frag key="right">{this.props.rightChildren}</x:frag>,
70 -> <x:frag key="left">{this.props.leftChildren}</x:frag>
71 -> </div>
72 -> );
73 -> ```
74 ->
75 -> 允许你直接在 JSX 里赋值 keys 而不用添加包裹元素。
docs/docs/10.7-update.it-IT.md deleted
-100
@@ -1,100 +0,0 @@
1 ----
2 -id: update-it-IT
3 -title: Helper per l'Immutabilità
4 -permalink: docs/update-it-IT.html
5 -prev: create-fragment-it-IT.html
6 -next: pure-render-mixin-it-IT.html
7 ----
8 -
9 -React ti permette di usare qualunque stile per la gestione dei dati che desideri, incluso la mutazione. Tuttavia, se puoi usare dati immutabili in parti critiche per le prestazioni della tua applicazione è facile implementare rapidamente un metodo `shouldComponentUpdate()` che aumenta significativamente la velocità della tua applicazione.
10 -
11 -Avere a che fare con dati immutabili in JavaScript è più difficile che in linguaggi progettati a tale scopo, come [Clojure](http://clojure.org/). Tuttavia, abbiamo fornito un semplice helper per l'immutabilità, `update()`, che rende avere a che fare con questo tipo di dati molto più semplice, *senza* cambiare fondamentalmente la rappresentazione dei tuoi dati. Se puoi anche dare un'occhiata alla libreria [Immutable-js](https://facebook.github.io/immutable-js/docs/) di Facebook e la sezione [Prestazioni Avanzate](/react/docs/advanced-performance.html) per maggiori dettagli su Immutable-js.
12 -
13 -## L'idea fondamentale
14 -
15 -Se muti i tuoi dati nella seguente maniera:
16 -
17 -```js
18 -myData.x.y.z = 7;
19 -// oppure...
20 -myData.a.b.push(9);
21 -```
22 -
23 -non hai modo di determinare quali dati siano cambiati dal momento che la copia precedente è stata sovrascritta. Invece, devi creare una nuova copia di `myData` e cambiare solo le parti che vanno cambiate. Allora puoi confrontare la vecchia copia di `myData` con la nuova in `shouldComponentUpdate()` usando l'operatore di uguaglianza stretta `===`:
24 -
25 -```js
26 -var newData = deepCopy(myData);
27 -newData.x.y.z = 7;
28 -newData.a.b.push(9);
29 -```
30 -
31 -Sfortunatamente, le copie profonde sono costose, e a volte impossibili. Puoi alleviare questa limitazione copiando soltanto gli oggetti che devono essere cambiati e riutilizzando gli oggetti che nonsono cambiati. Sfortunatamente, nel JavaScript odierno questa può essere un'operazione difficoltosa:
32 -
33 -```js
34 -var newData = extend(myData, {
35 - x: extend(myData.x, {
36 - y: extend(myData.x.y, {z: 7}),
37 - }),
38 - a: extend(myData.a, {b: myData.a.b.concat(9)})
39 -});
40 -```
41 -
42 -Mentre questo codice ha prestazioni accettabili (dal momento che effettua soltanto una copia superficiale di `log n` oggetti e riutilizza i rimanenti), è una gran scocciatura da scrivere. Guarda quanta ripetizione! Questo non è soltanto fastidioso, ma offre una grande superficie di attacco per i bachi.
43 -
44 -`update()` fornisce un semplice zucchero sintattico attorno a questo pattern per rendere più semplice la scrittura di questo codice. Questo codice diventa:
45 -
46 -```js
47 -var newData = React.addons.update(myData, {
48 - x: {y: {z: {$set: 7}}},
49 - a: {b: {$push: [9]}}
50 -});
51 -```
52 -
53 -Mentre la sintassi richiede qualche tempo per abituarsi (anche se è ispirata dal [linguaggio di query di MongoDB](http://docs.mongodb.org/manual/core/crud-introduction/#query)) non c'è ridondanza, può essere analizzato staticamente e non richiede la scrittura di più codice della versione mutativa.
54 -
55 -Le chiavi con il prefisso `$` sono chiamate *comandi*. La struttura dati che stanno "mutando" viene chiamata *bersaglio*.
56 -
57 -## Comandi disponibili
58 -
59 - * `{$push: array}` invoca `push()` sul bersagio passando ciascun elemento di `array`.
60 - * `{$unshift: array}` invoca `unshift()` sul bersagio passando ciascun elemento di `array`.
61 - * `{$splice: array of arrays}` per ogni elemento di `arrays` invoca `splice()` sul bersaglio con i parametri forniti dall'elemento.
62 - * `{$set: any}` sostituisce l'intero bersaglio.
63 - * `{$merge: object}` unisce le chiavi di `object` con il bersaglio.
64 - * `{$apply: function}` passa il valore attuale alla funzione e lo aggiorna con il nuovo valore da essa restituito.
65 -
66 -## Esempi
67 -
68 -### Semplice inserimento in coda
69 -
70 -```js
71 -var initialArray = [1, 2, 3];
72 -var newArray = update(initialArray, {$push: [4]}); // => [1, 2, 3, 4]
73 -```
74 -`initialArray` is still `[1, 2, 3]`.
75 -
76 -### Collezioni annidate
77 -
78 -```js
79 -var collection = [1, 2, {a: [12, 17, 15]}];
80 -var newCollection = update(collection, {2: {a: {$splice: [[1, 1, 13, 14]]}}});
81 -// => [1, 2, {a: [12, 13, 14, 15]}]
82 -```
83 -Questo accede all'indice `2` di `collection`, alla chiave `a`, ed effettua lo splice di un elemento a partire dall'indice `1` (per rimuovere `17`) e al contempo inserisce `13` e `14`.
84 -
85 -### Aggiornare un valore basandosi sul suo valore attuale
86 -
87 -```js
88 -var obj = {a: 5, b: 3};
89 -var newObj = update(obj, {b: {$apply: function(x) {return x * 2;}}});
90 -// => {a: 5, b: 6}
91 -// Questa è una forma equivalente, ma diventa prolissa per profonde collezioni annidate:
92 -var newObj2 = update(obj, {b: {$set: obj.b * 2}});
93 -```
94 -
95 -### Unione (superficiale)
96 -
97 -```js
98 -var obj = {a: 5, b: 3};
99 -var newObj = update(obj, {$merge: {b: 6, c: 7}}); // => {a: 5, b: 6, c: 7}
100 -```
docs/docs/10.7-update.ja-JP.md deleted
-101
@@ -1,101 +0,0 @@
1 ----
2 -id: update
3 -title: 不変性のヘルパ
4 -permalink: docs/update-ja-JP.html
5 -prev: create-fragment-ja-JP.html
6 -next: pure-render-mixin-ja-JP.html
7 ----
8 -
9 -Reactは変化を含む、使用したいデータマネジメントのスタイルであればどういったものであっても使用することができます。しかし、アプリケーションの、パフォーマンスが重要な部分において不変なデータを使用できる場合は、速い `shouldComponentUpdate()` メソッドを実行して、簡単にアプリケーションのスピードを著しく速くすることができます。
10 -
11 -[Clojure](http://clojure.org/)のような、不変なデータの扱いのためにデザインされた言語よりも、JavaScriptでそれを行うことは難しいです。しかし、単純な不変性のヘルパである、 `update()` が提供されています。それは、データがどのように表されるかということを基本的には変更すること *なく* データのタイプを扱うことを簡単にします。Immutable-jsについての詳細は、Facebookの[Immutable-js](https://facebook.github.io/immutable-js/docs/#/)や[進歩したパフォーマンス](/react/docs/advanced-performance.html)をご覧ください。
12 -
13 -## 主要な考え
14 -
15 -もし変更する予定のデータが以下のようなものであれば、
16 -
17 -```js
18 -myData.x.y.z = 7;
19 -// または...
20 -myData.a.b.push(9);
21 -```
22 -
23 -以前のコピーが上書きされるので、どのデータが変更されたか判断する方法はありません。代わりに、 `myData` の新しいコピーを作成する必要があり、変更される必要がある部分のみを変更します。それから、 `myData` の古いコピーと新しいコピーを `shouldComponentUpdate()` の中で以下のように、3つのイコールを使用して比較することができます。
24 -
25 -```js
26 -var newData = deepCopy(myData);
27 -newData.x.y.z = 7;
28 -newData.a.b.push(9);
29 -```
30 -
31 -不幸なことに、ディープコピーはコストがかかり、不可能なときもあります。変更される必要があるオブジェクトをコピーすることと、変更されていないオブジェクトを再利用することによってのみ、これを代替することができます。不幸なことに、今日のJavaScriptでは、こういったことは面倒です。
32 -
33 -```js
34 -var newData = extend(myData, {
35 - x: extend(myData.x, {
36 - y: extend(myData.x.y, {z: 7}),
37 - }),
38 - a: extend(myData.a, {b: myData.a.b.concat(9)})
39 -});
40 -```
41 -
42 -動きが速い一方で( `log n` オブジェクトのシャローコピーを作成し、残りを再利用するため)、記述するのには多くのコストがかかります。全てのコードの繰り返しを見てください。それらはつまらないものではなく、多くのバグの表面を提供します。
43 -
44 -`update()` はこのようなパターンにおいて、コードを簡単に記述するための単純な糖衣構文を提供します。そのコードは以下のようになります。
45 -
46 -```js
47 -var newData = React.addons.update(myData, {
48 - x: {y: {z: {$set: 7}}},
49 - a: {b: {$push: [9]}}
50 -});
51 -```
52 -
53 -シンタックスは少し慣れが必要ですが([MongoDBのクエリ言語](http://docs.mongodb.org/manual/core/crud-introduction/#query)にインスパイアされているため)、冗長性はありません。静的に分析し、変更ができるバージョンと比べてタイプする量がすごく増えているわけではありません。
54 -
55 -`$` から始まるキーは *コマンド* と呼ばれます。それらが「変更する」データ構造は *ターゲット* と呼ばれます。
56 -
57 -## 使用できるコマンド
58 -
59 - * `{$push: array}` ターゲットに `array` の全ての要素を `push()` します。
60 - * `{$unshift: array}` ターゲットの `array` の全ての要素を `unshift()` します。
61 - * `{$splice: array of arrays}` `arrays` の全ての要素について、その要素によって提供されるパラメータのターゲットにおいて、 `splice()` を呼び出します。
62 - * `{$set: any}` ターゲットを完全に置き換えます。
63 - * `{$merge: object}` `object` のキーをターゲットとマージします。
64 - * `{$apply: function}` 現在の値を関数に渡し、返された新しい値によってそれを更新します。
65 -
66 -## 例
67 -
68 -### 単純なプッシュ
69 -
70 -```js
71 -var initialArray = [1, 2, 3];
72 -var newArray = update(initialArray, {$push: [4]}); // => [1, 2, 3, 4]
73 -```
74 -`initialArray` は `[1, 2, 3]` のままです。
75 -
76 -### ネストしたコレクション
77 -
78 -```js
79 -var collection = [1, 2, {a: [12, 17, 15]}];
80 -var newCollection = update(collection, {2: {a: {$splice: [[1, 1, 13, 14]]}}});
81 -// => [1, 2, {a: [12, 13, 14, 15]}]
82 -```
83 -
84 -これは、 `collection` のインデックスが `2` である要素にアクセスし、インデックスが `1` である要素に( `17` を削除し)`13` と `14` を挿入することで繋ぎ合わせます。
85 -
86 -### 現在の値に基づいて値を更新すること
87 -
88 -```js
89 -var obj = {a: 5, b: 3};
90 -var newObj = update(obj, {b: {$apply: function(x) {return x * 2;}}});
91 -// => {a: 5, b: 6}
92 -// 以下は上と同義ですが、ネストが深いコレクションにとっては冗長になります。
93 -var newObj2 = update(obj, {b: {$set: obj.b * 2}});
94 -```
95 -
96 -### (シャロー)マージ
97 -
98 -```js
99 -var obj = {a: 5, b: 3};
100 -var newObj = update(obj, {$merge: {b: 6, c: 7}}); // => {a: 5, b: 6, c: 7}
101 -```
docs/docs/10.7-update.ko-KR.md deleted
-103
@@ -1,103 +0,0 @@
1 ----
2 -id: update-ko-KR
3 -title: 불변성 헬퍼들
4 -permalink: docs/update-ko-KR.html
5 -prev: create-fragment-ko-KR.html
6 -next: pure-render-mixin-ko-KR.html
7 ----
8 -
9 -React에서는 mutation을 포함해 어떤 데이터 관리 방식도 사용하실 수 있습니다. 하지만 애플리케이션의 성능이 중요한 부분에서 불변의(immutable) 데이터를 사용할 수 있다면, 쉽게 빠른 `shouldComponentUpdate()` 메소드를 구현해 애플리케이션의 속도를 크게 향상시킬 수 있습니다.
10 -
11 -JavaScript에서 불변성의 데이터를 다루는 것은 [Clojure](http://clojure.org/)같이 그것을 위해 디자인된 언어로 다루는 것보다는 어렵습니다. 하지만, React는 간단한 불변성 헬퍼를 제공합니다. `update()`는 이런 종류의 데이터를 근본적인 변화 *없이* 쉽게 다루도록 해줍니다. Immutable-js에 관한 좀 더 자세한 정보는 페이스북의 [Immutable-js](https://facebook.github.io/immutable-js/docs/)나 [성능 심화](/react/docs/advanced-performance-ko-KR.html)을 참조하세요.
12 -
13 -## 주요 아이디어
14 -
15 -만약 데이터를 이렇게 변화시킨다면:
16 -
17 -```js
18 -myData.x.y.z = 7;
19 -// or...
20 -myData.a.b.push(9);
21 -```
22 -
23 -이전의 카피가 덮어씌워진다면 어떤 자료가 바뀌었는지 알 방도가 없습니다. 대신에, `myData`의 새로운 카피를 만들고 오직 변화가 필요한 부분만 바꿀 필요가 있습니다. 그 다음 `shouldComponentUpdate()` 에서 `myData`의 이전 카피와 새로운 카피를 `===` 연산자를 사용하여 비교할 수 있습니다.
24 -
25 -```js
26 -var newData = deepCopy(myData);
27 -newData.x.y.z = 7;
28 -newData.a.b.push(9);
29 -```
30 -
31 -하지만 깊은 복사는 비싸고, 가끔은 불가능하기도 합니다. 변화가 필요한 객체만 복제하고, 변화가 없는 객체는 다시 사용하는 방법으로만 비용을 줄일 수 있습니다. 안타깝지만 오늘날의 JavaScript에서는 그 방법이 성가실 수 있습니다:
32 -
33 -```js
34 -var newData = extend(myData, {
35 - x: extend(myData.x, {
36 - y: extend(myData.x.y, {z: 7}),
37 - }),
38 - a: extend(myData.a, {b: myData.a.b.concat(9)})
39 -});
40 -```
41 -
42 -이것은 꽤 성능이 좋긴 하지만 (`log n`개의 객체만 얕은 복사하고, 나머지는 재사용하기 때문에), 일일히 쓰기엔 큰 고통이 따릅니다. 이 반복들을 보세요! 이건 짜증날 뿐만 아니라 버그들을 야기할수도 있습니다.
43 -
44 -`update()`는 이런 패턴 속에서 코드를 더 쉽게 쓸 수 있도록 편의 문법을 제공합니다. 코드는 이렇습니다:
45 -
46 -```js
47 -var update = require('react-addons-update');
48 -
49 -var newData = update(myData, {
50 - x: {y: {z: {$set: 7}}},
51 - a: {b: {$push: [9]}}
52 -});
53 -```
54 -
55 -([MongoDB 쿼리 언어](http://docs.mongodb.org/manual/core/crud-introduction/#query)에서 영감을 받은) 이 문법에 익숙해지기에는 시간이 조금 걸리긴 하지만, 쓸모 없는 반복이 없고 정적분석이 가능할 뿐더러 변할 수 있는(mutative) 버전보다 더 많은 타이핑이 필요하지도 않습니다.
56 -
57 -
58 -`$`가 앞에 붙어있는 키들은 *커맨드* 라고 불립니다. "변하는" 자료 구조는 *타겟* 이라고 불립니다.
59 -
60 -## 사용가능한 커맨드들
61 -
62 - * `{$push: array}` 모든 아이템들을 타겟에 있는 `array`에 `push()`합니다.
63 - * `{$unshift: array}` 타겟속 `array`에 있는 모든 아이템들을 `unshift()`합니다.
64 - * `{$splice: array of arrays}` `arrays` 안의 각 아이템들이 `splice()`를 주어진 인자들을 사용해 호출하게 합니다.
65 - * `{$set: any}` 타겟 전체를 대체합니다.
66 - * `{$merge: object}` 타겟과 `object`의 키들을 병합합니다.
67 - * `{$apply: function}` 는 지금 값을 함수에 전달하고 새로운 리턴 값으로 업데이트합니다.
68 -
69 -## 예제
70 -
71 -### 간단한 push
72 -
73 -```js
74 -var initialArray = [1, 2, 3];
75 -var newArray = update(initialArray, {$push: [4]}); // => [1, 2, 3, 4]
76 -```
77 -`initialArray` 은 여전히 `[1, 2, 3]` 입니다.
78 -
79 -### 중첩된 컬렉션
80 -
81 -```js
82 -var collection = [1, 2, {a: [12, 17, 15]}];
83 -var newCollection = update(collection, {2: {a: {$splice: [[1, 1, 13, 14]]}}});
84 -// => [1, 2, {a: [12, 13, 14, 15]}]
85 -```
86 -이것은 `collection`의 인덱스 `2`의 키 `a`에 접근해, 인덱스 `1`에 있는 한 아이템을 접합(splice)해서(`17`를 제거하고) `13`, `14`를 추가합니다.
87 -
88 -### 현재 상태에 의거해 값을 업데이트
89 -
90 -```js
91 -var obj = {a: 5, b: 3};
92 -var newObj = update(obj, {b: {$apply: function(x) {return x * 2;}}});
93 -// => {a: 5, b: 6}
94 -// 위의 것과 같은 동작을 합니다만, 깊게 중첩된 컬렉션들에서는 더 장황해 집니다.
95 -var newObj2 = update(obj, {b: {$set: obj.b * 2}});
96 -```
97 -
98 -### (얕은) 합병
99 -
100 -```js
101 -var obj = {a: 5, b: 3};
102 -var newObj = update(obj, {$merge: {b: 6, c: 7}}); // => {a: 5, b: 6, c: 7}
103 -```
docs/docs/10.7-update.zh-CN.md deleted
-102
@@ -1,102 +0,0 @@
1 ----
2 -id: update-zh-CN
3 -title: immutability 助手
4 -permalink: docs/update-zh-CN.html
5 -prev: create-fragment-zh-CN.html
6 -next: pure-render-mixin-zh-CN.html
7 ----
8 -
9 -React 让你可以使用任何你想要的数据管理方式,包括 mutation。然而,如果你可以在你的应用的性能关键性部分里使用 immutable 数据,将会易于实现一个快速的 `shouldComponentUpdate()` 方法来显著加速你的 app。
10 -
11 -在 JavaScript 里处理 immutable 数据比在为此设计的语言中要难的多,比如 [Clojure](http://clojure.org/)。然而,我们提供了一个简单的 immutability 助手,`update()`,它使处理这类数据容易多了,*不用* 根本性的改变你的数据的表达方式。你也同样可以看一看 Facebook 的 [Immutable-js](https://facebook.github.io/immutable-js/docs/) 和[Advanced Performance](/react/docs/advanced-performance.html) 了解更多关于 Immutable-js 的信息。
12 -
13 -## 主要的思路
14 -
15 -如果你像这样变动数据:
16 -
17 -```js
18 -myData.x.y.z = 7;
19 -// or...
20 -myData.a.b.push(9);
21 -```
22 -
23 -你将没有任何办法决定哪个数据被改变了,因为之前的拷贝已经被覆盖。作为替代,你需要创建一个新的 `myData` 的拷贝并且只修改需要改变的地方。然后你可以用三个等于在 `shouldComponentUpdate()` 里比较旧的 `myData` 拷贝与新的拷贝:
24 -
25 -```js
26 -var newData = deepCopy(myData);
27 -newData.x.y.z = 7;
28 -newData.a.b.push(9);
29 -```
30 -
31 -不幸的是,深拷贝很昂贵,并且有时候不可能。你可以通过仅仅拷贝需要被改变和重用没有改变的对象来缓解这个情况。不幸的是,在当今的 JavaScript 里这会很笨重:
32 -
33 -```js
34 -var newData = extend(myData, {
35 - x: extend(myData.x, {
36 - y: extend(myData.x.y, {z: 7}),
37 - }),
38 - a: extend(myData.a, {b: myData.a.b.concat(9)})
39 -});
40 -```
41 -
42 -虽然这相当高性能(因为只对 `log n` 的对象进行了浅拷贝并重用了剩下的),但它写起来很痛苦。看看所有重复的代码!这不仅仅是烦人的,同时也提供了一大片 bugs 区域。
43 -
44 -`update()` 提供了这个模式的简单语法糖来使写这类代码更容易。上面的代码变成:
45 -
46 -```js
47 -var update = require('react-addons-update');
48 -
49 -var newData = update(myData, {
50 - x: {y: {z: {$set: 7}}},
51 - a: {b: {$push: [9]}}
52 -});
53 -```
54 -
55 -虽然这个语法需要花一些时间来适应(它的灵感来自于 [MongoDB's query language](http://docs.mongodb.org/manual/core/crud-introduction/#query)),但是没有冗余,它可静态分析并且没有 mutative 版本那么多键入。
56 -
57 -`$`-前缀的 keys 被称为 *命令*。被 "变动的" 数据结构被称为 *目标*。
58 -
59 -## 有效的命令
60 -
61 - * `{$push: array}` 在目标上 `push()` 所有 `array` 里的项目。
62 - * `{$unshift: array}` 在目标上 `unshift()` 所有 `array` 里的项目。
63 - * `{$splice: array of arrays}` 在目标上对于每一个 `arrays` 里的项目使用项目提供的参数调用 `splice()`。
64 - * `{$set: any}` 整个替换目标.
65 - * `{$merge: object}` 合并 目标和 `object` 的 keys.
66 - * `{$apply: function}` 传递当前的值给 function 并用返回值更新它。
67 -
68 -## 例子
69 -
70 -### 简单的 push
71 -
72 -```js
73 -var initialArray = [1, 2, 3];
74 -var newArray = update(initialArray, {$push: [4]}); // => [1, 2, 3, 4]
75 -```
76 -`initialArray` is still `[1, 2, 3]`.
77 -
78 -### 嵌套的 collections
79 -
80 -```js
81 -var collection = [1, 2, {a: [12, 17, 15]}];
82 -var newCollection = update(collection, {2: {a: {$splice: [[1, 1, 13, 14]]}}});
83 -// => [1, 2, {a: [12, 13, 14, 15]}]
84 -```
85 -本例访问了 `collection` 的`2`索引下的键`a`,并且拼接了一个从索引`1`开始(移除`17`)并插入`13`和`14`的项目。
86 -
87 -### 基于当前的值更新新值
88 -
89 -```js
90 -var obj = {a: 5, b: 3};
91 -var newObj = update(obj, {b: {$apply: function(x) {return x * 2;}}});
92 -// => {a: 5, b: 6}
93 -// This is equivalent, but gets verbose for deeply nested collections:
94 -var newObj2 = update(obj, {b: {$set: obj.b * 2}});
95 -```
96 -
97 -### (浅) 合并
98 -
99 -```js
100 -var obj = {a: 5, b: 3};
101 -var newObj = update(obj, {$merge: {b: 6, c: 7}}); // => {a: 5, b: 6, c: 7}
102 -```
docs/docs/10.8-pure-render-mixin.it-IT.md deleted
-30
@@ -1,30 +0,0 @@
1 ----
2 -id: pure-render-mixin-it-IT
3 -title: PureRenderMixin
4 -permalink: docs/pure-render-mixin-it-IT.html
5 -prev: update-it-IT.html
6 -next: perf-it-IT.html
7 ----
8 -
9 -Se la funzione render del tuo componente React è "pura" (in altre parole, visualizza lo stesso risultato a partire dagli stessi proprietà e stato), puoi usare questo mixin per un incremento di prestazioni in alcuni casi.
10 -
11 -Esempio:
12 -
13 -```js
14 -var PureRenderMixin = require('react/addons').addons.PureRenderMixin;
15 -React.createClass({
16 - mixins: [PureRenderMixin],
17 -
18 - render: function() {
19 - return <div className={this.props.className}>foo</div>;
20 - }
21 -});
22 -```
23 -
24 -Dietro le quinte, il mixin implementa [shouldComponentUpdate](/react/docs/component-specs.html#updating-shouldcomponentupdate), nel quale confronta i valori attuali di `this.props` e `this.state` con i successivi e restituisce `false` se l'uguaglianza è verificata.
25 -
26 -> Nota:
27 ->
28 -> Questo confronto tra gli oggetti è soltanto superficiale. Se questi contengono strutture dati complesse, può causare dei falsi negativi per differenze in profondità. Effettua il mix in componenti la cui struttura di `this.props` e `this.state` sia semplice, oppure utilizza `forceUpdate()` quando si ha la certezza che le strutture dati siano cambiate in profondità. In alternativa, considera l'utilizzo di [oggetti immutabili](https://facebook.github.io/immutable-js/) per facilitare il confronto rapido di oggetti annidati.
29 ->
30 -> Inoltre, `shouldComponentUpdate` rimanda gli aggiornamenti per l'intero sotto albero di componenti. Assicurati che tutti i componenti figli siano anch'essi "puri".
docs/docs/10.8-pure-render-mixin.ja-JP.md deleted
-28
@@ -1,28 +0,0 @@
1 ----
2 -id: pure-render-mixin
3 -title: PureRenderMixin
4 -permalink: docs/pure-render-mixin-ja-JP.html
5 -prev: update-ja-JP.html
6 -next: perf-ja-JP.html
7 ----
8 -
9 -Reactコンポーネントのrender関数が「ピュア」である(言い換えると、同じpropsやstateが与えられた時に同じ結果をレンダリングする)場合は、いくつかのケースでパフォーマンスをあげるためにこのミックスインを使用することができます。
10 -
11 -例:
12 -
13 -```js
14 -var PureRenderMixin = require('react/addons').addons.PureRenderMixin;
15 -React.createClass({
16 - mixins: [PureRenderMixin],
17 -
18 - render: function() {
19 - return <div className={this.props.className}>foo</div>;
20 - }
21 -});
22 -```
23 -
24 -内部で、このミックスインは[shouldComponentUpdate](/react/docs/component-specs.html#updating-shouldcomponentupdate)を実行します。現在のpropsとstateを次のものと比較し、同様のものであれば、 `false` を返します。
25 -
26 -> 注意:
27 -> このミックスインはオブジェクトの比較のみを行います。それらが複雑なデータ構造を持っていた場合、深い位置における違いは見逃されることがあります。単純なpropsやstateをコンポーネントが持っている場合にのみ、使用してください。深いデータ構造が変更されることが分かっている場合は、 `forceUpdate()` を使用してください。または、ネストされたデータの比較を速く行うために[不変オブジェクト](https://facebook.github.io/immutable-js/)の使用を考えてみてください。
28 -> 更に、 `shouldComponentUpdate` は全てのコンポーネントのサブツリーのアップデートをスキップします。全ての子要素のコンポーネントもまた、「ピュア」であることを確認してください。
docs/docs/10.8-pure-render-mixin.ko-KR.md deleted
-30
@@ -1,30 +0,0 @@
1 ----
2 -id: pure-render-mixin-ko-KR
3 -title: PureRenderMixin
4 -permalink: docs/pure-render-mixin-ko-KR.html
5 -prev: update-ko-KR.html
6 -next: perf-ko-KR.html
7 ----
8 -
9 -React 컴포넌트의 렌더 함수가 "pure"하다면 (다른 말로, props나 state에 같은 값이 주어질 때 같은 결과를 렌더한다면) 몇몇 경우엔 이 믹스인을 사용하여 성능을 향상시킬 수 있습니다.
10 -
11 -예제:
12 -
13 -```js
14 -var PureRenderMixin = require('react-addons-pure-render-mixin');
15 -React.createClass({
16 - mixins: [PureRenderMixin],
17 -
18 - render: function() {
19 - return <div className={this.props.className}>foo</div>;
20 - }
21 -});
22 -```
23 -
24 -내부적으로 믹스인은 현재의 props와 state를 다음 값과 비교하여 같다면 `false`를 반환하도록 [shouldComponentUpdate](/react/docs/component-specs-ko-KR.html#업데이트-시-shouldcomponentupdate)를 구현합니다.
25 -
26 -> 주의:
27 ->
28 -> 여기서는 객체에 대한 얕은(shallow) 비교만 합니다. 복잡한 데이터 구조를 가진 경우에는 깊은 부분의 차이에 대해 잘못된 false를 반환 할 수도 있습니다. 간단한 props와 state를 사용하는 컴포넌트에만 적용하거나 깊은 데이터 구조가 변경 되었을때는 `forceUpdate()`를 사용하세요. 아니면 중첩 데이터의 비교를 빠르고 용이하게 하기 위해 [immutable 객체](https://facebook.github.io/immutable-js/)의 도입을 고려해보세요.
29 ->
30 -> 또, `shouldComponentUpdate`는 컴포넌트 서브트리의 업데이트를 건너뜁니다. 모든 자식 컴포넌트들도 "pure"한지 확인하세요.
docs/docs/10.8-pure-render-mixin.zh-CN.md deleted
-46
@@ -1,46 +0,0 @@
1 ----
2 -id: pure-render-mixin-zh-CN
3 -title: PureRenderMixin
4 -permalink: docs/pure-render-mixin-zh-CN.html
5 -prev: update-zh-CN.html
6 -next: perf-zh-CN.html
7 ----
8 -
9 -如果你的 React 组件的 render 函数是 "纯净" 的(换句话说,它的渲染在给定相同的 props 和 state 时返回相同的结果),你可以使用这个 mixin 在某些情况下进行性能加速。
10 -
11 -例子:
12 -
13 -```js
14 -var PureRenderMixin = require('react-addons-pure-render-mixin');
15 -React.createClass({
16 - mixins: [PureRenderMixin],
17 -
18 - render: function() {
19 - return <div className={this.props.className}>foo</div>;
20 - }
21 -});
22 -```
23 -
24 -使用 ES6 class 语法的例子:
25 -
26 -```js
27 -import PureRenderMixin from 'react-addons-pure-render-mixin';
28 -class FooComponent extends React.Component {
29 - constructor(props) {
30 - super(props);
31 - this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
32 - }
33 -
34 - render() {
35 - return <div className={this.props.className}>foo</div>;
36 - }
37 -}
38 -```
39 -
40 -在内部, mixin 实现了 [shouldComponentUpdate](/react/docs/component-specs.html#updating-shouldcomponentupdate), 它对当前及下一步的 props 和 state 进行比较,并当相等时返回 `false`。
41 -
42 -> 注意:
43 ->
44 -> 它仅仅浅比较对象。如果包含了复杂的对象,可能会对于深层的不同产生 false-negatives。只 mix 到那些含有简单 props 和 state 的组件,或者在你知道深层对象改变时使用 `forceUpdate()` 。或者,考虑使用[immutable objects](https://facebook.github.io/immutable-js/) 来促进快速的嵌套数据比较。
45 ->
46 -> 此外, `shouldComponentUpdate` 跳过了整个子树的更新。确保所有的子组件都是 "纯净" 的。
docs/docs/10.9-perf.it-IT.md deleted
-74
@@ -1,74 +0,0 @@
1 ----
2 -id: perf-it-IT
3 -title: Strumenti per la Performance
4 -permalink: docs/perf-it-IT.html
5 -prev: pure-render-mixin-it-IT.html
6 -next: advanced-performance-it-IT.html
7 ----
8 -
9 -React è solitamente assai veloce. Tuttavia, in situazioni nelle quali devi spremere fino all'ultima goccia di prestazioni dalla tua applicazione, fornisce un hook [shouldComponentUpdate](/react/docs/component-specs.html#updating-shouldcomponentupdate) nel quale puoi aggiungere controlli di ottimizzazione per l'algoritmo di confronto di React.
10 -
11 -Oltre a darti una panoramica sulle prestazioni generali della tua applicazione, ReactPerf è uno strumento di profilazione che ti dice esattamente dove è necessario aggiungere questi hook.
12 -
13 -> Nota:
14 ->
15 -> La build di sviluppo di React è più lenta della build di produzione, per via di tutta la logica aggiuntiva per fornire, ad esempio, gli avvisi amichevoli di React nella console (eliminati dalla build di produzione). Pertanto, il profilatore serve soltanto ad indicare le parti _relativamente_ costose della tua applicazione.
16 -
17 -## API Generale
18 -
19 -L'oggetto `Perf` documentato di seguito è esposto come `React.addons.Perf` quando si usa la build `react-with-addons.js` in modalità di sviluppo.
20 -
21 -### `Perf.start()` and `Perf.stop()`
22 -Avvia/interrompe la misurazione. Le operazioni React intermedie sono registrate per analisi in seguito. Le operazioni che hanno impiegato un tempo trascurabile vengono ignorate.
23 -
24 -Dopo l'interruzione, dovrai chiamare `Perf.getLastMeasurements()` (descritta in seguito) per ottenere le misurazioni.
25 -
26 -### `Perf.printInclusive(measurements)`
27 -Stampa il tempo complessivo impiegato. Se non vengono passati argomenti, stampa tutte le misurazioni dall'ultima registrazione. Stampa una tabella gradevolmente formattata nella console, come segue:
28 -
29 -![](/react/img/docs/perf-inclusive.png)
30 -
31 -### `Perf.printExclusive(measurements)`
32 -I tempi "esclusivi" non includono il tempo impiegato a montare i componenti: processare le proprietà, `getInitialState`, chiamare `componentWillMount` e `componentDidMount`, etc.
33 -
34 -![](/react/img/docs/perf-exclusive.png)
35 -
36 -### `Perf.printWasted(measurements)`
37 -
38 -**La parte più utile in assoluto del profilatore**.
39 -
40 -Il tempo "sprecato" è impiegato nei componenti che non hanno di fatto visualizzato nulla, ad es. il rendering è rimasto inalterato, quindi il DOM non è stato toccato.
41 -
42 -![](/react/img/docs/perf-wasted.png)
43 -
44 -### `Perf.printDOM(measurements)`
45 -Stampa le manipolazioni sottostanti del DOM, ad es. "imposta innerHTML" e "rimuovi".
46 -
47 -![](/react/img/docs/perf-dom.png)
48 -
49 -## API Avanzata
50 -
51 -I metodi di stampa precedenti utilizzano `Perf.getLastMeasurements()` per effettuare una gradevole stampa dei risultati.
52 -
53 -### `Perf.getLastMeasurements()`
54 -Ottieni l'array delle misurazioni dall'ultima sessione di avvio-interruzione. L'array contiene oggetti, ciascuno dei quali assomiglia a quanto segue:
55 -
56 -```js
57 -{
58 - // I termini "inclusive" ed "exclusive" sono spiegati in seguito
59 - "exclusive": {},
60 - // '.0.0' è l'identificativo React del nodo
61 - "inclusive": {".0.0": 0.0670000008540228, ".0": 0.3259999939473346},
62 - "render": {".0": 0.036999990697950125, ".0.0": 0.010000003385357559},
63 - // Numero di istanze
64 - "counts": {".0": 1, ".0.0": 1},
65 - // Scritture sul DOM
66 - "writes": {},
67 - // Informazioni aggiuntive per il debug
68 - "displayNames": {
69 - ".0": {"current": "App", "owner": "<root>"},
70 - ".0.0": {"current": "Box", "owner": "App"}
71 - },
72 - "totalTime": 0.48499999684281647
73 -}
74 -```
docs/docs/10.9-perf.ja-JP.md deleted
-73
@@ -1,73 +0,0 @@
1 ----
2 -id: perf
3 -title: パフォーマンスツール
4 -permalink: docs/perf-ja-JP.html
5 -prev: pure-render-mixin-ja-JP.html
6 -next: advanced-performance-ja-JP.html
7 ----
8 -
9 -Reactは普通、従来の枠を超えてとても速いです。しかし、アプリケーションにおいて、少しでもパフォーマンスを上げようという状況では、Reactの差分を取るアルゴリズムを最大限活用するヒントが得られる、[shouldComponentUpdate](/react/docs/component-specs.html#updating-shouldcomponentupdate)のフックを提供します。
10 -
11 -アプリケーション全体のパフォーマンスについての要約を得ることに加えて、ReactPerfはそれらのフックを実際にはどこに配置する必要があるか教えてくれるプロファイリングツールでもあります。
12 -
13 -> 注意:
14 -> Reactの開発版のビルドは与えられた外部ロジックのためにプロダクション版のビルドよりも遅くなります。例えば、Reactのフレンドリーコンソールの警告(プロダクション版のビルドにおいては警告が出ません)のように。それゆえ、プロファイラは *比較的* コストがかかっている箇所のみを指し示します。
15 -
16 -## 一般的なAPI
17 -
18 -ここに記述されている `Perf` オブジェクトは `react-with-addons.js` を開発版でビルドしたものを使用する際に `React.addons.Perf` として表されます。
19 -
20 -### `Perf.start()` と `Perf.stop()`
21 -測定の開始/終了です。その間のReactの操作は以下のような分析のために記録されます。あまり時間を使わない操作は無視されます。
22 -
23 -停止した後、あなたは、測定結果を得るために `Perf.getLastMeasurements()` (後述)が必要になります。
24 -
25 -### `Perf.printInclusive(measurements)`
26 -かかった全ての時間を出力します。引数が渡されなかった場合は、デフォルトで最後の測定から全ての測定が行われます。これは以下のように、コンソールに綺麗にフォーマットされたテーブルを出力します。
27 -
28 -![](/react/img/docs/perf-inclusive.png)
29 -
30 -### `Perf.printExclusive(measurements)`
31 -「占有」時間はコンポーネントをマウントするのにかかった時間を含みません。プロパティの処理、 `getInitialState` , `componentWillMount` や `componentDidMount` の呼び出しなどは含みます。
32 -
33 -![](/react/img/docs/perf-exclusive.png)
34 -
35 -### `Perf.printWasted(measurements)`
36 -
37 -**プロファイラの最も有用な箇所です**。
38 -
39 -「無駄な」時間はコンポーネントが実際には何もレンダリングしていないのにかかっている時間です。例えば、同じものをレンダリングしたので、DOMが触られなかったような場合です。
40 -
41 -![](/react/img/docs/perf-wasted.png)
42 -
43 -### `Perf.printDOM(measurements)`
44 -以下のような、DOMの操作を出力します。例えば、"set innerHTML"や"remove"といったものです。
45 -
46 -![](/react/img/docs/perf-dom.png)
47 -
48 -## 先進的なAPI
49 -
50 -上記の出力メソッドは結果をプリティプリントするのに `Perf.getLastMeasurements()` を使用しています。
51 -
52 -### `Perf.getLastMeasurements()`
53 -最後の開始と終了のセッションから測定の配列を取得します。配列は以下のようなオブジェクトを含みます。
54 -
55 -```js
56 -{
57 - // "inclusive"と"exclusive"の期間は以下で説明されています
58 - "exclusive": {},
59 - // '.0.0' はノードのReact ID
60 - "inclusive": {".0.0": 0.0670000008540228, ".0": 0.3259999939473346},
61 - "render": {".0": 0.036999990697950125, ".0.0": 0.010000003385357559},
62 - // インスタンスの数
63 - "counts": {".0": 1, ".0.0": 1},
64 - // 触ったDOM
65 - "writes": {},
66 - // 追加のデバッグ情報
67 - "displayNames": {
68 - ".0": {"current": "App", "owner": "<root>"},
69 - ".0.0": {"current": "Box", "owner": "App"}
70 - },
71 - "totalTime": 0.48499999684281647
72 -}
73 -```
docs/docs/10.9-perf.ko-KR.md deleted
-74
@@ -1,74 +0,0 @@
1 ----
2 -id: perf-ko-KR
3 -title: 성능 도구
4 -permalink: docs/perf-ko-KR.html
5 -prev: pure-render-mixin-ko-KR.html
6 -next: advanced-performance-ko-KR.html
7 ----
8 -
9 -React는 보통 처음에는 꽤 빠릅니다. 하지만 모든 성능을 짜내야 하는 상황일 때를 위해, React는 [shouldComponentUpdate](/react/docs/component-specs-ko-KR.html#업데이트-시-shouldcomponentupdate) 훅을 제공해 React의 diff 알고리즘을 위한 최적화 힌트를 추가할 수 있습니다.
10 -
11 -덧붙여 앱의 전반적인 성능의 개요도 제공합니다. ReactPerf는 프로파일링 도구로 정확히 어디에 훅이 필요한지 알려줍니다.
12 -
13 -> 주의:
14 ->
15 -> React의 개발 빌드는 제공되는 추가 기능으로 인해 프로덕션 빌드보다 느립니다. 추가 기능에는 React의 친절한 콘솔 경고같은 것이 있습니다.(이는 프로덕션 빌드에서는 제거 됩니다) 따라서, 프로파일러는 앱의 _상대적으로_ 비싼 부분만 표시하도록 합니다.
16 -
17 -## 일반 API
18 -
19 -여기에서 설명하는 `Perf` 객체는 `require('react-addons-perf')`로 노출되고 React 개발 모드에서만 사용할 수 있습니다. 이 번들을 프로덕션에서 앱과 같이 빌드하시면 안됩니다.
20 -
21 -### `Perf.start()`와 `Perf.stop()`
22 -측정을 시작/정지합니다. 그 사이의 React 연산은 밑에 있는 분석을 하기위해 기록됩니다. 미미한 양의 연산은 무시됩니다.
23 -
24 -종료 후, 측정을 하기위해서는 이후에 설명할 `Perf.getLastMeasurements()`가 필요합니다.
25 -
26 -### `Perf.printInclusive(measurements)`
27 -전 수행 시간을 출력합니다. 인자가 넘겨지지 않으면, 기본값은 지난 기록부터의 모든 측정이 됩니다. 이 출력은 밑에 있는 것처럼 콘솔에서 깔끔한 테이블로 그려집니다.
28 -
29 -![](/react/img/docs/perf-inclusive.png)
30 -
31 -### `Perf.printExclusive(measurements)`
32 -컴포넌트를 마운트하는 시간을 포함하지 않은 "exclusive" 시간입니다. 여기에는 props 연산, `getInitialState`, `componentWillMount` 호출, `componentDidMount`등이 포함됩니다.
33 -
34 -![](/react/img/docs/perf-exclusive.png)
35 -
36 -### `Perf.printWasted(measurements)`
37 -
38 -**프로파일러에서 가장 유용한 부분입니다**.
39 -
40 -렌더가 같아서, DOM을 변경(touch)하지 않는 경우같은 실제로는 아무것도 렌더하지 않는 컴포넌트가 사용하는 "낭비되는" 시간을 출력합니다.
41 -
42 -![](/react/img/docs/perf-wasted.png)
43 -
44 -### `Perf.printDOM(measurements)`
45 -"set innerHTML"이나 "remove"같은 기저의 DOM 조작을 출력합니다.
46 -
47 -![](/react/img/docs/perf-dom.png)
48 -
49 -## 고급 API
50 -
51 -위의 출력 메소드에 `Perf.getLastMeasurements()`를 사용해 결과를 이쁘게 출력합니다.
52 -
53 -### `Perf.getLastMeasurements()`
54 -마지막 start-stop 세션에서 측정들의 배열을 가져옵니다. 이 배열은 이런 객체들을 가지고 있습니다.
55 -
56 -```js
57 -{
58 - // 용어 "inclusive"와 "exclusive"는 위에서 설명했음
59 - "exclusive": {},
60 - // '.0.0'는 노드의 React ID
61 - "inclusive": {".0.0": 0.0670000008540228, ".0": 0.3259999939473346},
62 - "render": {".0": 0.036999990697950125, ".0.0": 0.010000003385357559},
63 - // 인스턴스의 수
64 - "counts": {".0": 1, ".0.0": 1},
65 - // DOM 변경(touch)
66 - "writes": {},
67 - // 추가 디버깅 정보
68 - "displayNames": {
69 - ".0": {"current": "App", "owner": "<root>"},
70 - ".0.0": {"current": "Box", "owner": "App"}
71 - },
72 - "totalTime": 0.48499999684281647
73 -}
74 -```
docs/docs/10.9-perf.md deleted
-64
@@ -1,64 +0,0 @@
1 ----
2 -id: perf
3 -title: Performance Tools
4 -permalink: docs/perf.html
5 -prev: pure-render-mixin.html
6 -next: shallow-compare.html
7 ----
8 -
9 -React is usually quite fast out of the box. However, in situations where you need to squeeze every ounce of performance out of your app, it provides a [shouldComponentUpdate](/react/docs/component-specs.html#updating-shouldcomponentupdate) hook where you can add optimization hints to React's diff algorithm.
10 -
11 -In addition to giving you an overview of your app's overall performance, ReactPerf is a profiling tool that tells you exactly where you need to put these hooks.
12 -
13 -See these two articles by the [Benchling Engineering Team](http://benchling.engineering) for a in-depth introduction to performance tooling: ["Performance Engineering with React"](http://benchling.engineering/performance-engineering-with-react/) and ["A Deep Dive into React Perf Debugging"](http://benchling.engineering/deep-dive-react-perf-debugging/)!
14 -
15 -## Development vs. Production Builds
16 -
17 -If you're benchmarking or seeing performance problems in your React apps, make sure you're testing with the [minified production build](/react/downloads.html). The development build includes extra warnings that are helpful when building your apps, but it is slower due to the extra bookkeeping it does.
18 -
19 -However, the perf tools described on this page only work when using the development build of React. Therefore, the profiler only serves to indicate the _relatively_ expensive parts of your app.
20 -
21 -## General API
22 -
23 -The `Perf` object documented here is exposed as `require('react-addons-perf')` and can be used with React in development mode only. You should not include this bundle when building your app for production.
24 -
25 -### `Perf.start()` and `Perf.stop()`
26 -Start/stop the measurement. The React operations in-between are recorded for analyses below. Operations that took an insignificant amount of time are ignored.
27 -
28 -After stopping, you will need `Perf.getLastMeasurements()` (described below) to get the measurements.
29 -
30 -### `Perf.printInclusive(measurements)`
31 -Prints the overall time taken. If no argument's passed, defaults to all the measurements from the last recording. This prints a nicely formatted table in the console, like so:
32 -
33 -![](/react/img/docs/perf-inclusive.png)
34 -
35 -### `Perf.printExclusive(measurements)`
36 -"Exclusive" times don't include the times taken to mount the components: processing props, `getInitialState`, call `componentWillMount` and `componentDidMount`, etc.
37 -
38 -![](/react/img/docs/perf-exclusive.png)
39 -
40 -### `Perf.printWasted(measurements)`
41 -
42 -**The most useful part of the profiler**.
43 -
44 -"Wasted" time is spent on components that didn't actually render anything, e.g. the render stayed the same, so the DOM wasn't touched.
45 -
46 -![](/react/img/docs/perf-wasted.png)
47 -
48 -### `Perf.printOperations(measurements)`
49 -Prints the underlying DOM manipulations, e.g. "set innerHTML" and "remove".
50 -
51 -![](/react/img/docs/perf-dom.png)
52 -
53 -### `Perf.printDOM(measurements)`
54 -
55 -This method has been renamed to `printOperations()` which is described in the previous paragraph. Currently `printDOM()` still exists as an alias but it prints a deprecation warning and will eventually be removed.
56 -
57 -## Advanced API
58 -
59 -The above print methods use `Perf.getLastMeasurements()` to pretty-print the result.
60 -
61 -### `Perf.getLastMeasurements()`
62 -Get the opaque data structure describing measurements from the last start-stop session. You can save it and pass it to the methods above to analyze past measurements.
63 -
64 -Don't rely on the exact format of the return value because it may change in minor releases. We will update the documentation if the return value format becomes a supported part of the public API.
docs/docs/10.9-perf.zh-CN.md deleted
-74
@@ -1,74 +0,0 @@
1 ----
2 -id: perf-zh-CN
3 -title: 性能工具
4 -permalink: docs/perf-zh-CN.html
5 -prev: pure-render-mixin-zh-CN.html
6 -next: shallow-compare-zh-CN.html
7 ----
8 -
9 -React 通常是相当快的。然而,在你需要压榨你的 app 的每一分性能的情况下,它提供了一个[shouldComponentUpdate](/react/docs/component-specs.html#updating-shouldcomponentupdate) 钩子,在此你可以添加优化提示到 React 的 diff 算法里。
10 -
11 -除了给予你一个你的 app 的整体性能概览外,ReactPerf 还是一个准确告诉你,你需要在哪里放置这些钩子的分析工具。
12 -
13 -## General API
14 -
15 -这里陈述的 `Perf` 对象被用 `require('react-addons-perf')` 暴露,并且只能被使用在 React 的开发模式。你不应在生产环境下在你的 app 包含这个包。
16 -
17 -> 注意:
18 ->
19 -> 开发版的 React 慢于生产版,因为所有额外提供的逻辑,例如,React 的友好的控制台警告 (在生产版中被除去)。因此,分析工具仅服务于指示你的 app _相对_ 昂贵的部分。
20 -
21 -### `Perf.start()` and `Perf.stop()`
22 -开始/停止测量。其间的React操作被记录用于之后的分析。产生无关紧要时间的操作被忽略。
23 -
24 -在停止以后,你将需要 `Perf.getLastMeasurements()` (下面将介绍)来获取测量结果。
25 -
26 -### `Perf.printInclusive(measurements)`
27 -打印总体花费的时间。如果没有传入参数,默认是从上次记录的所有测量数据。它在控制台里打印良好格式化的结果,像这样:
28 -
29 -![](/react/img/docs/perf-inclusive.png)
30 -
31 -### `Perf.printExclusive(measurements)`
32 -"独占的"时间不包括花费于加载组件的时间: 处理 props, `getInitialState`, 调用 `componentWillMount` 及 `componentDidMount`, 等等。
33 -
34 -![](/react/img/docs/perf-exclusive.png)
35 -
36 -### `Perf.printWasted(measurements)`
37 -
38 -**分析工具里最有用的部分**.
39 -
40 -"垃圾"时间是花费在组件上实际没有绘制任何东西的时间,例如渲染结果总是相同,所以 DOM 没有被触碰到。
41 -
42 -![](/react/img/docs/perf-wasted.png)
43 -
44 -### `Perf.printDOM(measurements)`
45 -打印底层的 DOM 操纵,例如 "set innerHTML" 和 "remove".
46 -
47 -![](/react/img/docs/perf-dom.png)
48 -
49 -## Advanced API
50 -
51 -以上的打印方法使用 `Perf.getLastMeasurements()` 来美观的打印结果。
52 -
53 -### `Perf.getLastMeasurements()`
54 -从最后的 start-stop 会话获取测量数据数据。这个数组包含对象,每个看起来像这样:
55 -
56 -```js
57 -{
58 - // The term "inclusive" and "exclusive" are explained below
59 - "exclusive": {},
60 - // '.0.0' is the React ID of the node
61 - "inclusive": {".0.0": 0.0670000008540228, ".0": 0.3259999939473346},
62 - "render": {".0": 0.036999990697950125, ".0.0": 0.010000003385357559},
63 - // Number of instances
64 - "counts": {".0": 1, ".0.0": 1},
65 - // DOM touches
66 - "writes": {},
67 - // Extra debugging info
68 - "displayNames": {
69 - ".0": {"current": "App", "owner": "<root>"},
70 - ".0.0": {"current": "Box", "owner": "App"}
71 - },
72 - "totalTime": 0.48499999684281647
73 -}
74 -```
docs/docs/11-advanced-performance.it-IT.md deleted
-207
@@ -1,207 +0,0 @@
1 ----
2 -id: advanced-performance-it-IT
3 -title: Performance Avanzata
4 -permalink: docs/advanced-performance-it-IT.html
5 -prev: perf-it-IT.html
6 ----
7 -
8 -Una tra le prime domande che la gente si pone quando considera React per un progetto è se l'applicazione sarà altrettanto veloce e scattante di una versione equivalente non basata su React. L'idea di ripetere il rendering di un intero sottoalbero di componenti in risposta a ciascun cambiamento dello stato rende la gente curiosa se questo processo influisce negativamente sulle prestazioni. React utilizza diverse tecniche intelligenti per minimizzare il numero di operazioni costose sul DOM richieste dall'aggiornamento della UI.
9 -
10 -## Evitare di riconciliare il DOM
11 -
12 -React fa uso di un *DOM virtuale*, che è un descrittore di un sottoalbero DOM visualizzato nel browser. Questa rappresentazione parallela permette a React di evitare di creare nodi DOM e accedere nodi esistenti, che è di gran lunga più lento di operazioni su oggetti JavaScript. Quando le proprietà di un componente o il suo stato cambiano, React decide se un'aggiornamento effettivo del DOM sia necessario costruendo un nuovo virtual DOM e confrontandolo con quello vecchio. Solo nel caso in cui non siano uguali, React [riconcilierà](/react/docs/reconciliation.html) il DOM, applicando il minor numero di mutamenti possibile.
13 -
14 -In aggiunta a questo, React offre una funzione per il ciclo di vita del componente, `shouldComponentUpdate`, che viene scatenata prima che il processo di ri-rendering cominci (il confronto del DOM virtuale e una possibile eventuale riconciliazione del DOM), dando allo sviluppatore la possibilità di cortocircuitare questo processo. L'implementazione predefinita di questa funzione restituisce `true`, lasciando che React effettui l'aggiornamento:
15 -
16 -```javascript
17 -shouldComponentUpdate: function(nextProps, nextState) {
18 - return true;
19 -}
20 -```
21 -
22 -Tieni in mente che React invocherà questa funzione abbastanza spesso, quindi l'implementazione deve essere veloce.
23 -
24 -Supponiamo che hai un'applicazione di messaggistica con parecchi thread di conversazioni. Supponi che solo uno dei thread sia cambiato. Se implementassimo `shouldComponentUpdate` sul componente `ChatThread`, React potrebbe saltare la fase di rendering per gli altri thread:
25 -
26 -```javascript
27 -shouldComponentUpdate: function(nextProps, nextState) {
28 - // TODO: restituisci true se il thread attuale è diverso
29 - // da quello precedente.
30 -}
31 -```
32 -
33 -Quindi, riassumendo, React evita di effettuare operazioni costose sul DOM richieste a riconciliare sottoalberi del DOM, permettendo all'utente di cortocircuitare il processo usando `shouldComponentUpdate`, e, per i casi in cui si debba aggiornare, confrontando i DOM virtuali.
34 -
35 -## shouldComponentUpdate in azione
36 -
37 -Ecco un sottoalbero di componenti. Per ciascuno di essi viene indicato cosa `shouldComponentUpdate` ha restituito e se i DOM virtuali siano equivalenti o meno. Infine, il colore del cerchio indica se il componente sia stato riconciliato o meno.
38 -
39 -<figure><img src="/react/img/docs/should-component-update.png" /></figure>
40 -
41 -Nell'esempio precedente, dal momento che `shouldComponentUpdate` ha restituito `false` per il sottoalbero di radice C2, React non ha avuto bisogno di generare il nuovo DOM virtuale, e quindi non ha nemmeno avuto bisogno di riconciliare il DOM. Nota che React non ha nemmeno avuto bisogno di invocare `shouldComponentUpdate` su C4 e C5.
42 -
43 -Per C1 e C3, `shouldComponentUpdate` ha restituito `true`, quindi React è dovuto scendere giù fino alle foglie e controllarle. Per C6 ha restituito `true`; dal momento che i DOM virtuali non erano equivalenti, ha dovuto riconciliare il DOM.
44 -L'ultimo caso interessante è C8. Per questo nodo React ha dovuto calcolare il DOM virtuale, ma dal momento che era uguale al vecchio, non ha dovuto riconciliare il suo DOM.
45 -
46 -Nota che React ha dovuto effettuare mutazioni del DOM soltanto per C6, che era inevitabile. Per C8, lo ha evitato confrontando i DOM virtuali, e per il sottoalbero di C2 e C7, non ha neppure dovuto calcolare il DOM virtuale in quanto è stato esonerato da `shouldComponentUpdate`.
47 -
48 -Quindi, come dovremmo implementare `shouldComponentUpdate`? Supponiamo di avere un componente che visualizza soltanto un valore stringa:
49 -
50 -```javascript
51 -React.createClass({
52 - propTypes: {
53 - value: React.PropTypes.string.isRequired
54 - },
55 -
56 - render: function() {
57 - return <div>{this.props.value}</div>;
58 - }
59 -});
60 -```
61 -
62 -Potremmo facilmente implementare `shouldComponentUpdate` come segue:
63 -
64 -```javascript
65 -shouldComponentUpdate: function(nextProps, nextState) {
66 - return this.props.value !== nextProps.value;
67 -}
68 -```
69 -
70 -Finora tutto a posto, maneggiare queste semplici strutture proprietà e stato è molto facile. Potremmo anche generalizzare un'implementazione basata sull'uguaglianza superficiale e farne il mix dentro i componenti. Infatti, React fornisce già una tale implementazione: [PureRenderMixin](/react/docs/pure-render-mixin.html).
71 -
72 -Ma che succede se le proprietà o lo stato del tuo componente sono strutture dati mutevoli? Supponiamo che la proprietà che il componente riceve sia, anziché una stringa come `'bar'`, un oggetto JavaScript che contiene una stringa, come `{ foo: 'bar' }`:
73 -
74 -```javascript
75 -React.createClass({
76 - propTypes: {
77 - value: React.PropTypes.object.isRequired
78 - },
79 -
80 - render: function() {
81 - return <div>{this.props.value.foo}</div>;
82 - }
83 -});
84 -```
85 -
86 -L'implementazione di `shouldComponentUpdate` che avevamo prima non funzionerebbe sempre come ci aspettiamo:
87 -
88 -```javascript
89 -// assumiamo che this.props.value sia { foo: 'bar' }
90 -// assumiamo che nextProps.value sia { foo: 'bar' },
91 -// ma questo riferimento è diverso da this.props.value
92 -this.props.value !== nextProps.value; // true
93 -```
94 -
95 -Il problema è che `shouldComponentUpdate` restituirà `true` quando la proprietà non è in realtà cambiata. Per risolvere questo problema, potremmo proporre questa implementazione alternativa:
96 -
97 -```javascript
98 -shouldComponentUpdate: function(nextProps, nextState) {
99 - return this.props.value.foo !== nextProps.value.foo;
100 -}
101 -```
102 -
103 -In breve, abbiamo finito per effettuare un confronto in profondità per assicurarci di accorgerci correttamente dei cambiamenti. In termini di prestazioni, questo approccio è molto costoso. Non scala in quanto dovremmo scrivere codice diverso per valutare l'uguaglianza in profondità per ciascun modello. Inoltre, potrebbe anche non funzionare per nulla se non gestiamo correttamente i riferimenti agli oggetti. Supponiamo che il componente sia usato da un genitore:
104 -
105 -```javascript
106 -React.createClass({
107 - getInitialState: function() {
108 - return { value: { foo: 'bar' } };
109 - },
110 -
111 - onClick: function() {
112 - var value = this.state.value;
113 - value.foo += 'bar'; // ANTI-PATTERN!
114 - this.setState({ value: value });
115 - },
116 -
117 - render: function() {
118 - return (
119 - <div>
120 - <InnerComponent value={this.state.value} />
121 - <a onClick={this.onClick}>Click me</a>
122 - </div>
123 - );
124 - }
125 -});
126 -```
127 -
128 -La prima volta che viene effettuato il rendering del componente interno, la sua proprietà value avrà il valore `{ foo: 'bar' }`. Se l'utente clicca l'ancora, lo stato del componente genitore sarà aggiornato a `{ value: { foo: 'barbar' } }`, scatenando il processo di ri-rendering sul componente interno, il quale riceverà `{ foo: 'barbar' }` come il nuovo valore della proprietà.
129 -
130 -Il problema è che, dal momento che il genitore e il componente interno condividono un riferimento allo stesso oggetto, quando l'oggetto viene modificato nella riga 2 della funzione `onClick`, la proprietà che il componente interno possedeva cambierà anch'essa. Quindi, quando il processo di ri-rendering inizia, e `shouldComponentUpdate` viene invocato, `this.props.value.foo` sarà uguale a `nextProps.value.foo`, perché infatti, `this.props.value` si riferisce allo stesso oggetto di `nextProps.value`.
131 -
132 -Di conseguenza, dal momento che non ci accorgiamo del cambiamento della proprietà e cortocircuitiamo il processo di ri-rendering, la UI non sarà aggiornata da `'bar'` a `'barbar'`.
133 -
134 -## Immutable-js viene in nostro soccorso
135 -
136 -[Immutable-js](https://github.com/facebook/immutable-js) è una libreria di collezioni JavaScript scritta da Lee Byron, che Facebook ha recentemente rilasciato come open source. Fornisce collezioni *immutabili e persistenti* attraverso *condivisione strutturale*. Vediamo cosa significano queste proprietà:
137 -
138 -* *Immutabile*: una volta creata, una collezione non può essere alterata in un momento successivo.
139 -* *Persistente*: nuove collezioni possono essere create da una collezione precedente e una mutazione come un assegnamento. La collezione originale è ancora valida dopo che la nuova collezione è stata creata.
140 -* *Condivisione Strutturale*: nuove collezioni sono create riutilizzando quanto più possibile della stessa struttura della collezione originale, riducendo le operazioni di copia al minimo, per ottenere efficienza spaziale e prestazioni accettabili. Se la nuova collezione è identica all'originale, l'originale è spesso restituita.
141 -
142 -L'immutabilità ci permette di tenere traccia dei cambiamenti in modo economico; un cambiamento risulterà sempre in un nuovo oggetto, quindi dobbiamo soltanto controllare se il riferimento all'oggeto sia cambiato. Ad esempio, in questo codice regolare JavaScript:
143 -
144 -```javascript
145 -var x = { foo: "bar" };
146 -var y = x;
147 -y.foo = "baz";
148 -x === y; // true
149 -```
150 -
151 -Sebbene `y` sia stato modificato, dal momento che si tratta di un riferimento allo stesso oggetto di `x`, questo confronto restituisce `true`. Tuttavia, questo codice potrebbe essere scritto usando immutable-js come segue:
152 -
153 -```javascript
154 -var SomeRecord = Immutable.Record({ foo: null });
155 -var x = new SomeRecord({ foo: 'bar' });
156 -var y = x.set('foo', 'baz');
157 -x === y; // false
158 -```
159 -
160 -In questo caso, poiché un nuovo riferimento è restituito quando si modifica `x`, possiamo assumere in tutta sicurezza che `x` sia cambiato.
161 -
162 -Un'altra maniera possibile di tener traccia dei cambiamenti potrebbe essere il dirty checking, ovvero usare un flag impostato dai metodi setter. Un problema con questo approccio è che ti forza ad usare i setter e scrivere un sacco di codice aggiuntivo, oppure instrumentare in qualche modo le tue classi. In alternativa, puoi effettuare una copia profonda dell'oggetto immediatamente prima della mutazione ed effettuare un confronto in profondità per determinare se vi è stato un cambiamento oppure no. Un problema con questo approccio è che sia deepCopy che deepCompare sono operazioni costose.
163 -
164 -Quindi, le strutture dati Immutable ti forniscono una maniera economica e concisa di osservare i cambiamenti degli oggetti, che è tutto ciò che ci serve per implementare `shouldComponentUpdate`. Pertanto, se modelliamo gli attributi delle proprietà e dello stato usando le astrazioni fornite da immutable-js saremo in grado di usare `PureRenderMixin` e ottenere un grande aumento di prestazioni.
165 -
166 -## Immutable-js e Flux
167 -
168 -Se stai usando [Flux](https://facebook.github.io/flux/), dovresti cominciare a scrivere i tuoi store usando immutable-js. Dài un'occhiata alla [API completa](https://facebook.github.io/immutable-js/docs/#/).
169 -
170 -Vediamo una delle possibili maniere di modellare l'esempio dei thread usando strutture dati Immutable. Anzitutto, dobbiamo definire un `Record` per ciascuna delle entità che desideriamo modellare. I Record sono semplicemente contenitori immutabili che contengono valori per un insieme specifico di campi:
171 -
172 -```javascript
173 -var User = Immutable.Record({
174 - id: undefined,
175 - name: undefined,
176 - email: undefined
177 -});
178 -
179 -var Message = Immutable.Record({
180 - timestamp: new Date(),
181 - sender: undefined,
182 - text: ''
183 -});
184 -```
185 -
186 -La funzione `Record` riceve un oggetto che definisce i campi che l'oggetto possiede e i loro valori predefiniti.
187 -
188 -Lo *store* dei messaggi potrebbe tenere traccia degli utenti e dei messaggi usando due liste:
189 -
190 -```javascript
191 -this.users = Immutable.List();
192 -this.messages = Immutable.List();
193 -```
194 -
195 -Dovrebbe essere abbastanza banale implementare funzioni che gestiscono ciascun tipo di *payload*. Ad esempio, quando lo store vede un payload che rappresenta un messaggio, possiamo semplicemente creare un nuovo record e metterlo in coda alla lista di messaggi:
196 -
197 -```javascript
198 -this.messages = this.messages.push(new Message({
199 - timestamp: payload.timestamp,
200 - sender: payload.sender,
201 - text: payload.text
202 -});
203 -```
204 -
205 -Nota che dal momento che le strutture dati sono immutabili, dobbiamo assegnare il valore di ritorno del metodo push a `this.messages`.
206 -
207 -Dal punto di vista di React, se usiamo strutture dati immutable-js anche per contenere lo stato del componente, possiamo fare il mix di `PureRenderMixin` in tutti i nostri componenti e cortocircuitare il processo di ri-rendering.
docs/docs/11-advanced-performance.ja-JP.md deleted
-205
@@ -1,205 +0,0 @@
1 ----
2 -id: advanced-performance
3 -title: 先進的なパフォーマンス
4 -permalink: docs/advanced-performance-ja-JP.html
5 -prev: perf-ja-JP.html
6 ----
7 -
8 -Reactをプロジェクトで使用しようとする際にまず最初に気になるのは、アプリケーションがReactを使用しないバージョンと比べて、同じくらい速くてレスポンシブであるかどうかということです。ステータスの変更毎にレスポンスでコンポーネントのサブツリーの全てを再度レンダリングするという考え方によって、このプロセスがパフォーマンスにネガティブな影響を与えるのではないかと人々は不安に思います。ReactはUIを更新するのに必要な、コストのかかる多くのDOMの操作を最小限にするためのいくつかの賢い技術を使用します。
9 -
10 -## DOMを一致させることを防ぐこと
11 -
12 -ReactはブラウザでレンダリングされるDOMのサブツリーの記述語である *virtual DOM* を使用しています。この2つの表現によってReactは、JavaScriptのオブジェクトの操作よりも遅い、DOMノードを作成したり存在しているDOMノードにアクセスすることを防いでいます。コンポーネントの `props` や `state` が変更された時、Reactは新しいvirtual DOMを構成して、それを古いものと比較することによって、実際のDOMの更新が必要かどうか決定します。それらが同じものでなかった場合にのみ、ReactはDOMを[一致](/react/docs/reconciliation.html)させ、最小限の変更を適用します。
13 -この最上位で、Reactはコンポーネントライフサイクルファンクションである `shouldComponentUpdate` を提供します。これは、再度レンダリングを行うプロセス(virtual DOMの比較と起こり得る最終的なDOMの一致)が始まる前に誘発されます。そして、開発者にこのプロセスの循環を短くすることを可能にします。デフォルトのこの関数の実行時にはReactが更新を行って、以下のように `true` が返ります。
14 -
15 -```javascript
16 -shouldComponentUpdate: function(nextProps, nextState) {
17 - return true;
18 -}
19 -```
20 -
21 -Reactがとても頻繁にこの関数を呼び出すので、実行が速いものである必要があることを頭に置いておいてください。
22 -
23 -いくつかのチャットのスレッドを持つメッセージングのアプリケーションを持っていると仮定してください。そして、スレッドのうち1つだけが変更されたと考えてください。 `ChatThread` コンポーネントで `shouldComponentUpdate` を実行した際には、Reactは以下のように、他のスレッドのレンダリングステップをスキップできます。
24 -
25 -```javascript
26 -shouldComponentUpdate: function(nextProps, nextState) {
27 - // TODO: 現在のチャットスレッドが以前のものと
28 - // 異なっているかどうかをリターンする。
29 -}
30 -```
31 -
32 -つまり、要約すると、ReactはDOMのサブツリーを一致させる必要があるためにコストのかかるDOMの操作を実行するのを避けます。 `shouldComponentUpdate` を使用して、このプロセスを短縮することができます。そして、virtual DOMを比較して、更新すべきDOMだけを更新します。
33 -
34 -## shouldComponentUpdate の実行
35 -
36 -以下はコンポーネントのサブツリーです。1つ1つは `shouldComponentUpdate` が何をリターンするかとvirtual DOMが同じものであるかどうかを示しています。最終的には、円の色が、コンポーネントを一致させる必要があるかどうかを示しています。
37 -
38 -<figure><img src="/react/img/docs/should-component-update.png" /></figure>
39 -
40 -上記の例では、C2の上の `shouldComponentUpdate` が `false` を返しているので、Reactは新しいvirtual DOMを生成する必要はありません。そして、それゆえ、DOMを一致させる必要もありません。C4とC5についても、Reactが `shouldComponentUpdate` を実行する必要がないことに注意してください。
41 -
42 -C1とC3の `shouldComponentUpdate` は `true` を返すので、Reactは葉の部分まで降りてそれらのチェックを行います。C6が `true` を返すので、virtual DOMが同じものではなくなり、DOMを一致させる必要があります。最後の興味深いケースはC8です。このノードについては、Reactはvirtual DOMを計算する必要がありますが、古いものと同じであるため、DOMと一致させる必要はありません。
43 -
44 -ReactがDOMを変化させるのはC6だけであることに注意してください。これは避けられません。C8は、virtual DOMの比較から解放されています。C2のサブツリーとC7も同様です。`shouldComponentUpdate` から解放されているので、virtual DOMの比較を行う必要はありません。
45 -
46 -それでは、私たちはどのように `shouldComponentUpdate` を実行すべきでしょうか?ある文字列の値をただレンダリングするコンポーネントの場合について見てみましょう。
47 -
48 -```javascript
49 -React.createClass({
50 - propTypes: {
51 - value: React.PropTypes.string.isRequired
52 - },
53 -
54 - render: function() {
55 - return <div>this.props.value</div>;
56 - }
57 -});
58 -```
59 -
60 -以下のように簡単に `shouldComponentUpdate` を実行することができます。
61 -
62 -```javascript
63 -shouldComponentUpdate: function(nextProps, nextState) {
64 - return this.props.value !== nextProps.value;
65 -}
66 -```
67 -
68 -これまでは順調でした。以上のような、単純なpropsやstateの構造を扱うことは簡単です。浅い同一性に基づいて実行したり、コンポーネントに組み込んだりもできます。実際、Reactはそのような実行のためのMixinを既に提供しています。[PureRenderMixin](/react/docs/pure-render-mixin-ja-JP.html)です。
69 -
70 -しかし、コンポーネントのpropsやstateが変更される可能性がある場合はどうでしょうか?propが `bar` のような文字列ではなく、コンポーネント受け取ったものであると考えてみると、 `{ foo: 'bar' }` のような文字列を含んだJavaScriptのオブジェクトになります。
71 -
72 -```javascript
73 -React.createClass({
74 - propTypes: {
75 - value: React.PropTypes.object.isRequired
76 - },
77 -
78 - render: function() {
79 - return <div>this.props.value.foo</div>;
80 - }
81 -});
82 -```
83 -
84 -今までに述べてきた `shouldComponentUpdate` の実行は常に想定した通りに動くとは限りません。
85 -
86 -```javascript
87 -// this.props.value が { foo: 'bar' } であると仮定
88 -// nextProps.value が { foo: 'bar' } であると仮定
89 -// しかし、この参照は this.props.value とは異なります。
90 -this.props.value !== nextProps.value; // true
91 -```
92 -
93 -問題は、 `shouldComponentUpdate` が、propが実際には変化していない場合にも `true` を返すことです。これを修正するために、以下のような代替の実行を行うことができます。
94 -
95 -```javascript
96 -shouldComponentUpdate: function(nextProps, nextState) {
97 - return this.props.value.foo !== nextProps.value.foo;
98 -}
99 -```
100 -
101 -基本的には、厳密に変更を追跡することを明確にするために、深い比較を行うことになります。パフォーマンスの点では、このアプローチはとてもコストがかかります。これは、それぞれのモデルに対して間違った深い同一性のコードを書いているであろうときには、スケールしません。その最上部では、オブジェクトの参照を注意深く見ていなければ、動作しさえしません。以下のコンポーネントが親から使用されていると考えてください。
102 -
103 -```javascript
104 -React.createClass({
105 - getInitialState: function() {
106 - return { value: { foo: 'bar' } };
107 - },
108 -
109 - onClick: function() {
110 - var value = this.state.value;
111 - value.foo += 'bar'; // アンチパターン!
112 - this.setState({ value: value });
113 - },
114 -
115 - render: function() {
116 - return (
117 - <div>
118 - <InnerComponent value={this.state.value} />
119 - <a onClick={this.onClick}>Click me</a>
120 - </div>
121 - );
122 - }
123 -});
124 -```
125 -
126 -はじめに、内部のコンポーネントがレンダリングされます。それは、valueというプロパティとして `{ foo: 'bar' }` を保有します。ユーザがアンカーをクリックした際には、親のコンポーネントのstateが `{ value: { foo: 'barbar' } }` にアップデートされるでしょう。そして、新しいvalueのプロパティとして、 `{ foo: 'barbar' }` を受け取る、内部のコンポーネントの再レンダリングのプロセスのトリガーとなります。
127 -
128 -問題は、親と内部のコンポーネントが同じオブジェクトへの参照を共有していることです。オブジェクトが `onClick` 関数の2行目で変更された時には、内部のコンポーネントが保有しているプロパティが変更されるでしょう。そのため、再レンダリングのプロセスが始まった時と、 `shouldComponentUpdate` が呼び出された時には、 `this.props.value.foo` は `nextProps.value.foo` と同じものになるでしょう。そのため、実際は、 `this.props.value` は `nextProps.value` と同じオブジェクトを参照します。
129 -
130 -結果として、プロパティの変更と再レンダリングのプロセスを省略ができなかったので、UIは `'bar'` から `'barbar'` にアップデートされないでしょう。
131 -
132 -## 助けとなるImmutable-js
133 -
134 -[Immutable-js](https://github.com/facebook/immutable-js)はLee Byronによって作成されたJavaScriptのコレクションのライブラリです。Facebookが最近オープンソース化しました。これは、 *構造の共有* を通して、*不変の状態を保ち続ける* コレクションを提供します。以下のプロパティが何を意味するか見ていきましょう。
135 -
136 -* *Immutable*: 一度作成されたら、コレクションは変更できません。
137 -* *Persistent*: 新しいコレクションは以前のコレクションかsetのような変化によってのみ作成されます。元となるコレクションは新しいコレクションが作成された後も使用可能です。
138 -* *Structural Sharing*: 新しいコレクションは元のコレクションとなるべく同じ構造を持って作成されます。パフォーマンスが効率的で許容できるものであるように、コピーを少なくします。新しいコレクションが元のものと同じである場合は、多くの場合元のものがリターンされます。
139 -
140 -不変性によって、変更を追跡するコストが下がります。変更は常に新しいオブジェクトを生むので、オブジェクトの参照が変更されたかどうかを確認しさえすればよいのです。例えば、以下のような一般的なJavaScriptのコードにおいては、
141 -
142 -```javascript
143 -var x = { foo: "bar" };
144 -var y = x;
145 -y.foo = "baz";
146 -x === y; // true
147 -```
148 -
149 -`y` は編集されていますが、`x` と同じオブジェクトを参照しているので、それらの比較は `true` を返します。しかし、以下のコードはimmutable-jsを使用すると以下のように記述されます。
150 -
151 -```javascript
152 -var SomeRecord = Immutable.Record({ foo: null });
153 -var x = new SomeRecord({ foo: 'bar' });
154 -var y = x.set('foo', 'baz');
155 -x === y; // false
156 -```
157 -
158 -このケースでは、 `x` を変更する時に新しい参照が返されているので、 `x` が変更されたことを安全に認識することができます。
159 -
160 -変更を追跡する他の方法は、セッタによるフラグセットを保持することでダーティーチェックを行うことです。このアプローチの問題は、追加のコードを多く書いた場合やクラスの編集をいくつか行った場合でもセッタの使用が強制されることです。代わりに、変化の直前にオブジェクトをディープコピーし、変更が有ろうと無かろうと、その特定のために深い比較を行うことができます。このアプローチの問題は、ディープコピーと深い比較の両方とも、コストの高い操作であることです。
161 -
162 -そのため、不変なデータ構造によって、オブジェクトの変更を追跡するためのコストの低く、冗長ではない方法が提供されます。私たちがすべきなのは `shouldComponentUpdate` を実行することだけです。それゆえ、immutable-jsに提供される抽象化を使用して、propsやstate属性を形作る場合は、 `PureRenderMixin` を使用して、パフォーマンスの向上を行うことができます。
163 -
164 -## Immutable-js と Flux
165 -
166 -[Flux](https://facebook.github.io/flux/)を使用している場合には、immutable-jsを使用して書き直すべきです。[API一覧](https://facebook.github.io/immutable-js/docs/#/)をご覧ください。
167 -
168 -不変のデータ構造を使用したスレッドの例を形作る、ある方法を見ていきましょう。はじめに、形作ろうとしているエンティティのそれぞれに `Record` を定義する必要が有ります。Record はあるフィールドのセットの値を保持している、ただの不変なコンテナです。
169 -
170 -```javascript
171 -var User = Immutable.Record({
172 - id: undefined,
173 - name: undefined,
174 - email: undefined
175 -});
176 -
177 -var Message = Immutable.Record({
178 - timestamp: new Date(),
179 - sender: undefined,
180 - text: ''
181 -});
182 -```
183 -
184 -`Record` 関数はオブジェクトが保有しているフィールドとデフォルトの値を定義するオブジェクトを受け取ります。
185 -
186 -メッセージの *ストア* は以下のように2つのリストを使用して users と messages を追跡し続けることができます。
187 -
188 -```javascript
189 -this.users = Immutable.List();
190 -this.messages = Immutable.List();
191 -```
192 -
193 -それぞれの *ペイロードの* 型を調査することはとても単純で、関数を実行するだけです。例えば、ストアが新しいメッセージを代表するペイロードを調べるときには、新しいレコードを作成し、それを以下のような messages のリストとして適用するだけです。
194 -
195 -```javascript
196 -this.messages = this.messages.push(new Message({
197 - timestamp: payload.timestamp,
198 - sender: payload.sender,
199 - text: payload.text
200 -});
201 -```
202 -
203 -データ構造が不変であることで、push関数の結果を `this.messages` にアサインする必要があることに注意してください。
204 -
205 -Reactの側では、 immutable-js のデータ構造をコンポーネントの state を保持するために使用する場合は、 `PureRenderMixin` をコンポーネントにミックスし、再レンダリングのプロセスを短縮することもできます。
docs/docs/11-advanced-performance.ko-KR.md deleted
-206
@@ -1,206 +0,0 @@
1 ----
2 -id: advanced-performance-ko-KR
3 -title: 성능 심화
4 -permalink: docs/advanced-performance-ko-KR.html
5 -prev: perf-ko-KR.html
6 -next: context-ko-KR.html
7 ----
8 -
9 -React를 도입하려 할 때 많은 사람이 묻는 첫 번째 질문은 React를 사용하지 않을 때처럼 애플리케이션이 빠르고 반응성도 좋을 것이냐는 것입니다. 모든 상태변화에 대해 컴포넌트의 하위 트리를 전부 다시 렌더링하는 아이디어에 대해 사람들은 이 프로세스가 성능에 부정적인 영향을 줄 것으로 생각하지만, React는 여러 가지 영리한 방법을 통해 UI를 업데이트하는데 필요한 비싼 DOM 조작을 최소화합니다.
10 -
11 -## DOM 조정 회피
12 -
13 -React는 브라우저에서 렌더된 DOM 하위 트리의 서술자 개념인 *가상의 DOM*을 사용합니다. 이 병렬적인 서술체는 React가 DOM 노드를 생성하거나 이미 존재하는 DOM 노드에 접근하는 것(JavaScript 객체를 조작하는 것보다 느리죠)을 피하게 해 줍니다. 컴포넌트의 props나 state가 변경되면 React는 새로운 가상의 DOM을 구성해 이전의 것과 비교해서 실제 DOM 업데이트가 필요한지 결정합니다. 가능한 적게 변화를 적용하기 위해, React는 둘이 다를 경우에만 DOM을 [조정](/react/docs/reconciliation-ko-KR.html)할 것입니다.
14 -
15 -이에 더해, React는 컴포넌트 생명주기 함수인 `shouldComponentUpdate`를 제공합니다. 이는 다시 렌더링하는 프로세스(가상 DOM 비교와 어쩌면 일어날 DOM 조정)가 일어나기 직전에 일어나며 개발자가 프로세스를 중단할 수 있게 합니다. 이 함수의 기본구현은 `true`를 반환해 React가 업데이트를 수행하도록 합니다.
16 -
17 -```javascript
18 -shouldComponentUpdate: function(nextProps, nextState) {
19 - return true;
20 -}
21 -```
22 -
23 -React가 이 함수를 자주 호출한다는 것을 명심하십시오. 따라서 구현체는 빨라야 합니다.
24 -
25 -대화 스레드가 여럿 돌고 있는 메시지처리 애플리케이션을 생각해 봅시다. 오직 하나의 스레드만이 변경되었다고 가정해 보죠. `ChatThread`에 `shouldComponentUpdate`를 구현했다면 React는 다른 스레드의 렌더링 프로세스를 건너뛸 수 있습니다.
26 -
27 -```javascript
28 -shouldComponentUpdate: function(nextProps, nextState) {
29 - // TODO: 현재의 대화 스레드가 이전의 것과 다른지 아닌지를 반환한다
30 -}
31 -```
32 -
33 -정리하자면, React는 사용자가 `shouldComponentUpdate`를 사용해 렌더링 프로세스를 중단하고 가상의 DOM과 비교해 업데이트 여부를 결정해서 DOM의 하위 트리를 조정하는 비싼 DOM 조작을 피하도록 합니다.
34 -
35 -## shouldComponentUpdate 실전
36 -
37 -다음은 컴포넌트의 하위 트리입니다. 각각은 `shouldComponentUpdate`의 반환값(SCU)과 가상의 DOM과의 동일성(vDOMEq)을 표시합니다. 마지막으로, 원의 색은 컴포넌트가 조정되었는지를 표시합니다.
38 -
39 -<figure><img src="/react/img/docs/should-component-update.png" /></figure>
40 -
41 -위의 예시에서, C2를 루트로 하는 하위 트리에 대해 `shouldComponentUpdate`가 `false`를 반환했기 때문에 React는 새로운 가상의 DOM을 만들 필요가 없습니다. 따라서 DOM을 조정할 필요도 없습니다. React가 C4와 C5에는 `shouldComponentUpdate`를 요청하지도 않은 것을 확인하세요.
42 -
43 -C1과 C3의 `shouldComponentUpdate`가 `true`를 반환했기 때문에 React는 하위 노드로 내려가 그들을 확인합니다. C6는 `true`를 반환했네요; 이는 가상의 DOM과 같지 않기 때문에 DOM의 조정이 일어났습니다. 마지막으로 흥미로운 사례는 C8입니다. React가 이 노드를 위해 가상의 DOM을 작동했지만, 노드가 이전의 것과 일치했기 때문에 DOM의 조정을 일어나지 않았습니다.
44 -
45 -React가 C6에만 DOM 변경을 수행한 것을 확인하세요. 이는 필연적이었습니다. C8의 경우는, 가상의 DOM과 비교를 해 제외되었고, C2의 하위 트리와 C7은 `shouldComponentUpdate` 단계에서 제외되어 가상의 DOM은 구동조차 되지 않았습니다.
46 -
47 -자 그럼, 어떻게 `shouldComponentUpdate`를 구현해야 할까요? 문자열 값을 렌더하는 컴포넌트를 생각해보죠.
48 -
49 -```javascript
50 -React.createClass({
51 - propTypes: {
52 - value: React.PropTypes.string.isRequired
53 - },
54 -
55 - render: function() {
56 - return <div>{this.props.value}</div>;
57 - }
58 -});
59 -```
60 -
61 -다음과 같이 간단히 `shouldComponentUpdate`를 구현해 볼 수 있습니다:
62 -
63 -```javascript
64 -shouldComponentUpdate: function(nextProps, nextState) {
65 - return this.props.value !== nextProps.value;
66 -}
67 -```
68 -
69 -여기까지는 좋습니다. 간단한 props/state 구조를 다루기는 쉽습니다. 단순한 등식비교 구현을 일반화하고 이를 컴포넌트에 혼합할 수도 있습니다. 사실, React는 이미 그런 구현을 제공합니다: [PureRenderMixin](/react/docs/pure-render-mixin-ko-KR.html).
70 -
71 -하지만 만약 컴포넌트의 props나 state가 가변적인 데이터 구조로 되어 있다면 어떨까요? 컴포넌트의 prop으로 `'bar'`같은 문자열 대신에 `{ foo: 'bar' }`처럼 문자열을 포함한 JavaScript 객체를 전달받는다고 해봅시다.
72 -
73 -```javascript
74 -React.createClass({
75 - propTypes: {
76 - value: React.PropTypes.object.isRequired
77 - },
78 -
79 - render: function() {
80 - return <div>{this.props.value.foo}</div>;
81 - }
82 -});
83 -```
84 -
85 -전에 구현했던 `shouldComponentUpdate`는 언제나 예상대로 작동하지 않을 것입니다:
86 -
87 -```javascript
88 -// this.props.value가 { foo: 'bar' }라고 가정합니다
89 -// nextProps.value도 { foo: 'bar' }라고 가정하지만,
90 -// 이 참조는 this.props.value와 다른 것입니다
91 -this.props.value !== nextProps.value; // true
92 -```
93 -
94 -문제는 prop이 실제로 변경되지 않았을 때도 `shouldComponentUpdate`가 `true`를 반환할 거라는 겁니다. 이를 해결하기 위한 대안으로, 아래와 같이 구현해 볼 수 있습니다:
95 -
96 -```javascript
97 -shouldComponentUpdate: function(nextProps, nextState) {
98 - return this.props.value.foo !== nextProps.value.foo;
99 -}
100 -```
101 -
102 -기본적으로, 우리는 변경을 정확히 추적하기 위해서 깊은 비교를 해야 했습니다. 이 방법은 성능 면에서 제법 비쌉니다. 각각의 모델마다 다른 깊은 등식 코드를 작성해야 하므로 확장이 힘들어 집니다. 심지어 객체 참조를 신중히 관리하지 않는다면 작동하지도 않을 수 있습니다. 컴포넌트가 부모에 의해 다뤄지는 경우를 살펴보죠:
103 -
104 -```javascript
105 -React.createClass({
106 - getInitialState: function() {
107 - return { value: { foo: 'bar' } };
108 - },
109 -
110 - onClick: function() {
111 - var value = this.state.value;
112 - value.foo += 'bar'; // 안티패턴 입니다!
113 - this.setState({ value: value });
114 - },
115 -
116 - render: function() {
117 - return (
118 - <div>
119 - <InnerComponent value={this.state.value} />
120 - <a onClick={this.onClick}>클릭하세요</a>
121 - </div>
122 - );
123 - }
124 -});
125 -```
126 -
127 -처음엔 내부 컴포넌트(`<InnerComponent />`)가 `{ foo: 'bar' }`를 value prop으로 가진 채 렌더될 것입니다. 사용자가 앵커(`<a>`)를 클릭한다면 부모 컴포넌트의 state는 `{ value: { foo: 'barbar' } }`로 업데이트되고, 내부 컴포넌트 또한 `{ foo: 'barbar' }`를 새로운 value prop으로 전달받아 다시 렌더링 되는 프로세스가 일어날 것입니다.
128 -
129 -이 문제는 부모와 내부 컴포넌트가 같은 객체에 대한 참조를 공유하기 때문에 발생합니다. `onClick` 함수의 두 번째 줄에서 객체에 대한 변경이 일어날 때, 내부 컴포넌트의 prop도 변경될 것입니다. 따라서 다시 렌더링 되는 프로세스가 시작될 때 `shouldComponentUpdate`가 호출되고 `this.props.value.foo`가 `nextProps.value.foo`와 같게 됩니다. 실제로 `this.props.value`는 `nextProps.value`와 같은 객체이기 때문입니다.
130 -
131 -그에따라 prop의 변경을 놓치게 되어 다시 렌더링하는 프로세스가 중단되고, UI는 `'bar'`에서 `'barbar'`로 업데이트되지 않습니다.
132 -
133 -## 구원자 Immutable-js
134 -
135 -[Immutable-js](https://github.com/facebook/immutable-js)는 Lee Byron이 만들고 Facebook이 오픈소스화 한 JavaScript 컬렉션 라이브러리입니다. 이는 *구조의 공유(structural sharing)*를 통해 *불변의 영속적인(immutable persistent)* 컬렉션을 제공합니다. 이러한 속성이 무엇을 의미하는지 살펴보죠:
136 -
137 -* *불변성(Immutable)*: 컬렉션이 한번 생성되면, 이 후 다른 시점에 변경될 수 없습니다.
138 -* *영속성(Persistent)*: 새로운 컬렉션이 이전의 컬렉션이나 셋(set) 같은 뮤테이션(mutation)에서 생성될 수 있습니다. 기존의 컬렉션은 새로운 컬렉션이 생성된 후에도 여전히 유효합니다.
139 -* *구조의 공유(Structural Sharing)*: 새로운 컬렉션은 가능한 한 원래의 컬렉션과 같은 구조를 사용해 생성됩니다. 공간 효율성과 적절한 성능을 위해 복사를 최소화합니다.
140 -
141 -불변성은 변경의 추적을 비용을 줄여줍니다; 변경은 항상 새로운 객체에만 발생하기 때문에 객체에 대한 참조가 변경될 때만 확인하면 됩니다. 예를 들어 일반적인 이 JavaScript 코드에서는:
142 -
143 -```javascript
144 -var x = { foo: "bar" };
145 -var y = x;
146 -y.foo = "baz";
147 -x === y; // true
148 -```
149 -
150 -`y`가 수정되더라도 여전히 같은 객체인 `x`를 참조하고 있기 때문에, 이 비교는 `true`를 반환합니다. 하지만 이 코드를 immutable-js를 사용해 다음과 같이 작성할 수 있습니다:
151 -
152 -```javascript
153 -var SomeRecord = Immutable.Record({ foo: null });
154 -var x = new SomeRecord({ foo: 'bar' });
155 -var y = x.set('foo', 'baz');
156 -x === y; // false
157 -```
158 -
159 -이 경우, `x`가 변경되면 새로운 참조가 반환되기 때문에, 우리는 안전하게 `x`가 변경되었을 것으로 추정할 수 있습니다.
160 -
161 -변경을 탐지할 수 있는 또 다른 방법은 세터(setter)에 의해 설정된 플래그를 더티 체킹(dirty checking)하는 것입니다. 이 방식의 문제는 당신이 세터를 사용할 뿐만 아니라 수많은 추가 코드를 작성하거나 어떻게든 클래스들을 인스트루먼트(instrument) 하도록 강요한다는 것입니다. 혹은 변경(mutations) 직전에 객체를 깊은 복사(deep copy) 한 뒤 깊은 비교(deep compare)를 수행해 변경 여부를 판단할 수 있습니다. 이 방식의 문제점은 deepCopy와 deepCompare 둘 다 비용이 많이 드는 연산이라는 것입니다.
162 -
163 -그래서 Immutable 자료구조는 `shouldComponentUpdate`의 구현에 필요한 객체의 변경사항을 추적할 수 있는 덜 자세하지만 저렴한 방법을 제공합니다. 그에 따라 immutable-js가 제공하는 추상화를 사용해 props와 state 어트리뷰트를 모델링한다면, `PureRenderMixin`을 사용해 성능을 향상할 수 있습니다.
164 -
165 -## Immutable-js와 Flux
166 -
167 -[Flux](https://facebook.github.io/flux/)를 사용한다면 immutable-js를 사용해 stores를 작성해야 합니다. [전체 API](https://facebook.github.io/immutable-js/docs/#/)를 살펴보세요.
168 -
169 -Immutable 자료구조를 이용해 스레드를 모델링하는 예제를 살펴봅시다. 먼저 모델링하려는 엔티티마다 `Record`를 정의해야 합니다. Record는 특정 필드들의 값을 유지하기 위한 불변의 컨테이너입니다:
170 -
171 -```javascript
172 -var User = Immutable.Record({
173 - id: undefined,
174 - name: undefined,
175 - email: undefined
176 -});
177 -
178 -var Message = Immutable.Record({
179 - timestamp: new Date(),
180 - sender: undefined,
181 - text: ''
182 -});
183 -```
184 -
185 -`Record` 함수는 필드별로 기본값이 선언된 객체에 대한 정의를 넘겨받습니다.
186 -
187 -메시지 store는 두 개의 List를 통해 users와 messages를 추적할 수 있습니다:
188 -
189 -```javascript
190 -this.users = Immutable.List();
191 -this.messages = Immutable.List();
192 -```
193 -
194 -각각의 *페이로드* 타입을 처리하는 기능을 구현하는 것은 꽤 간단합니다. 예를 들면, store가 새 메시지를 나타내는 페이로드를 확인할 때 레코드를 새로 생성하고 메시지 리스트에 추가할 수 있습니다.
195 -
196 -```javascript
197 -this.messages = this.messages.push(new Message({
198 - timestamp: payload.timestamp,
199 - sender: payload.sender,
200 - text: payload.text
201 -});
202 -```
203 -
204 -자료구조가 불변이기 때문에 push 함수의 결과를 `this.messages`에 할당할 필요가 있으니 주의하세요.
205 -
206 -React 측에서는, 컴포넌트의 state를 보존하기 위해 immutable-js 자료구조를 사용한다면, 모든 컴포넌트에 `PureRenderMixin`을 혼합해 다시 렌더링하는 프로세스를 중단할 수 있습니다.
docs/docs/11-advanced-performance.md deleted
-212
@@ -1,212 +0,0 @@
1 ----
2 -id: advanced-performance
3 -title: Advanced Performance
4 -permalink: docs/advanced-performance.html
5 -prev: shallow-compare.html
6 -next: context.html
7 ----
8 -
9 -One of the first questions people ask when considering React for a project is whether their application will be as fast and responsive as an equivalent non-React version. The idea of re-rendering an entire subtree of components in response to every state change makes people wonder whether this process negatively impacts performance. React uses several clever techniques to minimize the number of costly DOM operations required to update the UI.
10 -
11 -## Use the production build
12 -
13 -If you're benchmarking or experiencing performance problems in your React apps, make sure you're testing with the [minified production build](/react/downloads.html). The development build includes extra warnings that are helpful when building your apps, but it is slower due to the extra bookkeeping it does.
14 -
15 -## Avoiding reconciling the DOM
16 -
17 -React makes use of a *virtual DOM*, which is a descriptor of a DOM subtree rendered in the browser. This parallel representation allows React to avoid creating DOM nodes and accessing existing ones, which is slower than operations on JavaScript objects. When a component's props or state change, React decides whether an actual DOM update is necessary by constructing a new virtual DOM and comparing it to the old one. Only in the case they are not equal, will React [reconcile](/react/docs/reconciliation.html) the DOM, applying as few mutations as possible.
18 -
19 -On top of this, React provides a component lifecycle function, `shouldComponentUpdate`, which is triggered before the re-rendering process starts (virtual DOM comparison and possible eventual DOM reconciliation), giving the developer the ability to short circuit this process. The default implementation of this function returns `true`, leaving React to perform the update:
20 -
21 -```javascript
22 -shouldComponentUpdate: function(nextProps, nextState) {
23 - return true;
24 -}
25 -```
26 -
27 -Keep in mind that React will invoke this function pretty often, so the implementation has to be fast.
28 -
29 -Say you have a messaging application with several chat threads. Suppose only one of the threads has changed. If we implement `shouldComponentUpdate` on the `ChatThread` component, React can skip the rendering step for the other threads:
30 -
31 -```javascript
32 -shouldComponentUpdate: function(nextProps, nextState) {
33 - // TODO: return whether or not current chat thread is
34 - // different to former one.
35 -}
36 -```
37 -
38 -So, in summary, React avoids carrying out expensive DOM operations required to reconcile subtrees of the DOM by allowing the user to short circuit the process using `shouldComponentUpdate`, and, for those which should update, by comparing virtual DOMs.
39 -
40 -## shouldComponentUpdate in action
41 -
42 -Here's a subtree of components. For each one is indicated what `shouldComponentUpdate` returned and whether or not the virtual DOMs were equivalent. Finally, the circle's color indicates whether the component had to be reconciled or not.
43 -
44 -<figure><img src="/react/img/docs/should-component-update.png" /></figure>
45 -
46 -In the example above, since `shouldComponentUpdate` returned `false` for the subtree rooted at C2, React had no need to generate the new virtual DOM, and therefore, it neither needed to reconcile the DOM. Note that React didn't even have to invoke `shouldComponentUpdate` on C4 and C5.
47 -
48 -For C1 and C3 `shouldComponentUpdate` returned `true`, so React had to go down to the leaves and check them. For C6 it returned `true`; since the virtual DOMs weren't equivalent it had to reconcile the DOM.
49 -The last interesting case is C8. For this node React had to compute the virtual DOM, but since it was equal to the old one, it didn't have to reconcile it's DOM.
50 -
51 -Note that React only had to do DOM mutations for C6, which was inevitable. For C8, it bailed out by comparing the virtual DOMs, and for C2's subtree and C7, it didn't even have to compute the virtual DOM as we bailed out on `shouldComponentUpdate`.
52 -
53 -So, how should we implement `shouldComponentUpdate`? Say that you have a component that just renders a string value:
54 -
55 -```javascript
56 -React.createClass({
57 - propTypes: {
58 - value: React.PropTypes.string.isRequired
59 - },
60 -
61 - render: function() {
62 - return <div>{this.props.value}</div>;
63 - }
64 -});
65 -```
66 -
67 -We could easily implement `shouldComponentUpdate` as follows:
68 -
69 -```javascript
70 -shouldComponentUpdate: function(nextProps, nextState) {
71 - return this.props.value !== nextProps.value;
72 -}
73 -```
74 -
75 -So far so good, dealing with such simple props/state structures is easy. We could even generalize an implementation based on shallow equality and mix it into components. In fact, React already provides such implementation: [PureRenderMixin](/react/docs/pure-render-mixin.html).
76 -
77 -But what if your components' props or state are mutable data structures? Say the prop the component receives, instead of being a string like `'bar'`, is a JavaScript object that contains a string such as, `{ foo: 'bar' }`:
78 -
79 -```javascript
80 -React.createClass({
81 - propTypes: {
82 - value: React.PropTypes.object.isRequired
83 - },
84 -
85 - render: function() {
86 - return <div>{this.props.value.foo}</div>;
87 - }
88 -});
89 -```
90 -
91 -The implementation of `shouldComponentUpdate` we had before wouldn't always work as expected:
92 -
93 -```javascript
94 -// assume this.props.value is { foo: 'bar' }
95 -// assume nextProps.value is { foo: 'bar' },
96 -// but this reference is different to this.props.value
97 -this.props.value !== nextProps.value; // true
98 -```
99 -
100 -The problem is `shouldComponentUpdate` will return `true` when the prop actually didn't change. To fix this, we could come up with this alternative implementation:
101 -
102 -```javascript
103 -shouldComponentUpdate: function(nextProps, nextState) {
104 - return this.props.value.foo !== nextProps.value.foo;
105 -}
106 -```
107 -
108 -Basically, we ended up doing a deep comparison to make sure we properly track changes. In terms of performance, this approach is pretty expensive. It doesn't scale as we would have to write different deep equality code for each model. On top of that, it might not even work if we don't carefully manage object references. Say this component is used by a parent:
109 -
110 -```javascript
111 -React.createClass({
112 - getInitialState: function() {
113 - return { value: { foo: 'bar' } };
114 - },
115 -
116 - onClick: function() {
117 - var value = this.state.value;
118 - value.foo += 'bar'; // ANTI-PATTERN!
119 - this.setState({ value: value });
120 - },
121 -
122 - render: function() {
123 - return (
124 - <div>
125 - <InnerComponent value={this.state.value} />
126 - <a onClick={this.onClick}>Click me</a>
127 - </div>
128 - );
129 - }
130 -});
131 -```
132 -
133 -The first time the inner component gets rendered, it will have `{ foo: 'bar' }` as the value prop. If the user clicks on the anchor, the parent component's state will get updated to `{ value: { foo: 'barbar' } }`, triggering the re-rendering process of the inner component, which will receive `{ foo: 'barbar' }` as the new value for the prop.
134 -
135 -The problem is that since the parent and inner components share a reference to the same object, when the object gets mutated on line 2 of the `onClick` function, the prop the inner component had will change. So, when the re-rendering process starts, and `shouldComponentUpdate` gets invoked, `this.props.value.foo` will be equal to `nextProps.value.foo`, because in fact, `this.props.value` references the same object as `nextProps.value`.
136 -
137 -Consequently, since we'll miss the change on the prop and short circuit the re-rendering process, the UI won't get updated from `'bar'` to `'barbar'`.
138 -
139 -## Immutable-js to the rescue
140 -
141 -[Immutable-js](https://github.com/facebook/immutable-js) is a JavaScript collections library written by Lee Byron, which Facebook recently open-sourced. It provides *immutable persistent* collections via *structural sharing*. Let's see what these properties mean:
142 -
143 -* *Immutable*: once created, a collection cannot be altered at another point in time.
144 -* *Persistent*: new collections can be created from a previous collection and a mutation such as set. The original collection is still valid after the new collection is created.
145 -* *Structural Sharing*: new collections are created using as much of the same structure as the original collection as possible, reducing copying to a minimum to achieve space efficiency and acceptable performance. If the new collection is equal to the original, the original is often returned.
146 -
147 -Immutability makes tracking changes cheap; a change will always result in a new object so we only need to check if the reference to the object has changed. For example, in this regular JavaScript code:
148 -
149 -```javascript
150 -var x = { foo: "bar" };
151 -var y = x;
152 -y.foo = "baz";
153 -x === y; // true
154 -```
155 -
156 -Although `y` was edited, since it's a reference to the same object as `x`, this comparison returns `true`. However, this code could be written using immutable-js as follows:
157 -
158 -```javascript
159 -var SomeRecord = Immutable.Record({ foo: null });
160 -var x = new SomeRecord({ foo: 'bar' });
161 -var y = x.set('foo', 'baz');
162 -x === y; // false
163 -```
164 -
165 -In this case, since a new reference is returned when mutating `x`, we can safely assume that `x` has changed.
166 -
167 -Another possible way to track changes could be doing dirty checking by having a flag set by setters. A problem with this approach is that it forces you to use setters and, either write a lot of additional code, or somehow instrument your classes. Alternatively, you could deep copy the object just before the mutations and deep compare to determine whether there was a change or not. A problem with this approach is both deepCopy and deepCompare are expensive operations.
168 -
169 -So, Immutable data structures provides you a cheap and less verbose way to track changes on objects, which is all we need to implement `shouldComponentUpdate`. Therefore, if we model props and state attributes using the abstractions provided by immutable-js we'll be able to use `PureRenderMixin` and get a nice boost in perf.
170 -
171 -## Immutable-js and Flux
172 -
173 -If you're using [Flux](https://facebook.github.io/flux/), you should start writing your stores using immutable-js. Take a look at the [full API](https://facebook.github.io/immutable-js/docs/#/).
174 -
175 -Let's see one possible way to model the thread example using Immutable data structures. First, we need to define a `Record` for each of the entities we're trying to model. Records are just immutable containers that hold values for a specific set of fields:
176 -
177 -```javascript
178 -var User = Immutable.Record({
179 - id: undefined,
180 - name: undefined,
181 - email: undefined
182 -});
183 -
184 -var Message = Immutable.Record({
185 - timestamp: new Date(),
186 - sender: undefined,
187 - text: ''
188 -});
189 -```
190 -
191 -The `Record` function receives an object that defines the fields the object has and its default values.
192 -
193 -The messages *store* could keep track of the users and messages using two lists:
194 -
195 -```javascript
196 -this.users = Immutable.List();
197 -this.messages = Immutable.List();
198 -```
199 -
200 -It should be pretty straightforward to implement functions to process each *payload* type. For instance, when the store sees a payload representing a new message, we can just create a new record and append it to the messages list:
201 -
202 -```javascript
203 -this.messages = this.messages.push(new Message({
204 - timestamp: payload.timestamp,
205 - sender: payload.sender,
206 - text: payload.text
207 -});
208 -```
209 -
210 -Note that since the data structures are immutable, we need to assign the result of the push function to `this.messages`.
211 -
212 -On the React side, if we also use immutable-js data structures to hold the components' state, we could mix `PureRenderMixin` into all our components and short circuit the re-rendering process.
docs/docs/11-advanced-performance.zh-CN.md deleted
-212
@@ -1,212 +0,0 @@
1 ----
2 -id: advanced-performance-zh-CN
3 -title: 提高性能
4 -permalink: docs/advanced-performance-zh-CN.html
5 -prev: shallow-compare-zh-CN.html
6 -next: context-zh-CN.html
7 ----
8 -
9 -当人们考虑将React应用到自己的系统里时,都会想知道React是否可以和非React的应用一样可以快速的响应各种用户的操作。改变组件的state时,它会重新渲染组件的所有子节点,有人会怀疑这种重新渲染会带来很大的性能开销。但是React使用很多技术来最小化的减少DOM操作的开销达到更新UI的效果。
10 -
11 -## 使用生产构建版本
12 -
13 -如果你在开发React应用中,遇到了一些性能上的问题,你可以使用了[minified production build](/react/downloads.html)进行测试。这个开发构建版本包括了额外的一些警告信息,可以帮助你更好的调试你的应用。由于它做了很多额外的开销,所以它运行起来会相对要慢一点。
14 -
15 -## 避免调整真实DOM树
16 -
17 -React利用*虚拟DOM*,来描述在浏览器上显示的真实DOM树。这种并行的表示方法,可以让React避免直接去操作DOM节点,毕竟操作DOM节点的开销要远远大于直接去操作Javascript的对象。当组件的state或者props更新的时候,React会根据新生成的虚拟DOM和之前的虚拟DOM进行比较,来判断是否需要去更新真实DOM上的内容。只有在前后虚拟DOM不相等的情况下,React才会去[调整](/react/docs/reconciliation.html)真实DOM的结构。
18 -
19 -在此之上,React提供了一个组件生命周期函数`shouldComponentUpdate`,它会在组件进行重渲染过程开始的时候(虚拟DOM和真实DOM进行对比)进行调用。让开发者可以短接这个过程。该函数默认会返回`true`,让React去执行更新。
20 -
21 -```javascript
22 -shouldComponentUpdate: function(nextProps, nextState) {
23 - return true;
24 -}
25 -```
26 -
27 -记住一点,在React中,这个函数调用的非常频繁,所以里面的操作不能太复杂,一定要快。
28 -
29 -你有几个聊天对话的消息应用程序。假设只有一个对话改变了。如果你在`ChatThread`组件中实现了`shouldComponentUpdate`函数,React可以跳过对其他线程的重渲染的步骤。
30 -
31 -```javascript
32 -shouldComponentUpdate: function(nextProps, nextState) {
33 - // TODO: return whether or not current chat thread is
34 - // different to former one.
35 -}
36 -```
37 -
38 -所以,总而言之,React可以让开发者使用`shouldComponentUpdate`函数来减少对DOM子树的调整,对于那些需要更新的组件,再进行虚拟DOMs的对比。
39 -
40 -## shouldComponentUpdate 实战
41 -
42 -这个一个组件的子树的结构。每一个节点表示`shouldComponentUpdate` return了什么,以及是否虚拟DOMs是相等的。最后,圆的颜色代表这个节点是否需要被重新调整。
43 -
44 -<figure><img src="/react/img/docs/should-component-update.png" /></figure>
45 -
46 -在上述例子中,C2节点的`shouldComponentUpdate`函数返回了`false`,所以React就不需要在这里产生新的虚拟DOM,也就不需要重新调整DOM。由于父节点C2已经在`shouldComponentUpdate`函数中返回`false`,所以它的所有子节点也就不会执行该函数。
47 -
48 -对于C1和C3,`shouldComponentUpdate`函数返回了`true`,React会从上往下对子节点进行检查。对于C6节点,它返回了`true`;由于前后的虚拟DOMs不相等,所以它不得不调整真实DOM。最后在C8这个有趣的节点上。React会去对比前后虚拟DOM,由于前后是相等的,所以它不是对真实DOM进行调整。
49 -
50 -请注意,React只会对C6进行DOM操作。对于C8,它通过对比虚拟DOMs的方式,避免重新渲染。对于C2的子节点以及C7,通过`shouldComponentUpdate`函数,直接忽略了虚拟DOM比较的过程,提高性能。
51 -
52 -所以,我们应该怎么样来实现`shouldComponentUpdate`方法?举个例子,你有个组件仅仅只渲染一个string的文案:
53 -
54 -```javascript
55 -React.createClass({
56 - propTypes: {
57 - value: React.PropTypes.string.isRequired
58 - },
59 -
60 - render: function() {
61 - return <div>{this.props.value}</div>;
62 - }
63 -});
64 -```
65 -
66 -我们可以简单的像下面一样实现`shouldComponentUpdate`
67 -
68 -```javascript
69 -shouldComponentUpdate: function(nextProps, nextState) {
70 - return this.props.value !== nextProps.value;
71 -}
72 -```
73 -
74 -目前为止,在props/state上处理简单的的数据结构是非常容易的。基于这种数据类型,我们可以通过mixin的方式把该函数引入到你的所有组件中去。事实上,React官方已经提供了这种方法:[PureRenderMixin](/react/docs/pure-render-mixin.html)。
75 -
76 -但是,如果你的组件使用的在state或者props上使用的是可变的数据结构怎么办?组件里的prop不是以一个string的形式`'bar'`存在,而是以一种Javascript对象的形式包含了一个字符串,类似这样`{ foo: 'bar' }`:
77 -
78 -```javascript
79 -React.createClass({
80 - propTypes: {
81 - value: React.PropTypes.object.isRequired
82 - },
83 -
84 - render: function() {
85 - return <div>{this.props.value.foo}</div>;
86 - }
87 -});
88 -```
89 -
90 -如果是这种情况,按照我们刚才的在`shouldComponentUpdate`的实现的话,是不能达到我们的预期:
91 -
92 -```javascript
93 -// assume this.props.value is { foo: 'bar' }
94 -// assume nextProps.value is { foo: 'bar' },
95 -// but this reference is different to this.props.value
96 -this.props.value !== nextProps.value; // true
97 -```
98 -
99 -因为props实际上是没有改变的,所以`shouldComponentUpdate`始终会返回`true`。为了解决这个问题,我们也有一个可选的解决方案:
100 -
101 -```javascript
102 -shouldComponentUpdate: function(nextProps, nextState) {
103 - return this.props.value.foo !== nextProps.value.foo;
104 -}
105 -```
106 -
107 -基本上,我们是不会利用这种深度比较去判断是否有属性改变。这样的操作十分损耗性能的,并且非常难扩展。最重要的是,如果我们没有仔细管理对象的引用关系,很可能导致对比不出结果。让我们来看看下面这个组件:
108 -
109 -```javascript
110 -React.createClass({
111 - getInitialState: function() {
112 - return { value: { foo: 'bar' } };
113 - },
114 -
115 - onClick: function() {
116 - var value = this.state.value;
117 - value.foo += 'bar'; // ANTI-PATTERN!
118 - this.setState({ value: value });
119 - },
120 -
121 - render: function() {
122 - return (
123 - <div>
124 - <InnerComponent value={this.state.value} />
125 - <a onClick={this.onClick}>Click me</a>
126 - </div>
127 - );
128 - }
129 -});
130 -```
131 -
132 -子组件第一次渲染的时候,组件会收到`{ foo: 'bar' }`作为prop中的value的值。如果用户进行了点击的操作,父组件为更新state,变为`{ value: { foo: 'barbar' } }`,之后会触发子组件的重渲染的过程,子组件会收到新的prop中value的值`{ foo: 'barbar' }`。
133 -
134 -问题在与,因为父子组件共同分享了一个对象的引用,当这个对象在`onClick`函数中进行修改后,子组件的prop也已经改变。所以,当重渲染的过程开始,`shouldComponentUpdate`函数就会被触发,`this.props.value.foo` 与`nextProps.value.foo`会是相等的。因为`this.props.value`和`nextProps.value`指向的是同一个对象。
135 -
136 -因此,我们直接阻止了子组件进行重新渲染,整个UI也就不会把`'bar'`更新为`'barbar'`。
137 -
138 -## 使用Immutable-js
139 -
140 -[Immutable-js](https://github.com/facebook/immutable-js)是一个由Lee Byron编写的Javascript的数据类型库,现在已经被Facebook开源了。它通过 *结构共享* 的方式提供了一个 *持久不可变的* 的集合。让我们来看看这个到底是什么东西。
141 -
142 -* *不可变*:一旦被创建,一个集合不能被其他内容所改变
143 -* *持久性*:新的集合可以由之前的集合创建出来,或者由一个可变的数据创建。当新的集合被创建出来,原始的集合依然有效。
144 -* *结构共享*:新的集合会尽可能的复用之前集合内的内容。减少重复复制来提高性能。如果新集合和原来的集合是相等的,则会直接把之前的集合返回给新集合。
145 -
146 -不可变的特性让跟踪变化变得简单;每次改变总是会产生新的一个对象,所以。我们只需要判断一下它们引用是否相同即可。举个例子,下面是常规的Javascript的写法:
147 -
148 -```javascript
149 -var x = { foo: "bar" };
150 -var y = x;
151 -y.foo = "baz";
152 -x === y; // true
153 -```
154 -
155 -尽管`y`已经被更改了,但是它的引用还是和`x`是一致的。所以他们两个进行对比,始终会返回`true`。所以,这样的操作应该要用`immutable-js `来完成:
156 -
157 -```javascript
158 -var SomeRecord = Immutable.Record({ foo: null });
159 -var x = new SomeRecord({ foo: 'bar' });
160 -var y = x.set('foo', 'baz');
161 -x === y; // false
162 -```
163 -
164 -在这样的情况中,当我们改变了x里的内容,会返回给我们一个新的引用,我们可以安全地假定`x`已经改变。
165 -
166 -另一种来跟踪数据变化的方法,是通过 setter 来设置标识符来做脏检查 (dirty checking)。这种方法的问题在于它强迫你使用 setter;你需要多写很多额外代码或者跟踪分析 class 中的数据。另外一种方式是,你可以在更改一个对象之前对它进行一次深复制,之后再进行深比较,来判断这次操作是否造成了数据改变:这种方案的问题在于深复制与深比较都是很昂贵的操作。
167 -
168 -所以,Immutable的数据结构给你提供了一个很方便的方式去跟踪一个对象是否被修改了,我们只需要简单的实现`shouldComponentUpdate`即可。因此,如果我们的props和state模型使用了immutable-js方式,我们可以引入`PureRenderMixin`,从而提高我们的应用的性能。
169 -
170 -## Immutable-js 结合 Flux
171 -
172 -如果你正在使用[Flux](https://facebook.github.io/flux/),你应该在你的stores里使用immutable-js。可以来看下[full API](https://facebook.github.io/immutable-js/docs/#/)。
173 -
174 -让我们看看一种使用Immutable数据结构来处理的方式。首先,我们为每一个入口定义一个`Record`去处理模型。`Record`是一个保存各个字段的一个容器。
175 -
176 -```javascript
177 -var User = Immutable.Record({
178 - id: undefined,
179 - name: undefined,
180 - email: undefined
181 -});
182 -
183 -var Message = Immutable.Record({
184 - timestamp: new Date(),
185 - sender: undefined,
186 - text: ''
187 -});
188 -```
189 -
190 -Record 函数接受一个对象作为参数;这个对象定义了 Record 中的键值与默认值
191 -
192 -*store*可以用两个list来记录users和messages
193 -
194 -
195 -```javascript
196 -this.users = Immutable.List();
197 -this.messages = Immutable.List();
198 -```
199 -
200 -它可以很方便的实现处理*payload*数据类型。例如,当一个store收到了新的信息,我们可以直接创建一个新的record,然后把它加到我们message的list中去。
201 -
202 -```javascript
203 -this.messages = this.messages.push(new Message({
204 - timestamp: payload.timestamp,
205 - sender: payload.sender,
206 - text: payload.text
207 -});
208 -```
209 -
210 -注意,因为data的数据结构是不可变的,我们需要重新对`this.message`进行赋值。
211 -
212 -在React方面,如果我们用了 `immutable-js`的数据结构去保存组件的state,我们就可以引入`PureRenderMixin`到所有你的组件中,做一个快速的判断是否需要重新渲染的操作。
docs/docs/12-context.ko-KR.md deleted
-174
@@ -1,174 +0,0 @@
1 ----
2 -id: context
3 -title: 컨텍스트
4 -permalink: docs/context-ko-KR.html
5 -prev: advanced-performance-ko-KR.html
6 ----
7 -
8 -React의 가장 큰 장점 중 하나는 React 컴포넌트를 통해 데이터의 흐름을 추적하기 쉽다는 것입니다. 컴포넌트를 보면 각각의 프로퍼티가 어떻게 전달되었는지 쉽게 파악할 수 있습니다.
9 -
10 -때때로 컴포넌트 트리를 통해 props을 전단하는 대신 수동으로 모든 레벨에서 데이터를 전달하고 싶은 경우가 있습니다. React의 "컨텍스트" 기능은 이를 가능하게 해줍니다.
11 -
12 -
13 -> 주의:
14 ->
15 -> 컨텍스트는 실험적인 고급 기능입니다. 향후 릴리즈에서 API가 변경될 수 있습니다.
16 ->
17 -> 대부분은 애플리켄이션은 컨텍스트가 필요하지 않을겁니다. 특히 React로 시작한 경우에는 컨텍스트를 사용하지 않을겁니다. 컨텍스트의 사용은 데이터 흐름을 명확하지 않게 만들기 때문에 코드를 이해하기 어려워 집니다. 이는 마치 앱에서 전역 변수를 state로 전달하는 경우와 유사합니다.
18 ->
19 -> **만약 컨텍스트를 사용해야 하는 경우에도, 가능한 아껴 사용하세요.**
20 ->
21 -> 구축하는것이 애플리케이션이든 라이브러리든간에, 가능한 컨텍스트의 사용은 작은 영역으로 격리하고 직접적으로 컨텍스트 API를 사용하는 것을 피하세요. 그렇게 하면 API가 변경 되더라도 쉽게 업데이트 할 수 있습니다.
22 -
23 -## 트리를 통해 정보를 자동으로 전달하기
24 -
25 -아래와 같은 구조가 있다고 가정해 봅시다:
26 -
27 -```javascript
28 -var Button = React.createClass({
29 - render: function() {
30 - return (
31 - <button style={{'{{'}}background: this.props.color}}>
32 - {this.props.children}
33 - </button>
34 - );
35 - }
36 -});
37 -
38 -var Message = React.createClass({
39 - render: function() {
40 - return (
41 - <div>
42 - {this.props.text} <Button color={this.props.color}>삭제</Button>
43 - </div>
44 - );
45 - }
46 -});
47 -
48 -var MessageList = React.createClass({
49 - render: function() {
50 - var color = "purple";
51 - var children = this.props.messages.map(function(message) {
52 - return <Message text={message.text} color={color} />;
53 - });
54 - return <div>{children}</div>;
55 - }
56 -});
57 -```
58 -
59 -이 예제에서, 우리는 스타일을 주기 위해 수동으로 적절하게 `Button`과 `Messages` 컴포넌트에 `color` 프로퍼티를 엮어서 전달했습니다. 테마는 서브트리가 정보 조각의 일부(여기선 color)에 접근하기 원하는 좋은 예제입니다. 컨텍스트를 사용하면 우리는 이를 자동으로 트리로 전달할 수 있습니다:
60 -
61 -```javascript{2-4,7,18,25-30,33}
62 -var Button = React.createClass({
63 - contextTypes: {
64 - color: React.PropTypes.string
65 - },
66 - render: function() {
67 - return (
68 - <button style={{'{{'}}background: this.context.color}}>
69 - {this.props.children}
70 - </button>
71 - );
72 - }
73 -});
74 -
75 -var Message = React.createClass({
76 - render: function() {
77 - return (
78 - <div>
79 - {this.props.text} <Button>Delete</Button>
80 - </div>
81 - );
82 - }
83 -});
84 -
85 -var MessageList = React.createClass({
86 - childContextTypes: {
87 - color: React.PropTypes.string
88 - },
89 - getChildContext: function() {
90 - return {color: "purple"};
91 - },
92 - render: function() {
93 - var children = this.props.messages.map(function(message) {
94 - return <Message text={message.text} />;
95 - });
96 - return <div>{children}</div>;
97 - }
98 -});
99 -```
100 -
101 -`childContextTypes`와 `getChildContext`를 `MessageList`(context provider)에 추가함으로써, React는 정보를 자동으로 아래로 전달하며 서브트리내의 어떤 컴포넌트든 (여기선 `Button`) `contextTypes`를 정의함으로써 이에 접근할 수 있습니다.
102 -
103 -`contextTypes`가 정의되지 않은 경우, `this.context`는 빈 오브젝트가 됩니다.
104 -
105 -## 부모-자식 커플링
106 -
107 -컨텍스트는 다음과 같은 API를 구성할 수 있게 해줍니다:
108 -
109 -```javascript
110 -<Menu>
111 - <MenuItem>가지</MenuItem>
112 - <MenuItem>땅콩호박</MenuItem>
113 - <MenuItem>클레멘타인</MenuItem>
114 -</Menu>
115 -```
116 -
117 -`Menu` 컴포넌트에서 관련 정보를 전달함으로써 각각의 `MenuItem`가 부모인 `Menu` 컴포넌트와 통신할 수 있습니다.
118 -
119 -**이 API를 이용해 컴포넌트를 구성하기 전에, 깔끔한 대안이 있는지 먼저 고려해 보세요.** 다음과 같이 간단히 아이템을 배열로 넘겨 보겠습니다:
120 -
121 -```javascript
122 -<Menu items={['가지', '땅콩호박', '클레멘타인']} />
123 -```
124 -
125 -원한다면 전체 React 컴포넌트를 프로퍼티로 전달할 수도 있습니다.
126 -
127 -## Referencing context in lifecycle methods
128 -
129 -If `contextTypes` is defined within a component, the following lifecycle methods will receive an additional parameter, the `context` object:
130 -
131 -```javascript
132 -void componentWillReceiveProps(
133 - object nextProps, object nextContext
134 -)
135 -
136 -boolean shouldComponentUpdate(
137 - object nextProps, object nextState, object nextContext
138 -)
139 -
140 -void componentWillUpdate(
141 - object nextProps, object nextState, object nextContext
142 -)
143 -
144 -void componentDidUpdate(
145 - object prevProps, object prevState, object prevContext
146 -)
147 -```
148 -
149 -## Referencing context in stateless functional components
150 -
151 -Stateless functional components are also able to reference `context` if `contextTypes` is defined as a property of the function. The following code shows the `Button` component above written as a stateless functional component.
152 -
153 -```javascript
154 -function Button(props, context) {
155 - return (
156 - <button style={{'{{'}}background: context.color}}>
157 - {props.children}
158 - </button>
159 - );
160 -}
161 -Button.contextTypes = {color: React.PropTypes.string};
162 -```
163 -
164 -## 컨텍스트를 사용하지 말아야 하는 경우
165 -
166 -대부분의 경우, 깔끔한 코드를 위해 전역 변수를 피하는 것과 마찬가지로 컨텍스트의 사용을 피해야 합니다. 특히 "타이핑을 줄이거나" 명시적인 프로퍼티 전달 대신 이를 사용하려는 경우 다시 한번 생각해 보세요.
167 -
168 -컨텍스트의 가장 적절한 사용 사례는 로그인한 유저, 언어 설정, 테마 정보 등을 암시적으로 전달하는 것입니다. 컨텍스트를 사용함으로써 이런 정보들을 전역으로 다루는 대신 단일 React 서브트리 내에서 다룰 수 있습니다.
169 -
170 -모델 데이터를 컴포넌트로 전달하는데 컨텍스트를 사용하지 마세요. 트리를 통해 명시적으로 데이터를 엮어 전달하는 것이 훨씬 이해하기 쉽습니다. 컨텍스트는 렌더되는 위치에 따라 다르게 작동하기 때문에 컴포넌트를 더욱 연결되고(coupled) 재사용성이 떨어지게 만듭니다.
171 -
172 -## 알려진 한계점
173 -
174 -컴포넌트에 의해 제공되는 컨텍스트의 값이 변경될 때, 중간 부모가 `shouldComponentUpdate`에서`false`을 반환한다면 그 값을 사용하는 자손은 업데이트되지 않습니다. 자세한 내용은 [#2517](https://github.com/facebook/react/issues/2517) 이슈를 확인하세요.
docs/docs/12-context.zh-CN.md deleted
-205
@@ -1,205 +0,0 @@
1 ----
2 -id: context-zh-CN
3 -title: Context
4 -permalink: docs/context-zh-CN.html
5 -prev: advanced-performance-zh-CN.html
6 ----
7 -
8 -React优势之一是你可以很容易地从React组件里跟踪数据流动。当你查看一个组件时,你可以很容易地判断出传入了哪些props,而这也有利于你的App进行逻辑推断。
9 -
10 -有时,你想不通过在每一级组件设置prop的方式来向组件树内传递数据。那么,React的"context"特性可以让你做到这点。
11 -
12 -> 注意:
13 ->
14 -> Context是一个先进的实验性特性,这个API很可能在未来版本变化。
15 ->
16 -> 大多数应用将不会需要用到context。尤其是如果你刚开始用React,你很可能不会想用它。使用context将会使你的代码难以理解,因为它让数据流变得不清晰。它类似于在你的应用里用以传递state的全局变量。
17 ->
18 -> **如果你必须使用context,请保守地使用它。**
19 ->
20 -> 不论你正在创建一个应用或者是库,试着缩小context的使用范围,并尽可能避免直接使用context相关API,以便在API变动时容易升级。
21 -
22 -## 在组件树内自动传递info
23 -
24 -假设你有一个这样的结构:
25 -
26 -```javascript
27 -var Button = React.createClass({
28 - render: function() {
29 - return (
30 - <button style={{'{{'}}background: this.props.color}}>
31 - {this.props.children}
32 - </button>
33 - );
34 - }
35 -});
36 -
37 -var Message = React.createClass({
38 - render: function() {
39 - return (
40 - <div>
41 - {this.props.text} <Button color={this.props.color}>Delete</Button>
42 - </div>
43 - );
44 - }
45 -});
46 -
47 -var MessageList = React.createClass({
48 - render: function() {
49 - var color = "purple";
50 - var children = this.props.messages.map(function(message) {
51 - return <Message text={message.text} color={color} />;
52 - });
53 - return <div>{children}</div>;
54 - }
55 -});
56 -```
57 -
58 -在这个例子里,我们手工传递一个叫`color`的prop,以便于给`Button`和`Message`组件添加合适的样式。当你想所有子组件可以访问一部分信息时(比如color),上面的设置主题是一个很好的例子。通过使用context,我们能自动在组件树中传递信息:
59 -
60 -```javascript{2-4,7,18,25-30,33}
61 -var Button = React.createClass({
62 - contextTypes: {
63 - color: React.PropTypes.string
64 - },
65 - render: function() {
66 - return (
67 - <button style={{'{{'}}background: this.context.color}}>
68 - {this.props.children}
69 - </button>
70 - );
71 - }
72 -});
73 -
74 -var Message = React.createClass({
75 - render: function() {
76 - return (
77 - <div>
78 - {this.props.text} <Button>Delete</Button>
79 - </div>
80 - );
81 - }
82 -});
83 -
84 -var MessageList = React.createClass({
85 - childContextTypes: {
86 - color: React.PropTypes.string
87 - },
88 - getChildContext: function() {
89 - return {color: "purple"};
90 - },
91 - render: function() {
92 - var children = this.props.messages.map(function(message) {
93 - return <Message text={message.text} />;
94 - });
95 - return <div>{children}</div>;
96 - }
97 -});
98 -```
99 -
100 -通过添加`childContextTypes`和`getChildContext`到 `MessageList`(context提供者),React会自动下传信息,并且通过定义`contextTypes`,子树中的任何组件(在这个例子中,子组件是`Button`)可以访问`context`。
101 -
102 -如果`contextTypes`没有定义,那么`this.context`将是一个空对象。
103 -
104 -## 父子耦合
105 -
106 -Context同样可以使你构建这样的API:
107 -
108 -```javascript
109 -<Menu>
110 - <MenuItem>aubergine</MenuItem>
111 - <MenuItem>butternut squash</MenuItem>
112 - <MenuItem>clementine</MenuItem>
113 -</Menu>
114 -```
115 -
116 -通过在`Menu`组件内下传相关的信息,每个`MenuItem` 可以与包含他们的`Menu`组件沟通。
117 -
118 -**在你用这个API构建组件以前,考虑一下是否有清晰的替代方案** 我们喜欢用数组传递items,就像下面这样:
119 -
120 -```javascript
121 -<Menu items={['aubergine', 'butternut squash', 'clementine']} />
122 -```
123 -
124 -记住,如果你愿意,你同样可以在props里传递整个React组件。
125 -
126 -## 在生命周期方法里引用context
127 -
128 -如果`contextTypes`是定义在一个组件中,接下来的生命周期方法会收到一个额外的参数,`context`对象:
129 -
130 -```javascript
131 -void componentWillReceiveProps(
132 - object nextProps, object nextContext
133 -)
134 -
135 -boolean shouldComponentUpdate(
136 - object nextProps, object nextState, object nextContext
137 -)
138 -
139 -void componentWillUpdate(
140 - object nextProps, object nextState, object nextContext
141 -)
142 -
143 -void componentDidUpdate(
144 - object prevProps, object prevState, object prevContext
145 -)
146 -```
147 -
148 -## 在无状态函数组件里引用 context
149 -
150 -如果 `contextTypes` 被定义为函数的属性,无状态函数同样能够引用`context`。下面的代码展示了被写为无状态函数组件的`Button`组件:
151 -
152 -```javascript
153 -function Button(props, context) {
154 - return (
155 - <button style={{'{{'}}background: context.color}}>
156 - {props.children}
157 - </button>
158 - );
159 -}
160 -Button.contextTypes = {color: React.PropTypes.string};
161 -```
162 -
163 -## 更新context
164 -
165 -当state或props改变时,会调用`getChildContext`方法。为了能更新context内的数据,需要使用`this.setState`来触发组件state更新。这将会触发一个新的context,并且子组件也能接收变化。
166 -
167 -```javascript
168 -var MediaQuery = React.createClass({
169 - getInitialState: function(){
170 - return {type:'desktop'};
171 - },
172 - childContextTypes: {
173 - type: React.PropTypes.string
174 - },
175 - getChildContext: function() {
176 - return {type: this.state.type};
177 - },
178 - componentDidMount: function(){
179 - var checkMediaQuery = function(){
180 - var type = window.matchMedia("(min-width: 1025px)").matches ? 'desktop' : 'mobile';
181 - if (type !== this.state.type){
182 - this.setState({type:type});
183 - }
184 - };
185 -
186 - window.addEventListener('resize', checkMediaQuery);
187 - checkMediaQuery();
188 - },
189 - render: function(){
190 - return this.props.children;
191 - }
192 -});
193 -```
194 -
195 -## 什么时候不用 context
196 -
197 -正如在写清晰代码时最好要避免使用全局变量一样,在大多数情况下,你应该避免使用context。特别是,在用它来"节省输入"和代替显式传入props时要三思。
198 -
199 -隐式传入登录的用户,当前的语言,或者主题信息,是context最好的使用场景。要不然所有这些可能就是全局变量,但是context让你限定他们到一个单独的React树里。
200 -
201 -在组件里传递你的模型数据时,不要依赖context。在组件树内显式传递数据,会更容易令人理解。之所以使用context会增加组件耦合度以及降低复用性,是因为组件在不同的地方渲染时,他们会表现出不同的行为。
202 -
203 -## 已知的限制
204 -
205 -假设由父组件提供的context值发生变动,但中间父级组件的`shouldComponentUpdate`返回了`false`,那么后代子级不会更新context。详见 issue [#2517](https://github.com/facebook/react/issues/2517) 。
docs/docs/addons-animation.md renamed
+147 -88
@@ -1,24 +1,28 @@
1 ---
2 id: animation
3 -title: Animation
3 +title: Animation Add-Ons
4 permalink: docs/animation.html
5 +layout: docs
6 +category: Add-Ons
7 prev: addons.html
6 -next: two-way-binding-helpers.html
8 +next: create-fragment.html
9 ---
10
9 -React provides a `ReactTransitionGroup` add-on component as a low-level API for animation, and a `ReactCSSTransitionGroup` for easily implementing basic CSS animations and transitions.
11 +The [`ReactTransitionGroup`](#reacttransitiongroup) add-on component is a low-level API for animation, and [`ReactCSSTransitionGroup`](#reactcsstransitiongroup) is an add-on component for easily implementing basic CSS animations and transitions.
12
11 -## High-level API: `ReactCSSTransitionGroup`
13 +## High-level API: ReactCSSTransitionGroup
14
13 -`ReactCSSTransitionGroup` is based on `ReactTransitionGroup` and is an easy way to perform CSS transitions and animations when a React component enters or leaves the DOM. It's inspired by the excellent [ng-animate](http://www.nganimate.org/) library.
15 +`ReactCSSTransitionGroup` is a high-level API based on [`ReactTransitionGroup`](#low-level-api-reacttransitiongroup) and is an easy way to perform CSS transitions and animations when a React component enters or leaves the DOM. It's inspired by the excellent [ng-animate](http://www.nganimate.org/) library.
16
15 -### Getting Started
17 +**Importing**
18
17 -`ReactCSSTransitionGroup` is the interface to `ReactTransitions`. This is a simple element that wraps all of the components you are interested in animating. Here's an example where we fade list items in and out.
18 -
19 -```javascript{33-38}
20 -var ReactCSSTransitionGroup = require('react-addons-css-transition-group');
19 +```javascript
20 +import ReactCSSTransitionGroup from 'react-addons-css-transition-group' // ES6
21 +var ReactCSSTransitionGroup = require('react-addons-css-transition-group') // ES5 with npm
22 +var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup; // ES5 with react-with-addons.js
23 +```
24
25 +```javascript{31-36}
26 class TodoList extends React.Component {
27 constructor(props) {
28 super(props);
@@ -49,9 +53,9 @@ class TodoList extends React.Component {
53 return (
54 <div>
55 <button onClick={this.handleAdd}>Add Item</button>
52 - <ReactCSSTransitionGroup
53 - transitionName="example"
54 - transitionEnterTimeout={500}
56 + <ReactCSSTransitionGroup
57 + transitionName="example"
58 + transitionEnterTimeout={500}
59 transitionLeaveTimeout={300}>
60 {items}
61 </ReactCSSTransitionGroup>
@@ -96,16 +100,16 @@ You'll notice that animation durations need to be specified in both the CSS and
100 `ReactCSSTransitionGroup` provides the optional prop `transitionAppear`, to add an extra transition phase at the initial mount of the component. There is generally no transition phase at the initial mount as the default value of `transitionAppear` is `false`. The following is an example which passes the prop `transitionAppear` with the value `true`.
101
102 ```javascript{5-6}
99 - render() {
100 - return (
101 - <ReactCSSTransitionGroup
102 - transitionName="example"
103 - transitionAppear={true}
104 - transitionAppearTimeout={500}>
105 - <h1>Fading at Initial Mount</h1>
106 - </ReactCSSTransitionGroup>
107 - );
108 - }
103 +render() {
104 + return (
105 + <ReactCSSTransitionGroup
106 + transitionName="example"
107 + transitionAppear={true}
108 + transitionAppearTimeout={500}>
109 + <h1>Fading at Initial Mount</h1>
110 + </ReactCSSTransitionGroup>
111 + );
112 +}
113 ```
114
115 During the initial mount `ReactCSSTransitionGroup` will get the `example-appear` CSS class and the `example-appear-active` CSS class added in the next tick.
@@ -132,28 +136,28 @@ At the initial mount, all children of the `ReactCSSTransitionGroup` will `appear
136 It is also possible to use custom class names for each of the steps in your transitions. Instead of passing a string into transitionName you can pass an object containing either the `enter` and `leave` class names, or an object containing the `enter`, `enter-active`, `leave-active`, and `leave` class names. If only the enter and leave classes are provided, the enter-active and leave-active classes will be determined by appending '-active' to the end of the class name. Here are two examples using custom classes:
137
138 ```javascript
135 - ...
136 - <ReactCSSTransitionGroup
137 - transitionName={ {
138 - enter: 'enter',
139 - enterActive: 'enterActive',
140 - leave: 'leave',
141 - leaveActive: 'leaveActive',
142 - appear: 'appear',
143 - appearActive: 'appearActive'
144 - } }>
145 - {item}
146 - </ReactCSSTransitionGroup>
147 -
148 - <ReactCSSTransitionGroup
149 - transitionName={ {
150 - enter: 'enter',
151 - leave: 'leave',
152 - appear: 'appear'
153 - } }>
154 - {item2}
155 - </ReactCSSTransitionGroup>
156 - ...
139 +// ...
140 +<ReactCSSTransitionGroup
141 + transitionName={ {
142 + enter: 'enter',
143 + enterActive: 'enterActive',
144 + leave: 'leave',
145 + leaveActive: 'leaveActive',
146 + appear: 'appear',
147 + appearActive: 'appearActive'
148 + } }>
149 + {item}
150 +</ReactCSSTransitionGroup>
151 +
152 +<ReactCSSTransitionGroup
153 + transitionName={ {
154 + enter: 'enter',
155 + leave: 'leave',
156 + appear: 'appear'
157 + } }>
158 + {item2}
159 +</ReactCSSTransitionGroup>
160 +// ...
161 ```
162
163 ### Animation Group Must Be Mounted To Work
@@ -163,22 +167,22 @@ In order for it to apply transitions to its children, the `ReactCSSTransitionGro
167 The example below would **not** work, because the `ReactCSSTransitionGroup` is being mounted along with the new item, instead of the new item being mounted within it. Compare this to the [Getting Started](#getting-started) section above to see the difference.
168
169 ```javascript{4,6,13}
166 - render() {
167 - var items = this.state.items.map((item, i) => (
168 - <div key={item} onClick={() => this.handleRemove(i)}>
169 - <ReactCSSTransitionGroup transitionName="example">
170 - {item}
171 - </ReactCSSTransitionGroup>
172 - </div>
173 - ));
170 +render() {
171 + var items = this.state.items.map((item, i) => (
172 + <div key={item} onClick={() => this.handleRemove(i)}>
173 + <ReactCSSTransitionGroup transitionName="example">
174 + {item}
175 + </ReactCSSTransitionGroup>
176 + </div>
177 + ));
178
175 - return (
176 - <div>
177 - <button onClick={this.handleAdd}>Add Item</button>
178 - {items}
179 - </div>
180 - );
181 - }
179 + return (
180 + <div>
181 + <button onClick={this.handleAdd}>Add Item</button>
182 + {items}
183 + </div>
184 + );
185 +}
186 ```
187
188 ### Animating One or Zero Items
@@ -186,7 +190,7 @@ The example below would **not** work, because the `ReactCSSTransitionGroup` is b
190 In the example above, we rendered a list of items into `ReactCSSTransitionGroup`. However, the children of `ReactCSSTransitionGroup` can also be one or zero items. This makes it possible to animate a single element entering or leaving. Similarly, you can animate a new element replacing the current element. For example, we can implement a simple image carousel like this:
191
192 ```javascript{10}
189 -var ReactCSSTransitionGroup = require('react-addons-css-transition-group');
193 +import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
194
195 function ImageCarousel(props) {
196 return (
@@ -210,41 +214,34 @@ You can disable animating `enter` or `leave` animations if you want. For example
214 >
215 > When using `ReactCSSTransitionGroup`, there's no way for your components to be notified when a transition has ended or to perform any more complex logic around animation. If you want more fine-grained control, you can use the lower-level `ReactTransitionGroup` API which provides the hooks you need to do custom transitions.
216
213 -## Low-level API: `ReactTransitionGroup`
214 -
215 -`ReactTransitionGroup` is the basis for animations. It is accessible from `require('react-addons-transition-group')`. When children are declaratively added or removed from it (as in the example above) special lifecycle hooks are called on them.
217 +* * *
218
217 -### `componentWillAppear(callback)`
219 +## Low-level API: ReactTransitionGroup
220
219 -This is called at the same time as `componentDidMount()` for components that are initially mounted in a `TransitionGroup`. It will block other animations from occurring until `callback` is called. It is only called on the initial render of a `TransitionGroup`.
220 -
221 -### `componentDidAppear()`
221 +**Importing**
222
223 -This is called after the `callback` function that was passed to `componentWillAppear` is called.
224 -
225 -### `componentWillEnter(callback)`
226 -
227 -This is called at the same time as `componentDidMount()` for components added to an existing `TransitionGroup`. It will block other animations from occurring until `callback` is called. It will not be called on the initial render of a `TransitionGroup`.
228 -
229 -### `componentDidEnter()`
230 -
231 -This is called after the `callback` function that was passed to `componentWillEnter` is called.
232 -
233 -### `componentWillLeave(callback)`
234 -
235 -This is called when the child has been removed from the `ReactTransitionGroup`. Though the child has been removed, `ReactTransitionGroup` will keep it in the DOM until `callback` is called.
223 +```javascript
224 +import ReactTransitionGroup from 'react-addons-transition-group' // ES6
225 +var ReactTransitionGroup = require('react-addons-transition-group') // ES5 with npm
226 +var ReactTransitionGroup = React.addons.TransitionGroup; // ES5 with react-with-addons.js
227 +```
228
237 -### `componentDidLeave()`
229 +`ReactTransitionGroup` is the basis for animations. When children are declaratively added or removed from it (as in the [example above](#getting-started)), special lifecycle hooks are called on them.
230
239 -This is called when the `willLeave` `callback` is called (at the same time as `componentWillUnmount`).
231 + - [`componentWillAppear()`](#componentwillappear)
232 + - [`componentDidAppear()`](#componentdidappear)
233 + - [`componentWillEnter()`](#componentwillenter)
234 + - [`componentDidEnter()`](#componentdidenter)
235 + - [`componentWillLeave()`](#componentwillleave)
236 + - [`componentDidLeave()`](#componentdidleave)
237
241 -### Rendering a Different Component
238 +#### Rendering a Different Component
239
243 -By default `ReactTransitionGroup` renders as a `span`. You can change this behavior by providing a `component` prop. For example, here's how you would render a `<ul>`:
240 +`ReactTransitionGroup` renders as a `span` by default. You can change this behavior by providing a `component` prop. For example, here's how you would render a `<ul>`:
241
242 ```javascript{1}
243 <ReactTransitionGroup component="ul">
247 - ...
244 + {/* ... */}
245 </ReactTransitionGroup>
246 ```
247
@@ -252,13 +249,13 @@ Any additional, user-defined, properties will become properties of the rendered
249
250 ```javascript{1}
251 <ReactTransitionGroup component="ul" className="animated-list">
255 - ...
252 + {/* ... */}
253 </ReactTransitionGroup>
254 ```
255
256 Every DOM component that React can render is available for use. However, `component` does not need to be a DOM component. It can be any React component you want; even ones you've written yourself! Just write `component={List}` and your component will receive `this.props.children`.
257
261 -### Rendering a Single Child
258 +#### Rendering a Single Child
259
260 People often use `ReactTransitionGroup` to animate mounting and unmounting of a single child such as a collapsible panel. Normally `ReactTransitionGroup` wraps all its children in a `span` (or a custom `component` as described above). This is because any React component has to return a single root element, and `ReactTransitionGroup` is no exception to this rule.
261
@@ -280,3 +277,65 @@ Now you can specify `FirstChild` as the `component` prop in `<ReactTransitionGro
277 ```
278
279 This only works when you are animating a single child in and out, such as a collapsible panel. This approach wouldn't work when animating multiple children or replacing the single child with another child, such as an image carousel. For an image carousel, while the current image is animating out, another image will animate in, so `<ReactTransitionGroup>` needs to give them a common DOM parent. You can't avoid the wrapper for multiple children, but you can customize the wrapper with the `component` prop as described above.
280 +
281 +* * *
282 +
283 +## Reference
284 +
285 +### `componentWillAppear()`
286 +
287 +```javascript
288 +componentWillAppear(callback)
289 +```
290 +
291 +This is called at the same time as `componentDidMount()` for components that are initially mounted in a `TransitionGroup`. It will block other animations from occurring until `callback` is called. It is only called on the initial render of a `TransitionGroup`.
292 +
293 +* * *
294 +
295 +### `componentDidAppear()`
296 +
297 +```javascript
298 +componentDidAppear()
299 +```
300 +
301 +This is called after the `callback` function that was passed to `componentWillAppear` is called.
302 +
303 +* * *
304 +
305 +### `componentWillEnter()`
306 +
307 +```javascript
308 +componentWillEnter(callback)
309 +```
310 +
311 +This is called at the same time as `componentDidMount()` for components added to an existing `TransitionGroup`. It will block other animations from occurring until `callback` is called. It will not be called on the initial render of a `TransitionGroup`.
312 +
313 +* * *
314 +
315 +### `componentDidEnter()`
316 +
317 +```javascript
318 +componentDidEnter()
319 +```
320 +
321 +This is called after the `callback` function that was passed to [`componentWillEnter()`](#componentwillenter) is called.
322 +
323 +* * *
324 +
325 +### `componentWillLeave()`
326 +
327 +```javascript
328 +componentWillLeave(callback)
329 +```
330 +
331 +This is called when the child has been removed from the `ReactTransitionGroup`. Though the child has been removed, `ReactTransitionGroup` will keep it in the DOM until `callback` is called.
332 +
333 +* * *
334 +
335 +### `componentDidLeave()`
336 +
337 +```javascript
338 +componentDidLeave()
339 +```
340 +
341 +This is called when the `willLeave` `callback` is called (at the same time as `componentWillUnmount()`).
docs/docs/addons-create-fragment.md renamed
+15 -3
@@ -2,10 +2,22 @@
2 id: create-fragment
3 title: Keyed Fragments
4 permalink: docs/create-fragment.html
5 -prev: clone-with-props.html
6 -next: update.html
5 +layout: docs
6 +category: Add-Ons
7 +prev: animation.html
8 +next: perf.html
9 ---
10
11 +**Importing**
12 +
13 +```javascript
14 +import createFragment from 'react-addons-create-fragment' // ES6
15 +var createFragment = require('react-addons-create-fragment') // ES5 with npm
16 +var createFragment = React.addons.createFragment; // ES5 with react-with-addons.js
17 +```
18 +
19 +## Overview
20 +
21 In most cases, you can use the `key` prop to specify keys on the elements you're returning from `render`. However, this breaks down in one situation: if you have two sets of children that you need to reorder, there's no way to put a key on each set without adding a wrapper element.
22
23 That is, if you have a component such as:
@@ -52,4 +64,4 @@ function Swapper(props) {
64
65 The keys of the passed object (that is, `left` and `right`) are used as keys for the entire set of children, and the order of the object's keys is used to determine the order of the rendered children. With this change, the two sets of children will be properly reordered in the DOM without unmounting.
66
55 -The return value of `createFragment` should be treated as an opaque object; you can use the `React.Children` helpers to loop through a fragment but should not access it directly. Note also that we're relying on the JavaScript engine preserving object enumeration order here, which is not guaranteed by the spec but is implemented by all major browsers and VMs for objects with non-numeric keys.
67 +The return value of `createFragment` should be treated as an opaque object; you can use the [`React.Children`](/react/docs/react-api.html#react.children) helpers to loop through a fragment but should not access it directly. Note also that we're relying on the JavaScript engine preserving object enumeration order here, which is not guaranteed by the spec but is implemented by all major browsers and VMs for objects with non-numeric keys.
docs/docs/addons-perf.md new
+146
@@ -0,0 +1,146 @@
1 +---
2 +id: perf
3 +title: Performance Tools
4 +permalink: docs/perf.html
5 +layout: docs
6 +category: Add-Ons
7 +prev: create-fragment.html
8 +next: test-utils.html
9 +---
10 +
11 +**Importing**
12 +
13 +```javascript
14 +import Perf from 'react-addons-perf' // ES6
15 +var Perf = require('react-addons-perf') // ES5 with npm
16 +var Perf = React.addons.Perf; // ES5 with react-with-addons.js
17 +```
18 +
19 +
20 +## Overview
21 +
22 +React is usually quite fast out of the box. However, in situations where you need to squeeze every ounce of performance out of your app, it provides a [shouldComponentUpdate()](/react/docs/react-component.html#shouldcomponentupdate) hook where you can add optimization hints to React's diff algorithm.
23 +
24 +In addition to giving you an overview of your app's overall performance, `Perf` is a profiling tool that tells you exactly where you need to put these hooks.
25 +
26 +See these articles by the [Benchling Engineering Team](http://benchling.engineering) for a in-depth introduction to performance tooling:
27 +
28 + - ["Performance Engineering with React"](http://benchling.engineering/performance-engineering-with-react/)
29 + - ["A Deep Dive into React Perf Debugging"](http://benchling.engineering/deep-dive-react-perf-debugging/)
30 +
31 +### Development vs. Production Builds
32 +
33 +If you're benchmarking or seeing performance problems in your React apps, make sure you're testing with the [minified production build](/react/downloads.html). The development build includes extra warnings that are helpful when building your apps, but it is slower due to the extra bookkeeping it does.
34 +
35 +However, the perf tools described on this page only work when using the development build of React. Therefore, the profiler only serves to indicate the _relatively_ expensive parts of your app.
36 +
37 +### Using Perf
38 +
39 +The `Perf` object can be used with React in development mode only. You should not include this bundle when building your app for production.
40 +
41 +#### Getting Measurements
42 +
43 + - [`start()`](#start)
44 + - [`stop()`](#stop)
45 + - [`getLastMeasurements()`](#getlastmeasurements)
46 +
47 +#### Printing Results
48 +
49 +The following methods use the measurements returned by [`Perf.getLastMeasurements()`](#getlastmeasurements) to pretty-print the result.
50 +
51 + - [`printInclusive()`](#printinclusive)
52 + - [`printExclusive()`](#printexclusive)
53 + - [`printWasted()`](#printwasted)
54 + - [`printOperations()`](#printoperations)
55 + - [`printDOM()`](#printdom)
56 +
57 +* * *
58 +
59 +## Reference
60 +
61 +### `start()`
62 +### `stop()`
63 +
64 +```javascript
65 +Perf.start()
66 +// ...
67 +Perf.stop()
68 +```
69 +
70 +Start/stop the measurement. The React operations in-between are recorded for analyses below. Operations that took an insignificant amount of time are ignored.
71 +
72 +After stopping, you will need [`Perf.getLastMeasurements()`](#getlastmeasurements) to get the measurements.
73 +
74 +* * *
75 +
76 +### `getLastMeasurements()`
77 +
78 +```javascript
79 +Perf.getLastMeasurements()
80 +```
81 +
82 +Get the opaque data structure describing measurements from the last start-stop session. You can save it and pass it to the other print methods in [`Perf`](#printing-results) to analyze past measurements.
83 +
84 +> Note
85 +>
86 +> Don't rely on the exact format of the return value because it may change in minor releases. We will update the documentation if the return value format becomes a supported part of the public API.
87 +
88 +* * *
89 +
90 +### `printInclusive()`
91 +
92 +```javascript
93 +Perf.printInclusive(measurements)
94 +```
95 +
96 +Prints the overall time taken. If no argument's passed, defaults to all the measurements from the last recording. This prints a nicely formatted table in the console, like so:
97 +
98 +![](/react/img/docs/perf-inclusive.png)
99 +
100 +* * *
101 +
102 +### `printExclusive()`
103 +
104 +```javascript
105 +Perf.printExclusive(measurements)
106 +```
107 +
108 +"Exclusive" times don't include the times taken to mount the components: processing props, calling `componentWillMount` and `componentDidMount`, etc.
109 +
110 +![](/react/img/docs/perf-exclusive.png)
111 +
112 +* * *
113 +
114 +### `printWasted()`
115 +
116 +```javascript
117 +Perf.printWasted(measurements)
118 +```
119 +
120 +**The most useful part of the profiler**.
121 +
122 +"Wasted" time is spent on components that didn't actually render anything, e.g. the render stayed the same, so the DOM wasn't touched.
123 +
124 +![](/react/img/docs/perf-wasted.png)
125 +
126 +* * *
127 +
128 +### `printOperations()`
129 +
130 +```javascript
131 +Perf.printOperations(measurements)
132 +```
133 +
134 +Prints the underlying DOM manipulations, e.g. "set innerHTML" and "remove".
135 +
136 +![](/react/img/docs/perf-dom.png)
137 +
138 +* * *
139 +
140 +### `printDOM()`
141 +
142 +```javascript
143 +Perf.printDOM(measurements)
144 +```
145 +
146 +This method has been renamed to [`printOperations()`](#printoperations). Currently `printDOM()` still exists as an alias but it prints a deprecation warning and will eventually be removed.
docs/docs/addons-pure-render-mixin.md new
+42
@@ -0,0 +1,42 @@
1 +---
2 +id: pure-render-mixin
3 +title: PureRenderMixin
4 +permalink: docs/pure-render-mixin.html
5 +layout: docs
6 +category: Add-Ons
7 +---
8 +
9 +> Note:
10 +> `PureRenderMixin` is a legacy add-on. Use [`React.PureComponent`](/react/docs/react-api.html#react.purecomponent) instead.
11 +
12 +**Importing**
13 +
14 +```javascript
15 +import PureRenderMixin from 'react-addons-pure-render-mixin' // ES6
16 +var PureRenderMixin = require('react-addons-pure-render-mixin') // ES5 with npm
17 +var PureRenderMixin = React.addons.PureRenderMixin; // ES5 with react-with-addons.js
18 +```
19 +
20 +## Overview
21 +
22 +If your React component's render function renders the same result given the same props and state, you can use this mixin for a performance boost in some cases.
23 +
24 +Example:
25 +
26 +```js
27 +React.createClass({
28 + mixins: [PureRenderMixin],
29 +
30 + render: function() {
31 + return <div className={this.props.className}>foo</div>;
32 + }
33 +});
34 +```
35 +
36 +Under the hood, the mixin implements [shouldComponentUpdate](/react/docs/component-specs.html#updating-shouldcomponentupdate), in which it compares the current props and state with the next ones and returns `false` if the equalities pass.
37 +
38 +> Note:
39 +>
40 +> This only shallowly compares the objects. If these contain complex data structures, it may produce false-negatives for deeper differences. Only mix into components which have simple props and state, or use `forceUpdate()` when you know deep data structures have changed. Or, consider using [immutable objects](https://facebook.github.io/immutable-js/) to facilitate fast comparisons of nested data.
41 +>
42 +> Furthermore, `shouldComponentUpdate` skips updates for the whole component subtree. Make sure all the children components are also "pure".
docs/docs/addons-shallow-compare.md renamed
+16 -4
@@ -2,18 +2,30 @@
2 id: shallow-compare
3 title: Shallow Compare
4 permalink: docs/shallow-compare.html
5 -prev: perf.html
6 -next: advanced-performance.html
5 +layout: docs
6 +category: Reference
7 ---
8
9 -`shallowCompare` is a helper function to achieve the same functionality as `PureRenderMixin` while using ES6 classes with React.
9 +> Note:
10 +> `shallowCompare` is a legacy add-on. Use [`React.PureComponent`](/react/docs/react-api.html#react.purecomponent) instead.
11 +
12 +**Importing**
13 +
14 +```javascript
15 +import shallowCompare from 'react-addons-shallow-compare' // ES6
16 +var shallowCompare = require('react-addons-shallow-compare') // ES5 with npm
17 +var shallowCompare = React.addons.shallowCompare; // ES5 with react-with-addons.js
18 +```
19 +
20 +## Overview
21 +
22 +Before [`React.PureComponent`](/react/docs/react-api.html#react.purecomponent) was introduced, `shallowCompare` was commonly used to achieve the same functionality as [`PureRenderMixin`](pure-render-mixin.html) while using ES6 classes with React.
23
24 If your React component's render function is "pure" (in other words, it renders the same result given the same props and state), you can use this helper function for a performance boost in some cases.
25
26 Example:
27
28 ```js
16 -var shallowCompare = require('react-addons-shallow-compare');
29 export class SampleComponent extends React.Component {
30 shouldComponentUpdate(nextProps, nextState) {
31 return shallowCompare(this, nextProps, nextState);
docs/docs/addons-test-utils.md new
+326
@@ -0,0 +1,326 @@
1 +---
2 +id: test-utils
3 +title: Test Utilities
4 +permalink: docs/test-utils.html
5 +layout: docs
6 +category: Reference
7 +prev: perf.html
8 +---
9 +
10 +**Importing**
11 +
12 +```javascript
13 +import ReactTestUtils from 'react-addons-test-utils' // ES6
14 +var ReactTestUtils = require('react-addons-test-utils') // ES5 with npm
15 +var ReactTestUtils = React.addons.TestUtils; // ES5 with react-with-addons.js
16 +```
17 +
18 +## Overview
19 +
20 +`ReactTestUtils` makes it easy to test React components in the testing framework of your choice. At Facebook we use [Jest](https://facebook.github.io/jest/) for painless JavaScript testing. Learn how to get started with Jest through the Jest website's [React Tutorial](http://facebook.github.io/jest/docs/tutorial-react.html#content).
21 +
22 +> Note:
23 +>
24 +> Airbnb has released a testing utility called Enzyme, which makes it easy to assert, manipulate, and traverse your React Components' output. If you're deciding on a unit testing utility to use together with Jest, or any other test runner, it's worth checking out: [http://airbnb.io/enzyme/](http://airbnb.io/enzyme/)
25 +
26 + - [`Simulate`](#simulate)
27 + - [`renderIntoDocument()`](#renderintodocument)
28 + - [`mockComponent()`](#mockcomponent)
29 + - [`isElement()`](#iselement)
30 + - [`isElementOfType()`](#iselementoftype)
31 + - [`isDOMComponent()`](#isdomcomponent)
32 + - [`isCompositeComponent()`](#iscompositecomponent)
33 + - [`isCompositeComponentWithType()`](#iscompositecomponentwithtype)
34 + - [`findAllInRenderedTree()`](#findallinrenderedtree)
35 + - [`scryRenderedDOMComponentsWithClass()`](#scryrendereddomcomponentswithclass)
36 + - [`findRenderedDOMComponentWithClass()`](#findrendereddomcomponentwithclass)
37 + - [`scryRenderedDOMComponentsWithTag()`](#scryrendereddomcomponentswithtag)
38 + - [`findRenderedDOMComponentWithTag()`](#findrendereddomcomponentwithtag)
39 + - [`scryRenderedComponentsWithType()`](#scryrenderedcomponentswithtype)
40 + - [`findRenderedComponentWithType()`](#findrenderedcomponentwithtype)
41 +
42 +### Shallow Rendering
43 +
44 +Shallow rendering lets you render a component "one level deep" and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered. This does not require a DOM.
45 +
46 + - [`createRenderer()`](#createrenderer)
47 + - [`shallowRenderer.render()`](#shallowrenderer.render)
48 + - [`shallowRenderer.getRenderOutput()`](#shallowrenderer.getrenderoutput)
49 +
50 +Call [`createRenderer()`](#createrenderer) in your tests to create a shallow renderer. You can think of this as a "place" to render the component you're testing, and from which you can extract the component's output.
51 +
52 +[`shadowRenderer.render()`](#shallowrenderer.render) is similar to [`ReactDOM.render()`](/react/docs/react-dom.html#render) but it doesn't require DOM and only renders a single level deep. This means you can test components in isolated from how their children are implemented.
53 +
54 +After `shadowRenderer.render()` has been called, you can use [`shallowRenderer.getRenderOutput()`](#shallowrenderer.getrenderoutput) to get the shallowly rendered output.
55 +
56 +You can then begin to assert facts about the output. For example, if your component's render method returns:
57 +
58 +```javascript
59 +<div>
60 + <span className="heading">Title</span>
61 + <Subcomponent foo="bar" />
62 +</div>
63 +```
64 +
65 +Then you can assert:
66 +
67 +```javascript
68 +var renderer = ReactTestUtils.createRenderer();
69 +result = renderer.getRenderOutput();
70 +expect(result.type).toBe('div');
71 +expect(result.props.children).toEqual([
72 + <span className="heading">Title</span>,
73 + <Subcomponent foo="bar" />
74 +]);
75 +```
76 +
77 +Shallow testing currently has some limitations, namely not supporting refs.
78 +
79 +We also recommend checking out Enzyme's [Shallow Rendering API](http://airbnb.io/enzyme/docs/api/shallow.html). It provides a nicer higher-level API over the same functionality.
80 +
81 +* * *
82 +
83 +## Reference
84 +
85 +### `Simulate`
86 +
87 +```javascript
88 +Simulate.{eventName}(
89 + element,
90 + [eventData]
91 +)
92 +```
93 +
94 +Simulate an event dispatch on a DOM node with optional `eventData` event data.
95 +
96 +`Simulate` has a method for [every event that React understands](/react/docs/events.html#supported-events).
97 +
98 +**Clicking an element**
99 +
100 +```javascript
101 +// <button ref="button">...</button>
102 +var node = this.refs.button;
103 +ReactTestUtils.Simulate.click(node);
104 +```
105 +
106 +**Changing the value of an input field and then pressing ENTER.**
107 +
108 +```javascript
109 +// <input ref="input" />
110 +var node = this.refs.input;
111 +node.value = 'giraffe';
112 +ReactTestUtils.Simulate.change(node);
113 +ReactTestUtils.Simulate.keyDown(node, {key: "Enter", keyCode: 13, which: 13});
114 +```
115 +
116 +> Note
117 +>
118 +> You will have to provide any event property that you're using in your component (e.g. keyCode, which, etc...) as React is not creating any of these for you.
119 +
120 +* * *
121 +
122 +### `renderIntoDocument()`
123 +
124 +```javascript
125 +renderIntoDocument(instance)
126 +```
127 +
128 +Render a component into a detached DOM node in the document. **This function requires a DOM.**
129 +
130 +> Note:
131 +>
132 +> You will need to have `window`, `window.document` and `window.document.createElement` globally available **before** you import `React`. Otherwise React will think it can't access the DOM and methods like `setState` won't work.
133 +
134 +* * *
135 +
136 +### `mockComponent()`
137 +
138 +```javascript
139 +mockComponent(
140 + componentClass,
141 + [mockTagName]
142 +)
143 +```
144 +
145 +Pass a mocked component module to this method to augment it with useful methods that allow it to be used as a dummy React component. Instead of rendering as usual, the component will become a simple `<div>` (or other tag if `mockTagName` is provided) containing any provided children.
146 +
147 +* * *
148 +
149 +### `isElement()`
150 +
151 +```javascript
152 +isElement(element)
153 +```
154 +
155 +Returns `true` if `element` is any React element.
156 +
157 +* * *
158 +
159 +### `isElementOfType()`
160 +
161 +```javascript
162 +isElementOfType(
163 + element,
164 + componentClass
165 +)
166 +```
167 +
168 +Returns `true` if `element` is a React element whose type is of a React `componentClass`.
169 +
170 +* * *
171 +
172 +### `isDOMComponent()`
173 +
174 +```javascript
175 +isDOMComponent(instance)
176 +```
177 +
178 +Returns `true` if `instance` is a DOM component (such as a `<div>` or `<span>`).
179 +
180 +* * *
181 +
182 +### `isCompositeComponent()`
183 +
184 +```javascript
185 +isCompositeComponent(instance)
186 +```
187 +
188 +Returns `true` if `instance` is a user-defined component, such as a class or a function.
189 +
190 +* * *
191 +
192 +### `isCompositeComponentWithType()`
193 +
194 +```javascript
195 +isCompositeComponentWithType(
196 + instance,
197 + componentClass
198 +)
199 +```
200 +
201 +Returns `true` if `instance` is a component whose type is of a React `componentClass`.
202 +
203 +* * *
204 +
205 +### `findAllInRenderedTree()`
206 +
207 +```javascript
208 +findAllInRenderedTree(
209 + tree,
210 + test
211 +)
212 +```
213 +
214 +Traverse all components in `tree` and accumulate all components where `test(component)` is `true`. This is not that useful on its own, but it's used as a primitive for other test utils.
215 +
216 +* * *
217 +
218 +### `scryRenderedDOMComponentsWithClass()`
219 +
220 +```javascript
221 +scryRenderedDOMComponentsWithClass(
222 + tree,
223 + className
224 +)
225 +```
226 +
227 +Finds all DOM elements of components in the rendered tree that are DOM components with the class name matching `className`.
228 +
229 +* * *
230 +
231 +### `findRenderedDOMComponentWithClass()`
232 +
233 +```javascript
234 +findRenderedDOMComponentWithClass(
235 + tree,
236 + className
237 +)
238 +```
239 +
240 +Like [`scryRenderedDOMComponentsWithClass()`](#scryrendereddomcomponentswithclass) but expects there to be one result, and returns that one result, or throws exception if there is any other number of matches besides one.
241 +
242 +* * *
243 +
244 +### `scryRenderedDOMComponentsWithTag()`
245 +
246 +```javascript
247 +scryRenderedDOMComponentsWithTag(
248 + tree,
249 + tagName
250 +)
251 +```
252 +
253 +Finds all DOM elements of components in the rendered tree that are DOM components with the tag name matching `tagName`.
254 +
255 +* * *
256 +
257 +### `findRenderedDOMComponentWithTag()`
258 +
259 +```javascript
260 +findRenderedDOMComponentWithTag(
261 + tree,
262 + tagName
263 +)
264 +```
265 +
266 +Like [`scryRenderedDOMComponentsWithTag()`](#scryrendereddomcomponentswithtag) but expects there to be one result, and returns that one result, or throws exception if there is any other number of matches besides one.
267 +
268 +* * *
269 +
270 +### `scryRenderedComponentsWithType()`
271 +
272 +```javascript
273 +scryRenderedComponentsWithType(
274 + tree,
275 + componentClass
276 +)
277 +```
278 +
279 +Finds all instances of components with type equal to `componentClass`.
280 +
281 +* * *
282 +
283 +### `findRenderedComponentWithType()`
284 +
285 +```javascript
286 +findRenderedComponentWithType(
287 + tree,
288 + componentClass
289 +)
290 +```
291 +
292 +Same as [`scryRenderedComponentsWithType()`](#scryrenderedcomponentswithtype) but expects there to be one result and returns that one result, or throws exception if there is any other number of matches besides one.
293 +
294 +* * *
295 +
296 +## Shallow Rendering
297 +
298 +### `createRenderer()`
299 +
300 +```javascript
301 +createRenderer()
302 +```
303 +
304 +Call this in your tests to create a [shallow renderer](#shallow-rendering).
305 +
306 +* * *
307 +
308 +### `shallowRenderer.render()`
309 +
310 +```javascript
311 +shallowRenderer.render(
312 + element
313 +)
314 +```
315 +
316 +Similar to [`ReactDOM.render`](/react/docs/react-dom.html#render) but it doesn't require DOM and only renders a single level deep. See [Shallow Rendering](#shallow-rendering).
317 +
318 +* * *
319 +
320 +### `shallowRenderer.getRenderOutput()`
321 +
322 +```javascript
323 +shallowRenderer.getRenderOutput()
324 +```
325 +
326 +After [`shallowRenderer.render()`](#shallowrenderer.render) has been called, returns shallowly rendered output.
docs/docs/addons-two-way-binding-helpers.md renamed
+29 -20
@@ -1,16 +1,27 @@
1 ---
2 id: two-way-binding-helpers
3 -title: Two-Way Binding Helpers
3 +title: Two-way Binding Helpers
4 permalink: docs/two-way-binding-helpers.html
5 -prev: animation.html
6 -next: test-utils.html
5 +layout: docs
6 +category: Add-Ons
7 +prev: pure-render-mixin.html
8 +next: update.html
9 ---
10
9 -`ReactLink` is an easy way to express two-way binding with React.
10 -
11 > Note:
12 ->
13 -> ReactLink is deprecated as of React v15. The recommendation is to explicitly set the value and change handler, instead of using ReactLink.
12 +> `LinkedStateMixin` is deprecated as of React v15. The recommendation is to explicitly set the value and change handler, instead of using `LinkedStateMixin`.
13 +
14 +**Importing**
15 +
16 +```javascript
17 +import LinkedStateMixin from 'react-addons-linked-state-mixin' // ES6
18 +var LinkedStateMixin = require('react-addons-linked-state-mixin') // ES5 with npm
19 +var LinkedStateMixin = React.addons.LinkedStateMixin; // ES5 with react-with-addons.js
20 +```
21 +
22 +## Overview
23 +
24 +`LinkedStateMixin` is an easy way to express two-way binding with React.
25
26 In React, data flows one way: from owner to child. This is because data only flows one direction in [the Von Neumann model of computing](https://en.wikipedia.org/wiki/Von_Neumann_architecture). You can think of it as "one-way data binding."
27
@@ -18,15 +29,15 @@ However, there are lots of applications that require you to read some data and f
29
30 In React, you would implement this by listening to a "change" event, read from your data source (usually the DOM) and call `setState()` on one of your components. "Closing the data flow loop" explicitly leads to more understandable and easier-to-maintain programs. See [our forms documentation](/react/docs/forms.html) for more information.
31
21 -Two-way binding -- implicitly enforcing that some value in the DOM is always consistent with some React `state` -- is concise and supports a wide variety of applications. We've provided `ReactLink`: syntactic sugar for setting up the common data flow loop pattern described above, or "linking" some data source to React `state`.
32 +Two-way binding -- implicitly enforcing that some value in the DOM is always consistent with some React `state` -- is concise and supports a wide variety of applications. We've provided `LinkedStateMixin`: syntactic sugar for setting up the common data flow loop pattern described above, or "linking" some data source to React `state`.
33
34 > Note:
35 >
25 -> `ReactLink` is just a thin wrapper and convention around the `onChange`/`setState()` pattern. It doesn't fundamentally change how data flows in your React application.
36 +> `LinkedStateMixin` is just a thin wrapper and convention around the `onChange`/`setState()` pattern. It doesn't fundamentally change how data flows in your React application.
37
27 -## ReactLink: Before and After
38 +## LinkedStateMixin: Before and After
39
29 -Here's a simple form example without using `ReactLink`:
40 +Here's a simple form example without using `LinkedStateMixin`:
41
42 ```javascript
43 var NoLink = React.createClass({
@@ -43,11 +54,9 @@ var NoLink = React.createClass({
54 });
55 ```
56
46 -This works really well and it's very clear how data is flowing, however, with a lot of form fields it could get a bit verbose. Let's use `ReactLink` to save us some typing:
57 +This works really well and it's very clear how data is flowing, however, with a lot of form fields it could get a bit verbose. Let's use `LinkedStateMixin` to save us some typing:
58
59 ```javascript{4,9}
49 -var LinkedStateMixin = require('react-addons-linked-state-mixin');
50 -
60 var WithLink = React.createClass({
61 mixins: [LinkedStateMixin],
62 getInitialState: function() {
@@ -59,9 +68,9 @@ var WithLink = React.createClass({
68 });
69 ```
70
62 -`LinkedStateMixin` adds a method to your React component called `linkState()`. `linkState()` returns a `ReactLink` object which contains the current value of the React state and a callback to change it.
71 +`LinkedStateMixin` adds a method to your React component called `linkState()`. `linkState()` returns a `valueLink` object which contains the current value of the React state and a callback to change it.
72
64 -`ReactLink` objects can be passed up and down the tree as props, so it's easy (and explicit) to set up two-way binding between a component deep in the hierarchy and state that lives higher in the hierarchy.
73 +`valueLink` objects can be passed up and down the tree as props, so it's easy (and explicit) to set up two-way binding between a component deep in the hierarchy and state that lives higher in the hierarchy.
74
75 Note that checkboxes have a special behavior regarding their `value` attribute, which is the value that will be sent on form submit if the checkbox is checked (defaults to `on`). The `value` attribute is not updated when the checkbox is checked or unchecked. For checkboxes, you should use `checkedLink` instead of `valueLink`:
76 ```
@@ -70,9 +79,9 @@ Note that checkboxes have a special behavior regarding their `value` attribute,
79
80 ## Under the Hood
81
73 -There are two sides to `ReactLink`: the place where you create the `ReactLink` instance and the place where you use it. To prove how simple `ReactLink` is, let's rewrite each side separately to be more explicit.
82 +There are two sides to `LinkedStateMixin`: the place where you create the `valueLink` instance and the place where you use it. To prove how simple `LinkedStateMixin` is, let's rewrite each side separately to be more explicit.
83
75 -### ReactLink Without LinkedStateMixin
84 +### valueLink Without LinkedStateMixin
85
86 ```javascript{5-7,9-12}
87 var WithoutMixin = React.createClass({
@@ -92,9 +101,9 @@ var WithoutMixin = React.createClass({
101 });
102 ```
103
95 -As you can see, `ReactLink` objects are very simple objects that just have a `value` and `requestChange` prop. And `LinkedStateMixin` is similarly simple: it just populates those fields with a value from `this.state` and a callback that calls `this.setState()`.
104 +As you can see, `valueLink` objects are very simple objects that just have a `value` and `requestChange` prop. And `LinkedStateMixin` is similarly simple: it just populates those fields with a value from `this.state` and a callback that calls `this.setState()`.
105
97 -### ReactLink Without valueLink
106 +### LinkedStateMixin Without valueLink
107
108 ```javascript
109 var LinkedStateMixin = require('react-addons-linked-state-mixin');
docs/docs/addons-update.md renamed
+22 -7
@@ -2,15 +2,28 @@
2 id: update
3 title: Immutability Helpers
4 permalink: docs/update.html
5 -prev: create-fragment.html
6 -next: pure-render-mixin.html
5 +layout: docs
6 +category: Add-Ons
7 ---
8
9 -React lets you use whatever style of data management you want, including mutation. However, if you can use immutable data in performance-critical parts of your application it's easy to implement a fast `shouldComponentUpdate()` method to significantly speed up your app.
9 +> Note:
10 +> `update` is a legacy add-on. Use [kolodny/immutability-helper](https://github.com/kolodny/immutability-helper) instead.
11 +
12 +**Importing**
13 +
14 +```javascript
15 +import update from 'react-addons-update'; // ES6
16 +var update = require('react-addons-update'); // ES5 with npm
17 +var update = React.addons.update; // ES5 with react-with-addons.js
18 +```
19 +
20 +## Overview
21 +
22 +React lets you use whatever style of data management you want, including mutation. However, if you can use immutable data in performance-critical parts of your application it's easy to implement a fast [`shouldComponentUpdate()`](/react/docs/react-component.html#shouldcomponentupdate) method to significantly speed up your app.
23
24 Dealing with immutable data in JavaScript is more difficult than in languages designed for it, like [Clojure](http://clojure.org/). However, we've provided a simple immutability helper, `update()`, that makes dealing with this type of data much easier, *without* fundamentally changing how your data is represented. You can also take a look at Facebook's [Immutable-js](https://facebook.github.io/immutable-js/docs/) and the [Advanced Performance](/react/docs/advanced-performance.html) section for more detail on Immutable-js.
25
13 -## The main idea
26 +### The Main Idea
27
28 If you mutate data like this:
29
@@ -41,10 +54,12 @@ var newData = extend(myData, {
54
55 While this is fairly performant (since it only makes a shallow copy of `log n` objects and reuses the rest), it's a big pain to write. Look at all the repetition! This is not only annoying, but also provides a large surface area for bugs.
56
57 +## `update()`
58 +
59 `update()` provides simple syntactic sugar around this pattern to make writing this code easier. This code becomes:
60
61 ```js
47 -var update = require('react-addons-update');
62 +import update from 'react-addons-update';
63
64 var newData = update(myData, {
65 x: {y: {z: {$set: 7}}},
@@ -56,7 +71,7 @@ While the syntax takes a little getting used to (though it's inspired by [MongoD
71
72 The `$`-prefixed keys are called *commands*. The data structure they are "mutating" is called the *target*.
73
59 -## Available commands
74 +## Available Commands
75
76 * `{$push: array}` `push()` all the items in `array` on the target.
77 * `{$unshift: array}` `unshift()` all the items in `array` on the target.
@@ -94,7 +109,7 @@ var newObj = update(obj, {b: {$apply: function(x) {return x * 2;}}});
109 var newObj2 = update(obj, {b: {$set: obj.b * 2}});
110 ```
111
97 -### (Shallow) merge
112 +### (Shallow) Merge
113
114 ```js
115 var obj = {a: 5, b: 3};
docs/docs/addons.md new
+44
@@ -0,0 +1,44 @@
1 +---
2 +id: addons
3 +title: Add-Ons
4 +permalink: docs/addons.html
5 +---
6 +
7 +The React add-ons are a collection of useful utility modules for building React apps. **These should be considered experimental** and tend to change more often than the core.
8 +
9 +- [`TransitionGroup` and `CSSTransitionGroup`](animation.html), for dealing with animations and transitions that are usually not simple to implement, such as before a component's removal.
10 +- [`createFragment`](create-fragment.html), to create a set of externally-keyed children.
11 +
12 +The add-ons below are in the development (unminified) version of React only:
13 +
14 +- [`Perf`](perf.html), a performance profiling tool for finding optimization opportunities.
15 +- [`ReactTestUtils`](test-utils.html), simple helpers for writing test cases.
16 +
17 +### Legacy Add-ons
18 +
19 +The add-ons below are considered legacy and their use is discouraged.
20 +
21 +- [`PureRenderMixin`](pure-render-mixin.html). Use [`React.PureComponent`](/react/docs/react-api.html#react.purecomponent) instead.
22 +- [`shallowCompare`](shallow-compare.html), a helper function that performs a shallow comparison for props and state in a component to decide if a component should update.
23 +- [`update`](update.html). Use [`kolodny/immutability-helper`](https://github.com/kolodny/immutability-helper) instead.
24 +
25 +### Deprecated Add-ons
26 +
27 +[`LinkedStateMixin`](two-way-binding-helpers.html) has been deprecated.
28 +
29 +## Using React with Add-ons
30 +
31 +If using npm, you can install the add-ons individually from npm (e.g. `npm install react-addons-test-utils`) and import them:
32 +
33 +```javascript
34 +import Perf from 'react-addons-perf'; // ES6
35 +var Perf = require('react-addons-perf'); // ES5 with npm
36 +```
37 +
38 +When using a CDN, you can use `react-with-addons.js` instead of `react.js`:
39 +
40 +```html
41 +<script src="https://unpkg.com/react@15/dist/react-with-addons.js"></script>
42 +```
43 +
44 +The add-ons will be available via the `React.addons` global (e.g. `React.addons.TestUtils`).
docs/docs/components-and-props.md new
+258
@@ -0,0 +1,258 @@
1 +---
2 +id: components-and-props
3 +title: Components and Props
4 +permalink: docs/components-and-props.html
5 +redirect_from: "/docs/reusable-components.html"
6 +redirect_from: "/docs/transferring-props.html"
7 +redirect_from: "/tips/props-in-getInitialState-as-anti-pattern.html"
8 +redirect_from: "/tips/communicate-between-components.html"
9 +prev: rendering-elements.html
10 +next: state-and-lifecycle.html
11 +---
12 +
13 +Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
14 +
15 +Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen.
16 +
17 +## Functional and Class Components
18 +
19 +The simplest way to define a component is to write a JavaScript function:
20 +
21 +```js
22 +function Welcome(props) {
23 + return <h1>Hello, {props.name}</h1>;
24 +}
25 +```
26 +
27 +This function is a valid React component because it accepts a single "props" object argument with data and returns a React element. We call such components "functional" because they are literally JavaScript functions.
28 +
29 +You can also use an [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes) to define a component:
30 +
31 +```js
32 +class Welcome extends React.Component {
33 + render() {
34 + return <h1>Hello, {this.props.name}</h1>;
35 + }
36 +}
37 +```
38 +
39 +The above two components are equivalent from React's point of view.
40 +
41 +Classes have some additional features that we will discuss in the [next sections](/react/docs/state-and-lifecycle.html). Until then, we will use functional components for their conciseness.
42 +
43 +## Rendering a Component
44 +
45 +Previously, we only encountered React elements that represent DOM tags:
46 +
47 +```js
48 +const element = <div />;
49 +```
50 +
51 +However, elements can also represent user-defined components:
52 +
53 +```js
54 +const element = <Welcome name="Sara" />;
55 +```
56 +
57 +When React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object "props".
58 +
59 +For example, this code renders "Hello, Sara" on the page:
60 +
61 +```js{1,5}
62 +function Welcome(props) {
63 + return <h1>Hello, {props.name}</h1>;
64 +}
65 +
66 +const element = <Welcome name="Sara" />;
67 +ReactDOM.render(
68 + element,
69 + document.getElementById('root')
70 +);
71 +```
72 +
73 +[Try it on CodePen.](http://codepen.io/gaearon/pen/YGYmEG?editors=0010)
74 +
75 +Let's recap what happens in this example:
76 +
77 +1. We call `ReactDOM.render()` with the `<Welcome name="Sara" />` element.
78 +2. React calls the `Welcome` component with `{name: 'Sara'}` as the props.
79 +3. Our `Welcome` component returns a `<h1>Hello, Sara</h1>` element as the result.
80 +4. React DOM efficiently updates the DOM to match `<h1>Hello, Sara</h1>`.
81 +
82 +>**Caveat:**
83 +>
84 +>Always start component names with a capital letter.
85 +>
86 +>For example, `<div />` represents a DOM tag, but `<Welcome />` represents a component and requires `Welcome` to be in scope.
87 +
88 +## Composing Components
89 +
90 +Components can refer to other components in their output. This lets us use the same component abstraction for any level of detail. A button, a form, a dialog, a screen: in React apps, all those are commonly expressed as components.
91 +
92 +For example, we can create an `App` component that renders `Welcome` many times:
93 +
94 +```js{8-10}
95 +function Welcome(props) {
96 + return <h1>Hello, {props.name}</h1>;
97 +}
98 +
99 +function App() {
100 + return (
101 + <div>
102 + <Welcome name="Sara" />
103 + <Welcome name="Cahal" />
104 + <Welcome name="Edite" />
105 + </div>
106 + );
107 +}
108 +
109 +ReactDOM.render(
110 + <App />,
111 + document.getElementById('root')
112 +);
113 +```
114 +
115 +[Try it on CodePen.](http://codepen.io/gaearon/pen/KgQKPr?editors=0010)
116 +
117 +Typically, new React apps have a single `App` component at the very top. However, if you integrate React into an existing app, you might start bottom-up with a small component like `Button` and gradually work your way to the top of the view hierarchy.
118 +
119 +>**Caveat:**
120 +>
121 +>Components must return a single root element. This is why we added a `<div>` to contain all the `<Welcome />` elements.
122 +
123 +## Extracting Components
124 +
125 +Don't be afraid to split components into smaller components.
126 +
127 +For example, consider this `Comment` component:
128 +
129 +```js
130 +function Comment(props) {
131 + return (
132 + <div className="Comment">
133 + <div className="UserInfo">
134 + <img className="Avatar"
135 + src={props.author.avatarUrl}
136 + alt={props.author.name} />
137 + <div className="UserInfo-name">
138 + {props.author.name}
139 + </div>
140 + </div>
141 + <div className="Comment-text">
142 + {props.text}
143 + </div>
144 + <div className="Comment-date">
145 + {formatDate(props.date)}
146 + </div>
147 + </div>
148 + );
149 +}
150 +```
151 +
152 +[Try it on CodePen.](http://codepen.io/gaearon/pen/VKQwEo?editors=0010)
153 +
154 +It accepts `author` (an object), `text` (a string), and `date` (a date) as props, and describes a comment on a social media website.
155 +
156 +This component can be tricky to change because of all the nesting, and it is also hard to reuse individual parts of it. Let's extract a few components from it.
157 +
158 +First, we will extract `Avatar`:
159 +
160 +```js{3-5}
161 +function Avatar(props) {
162 + return (
163 + <img className="Avatar"
164 + src={props.user.avatarUrl}
165 + alt={props.user.name} />
166 + );
167 +}
168 +```
169 +
170 +The `Avatar` doesn't need to know that it is being rendered inside a `Comment`. This is why we have given its prop a more generic name: `user` rather than `author`.
171 +
172 +We recommend naming props from the component's own point of view rather than the context in which it is being used.
173 +
174 +We can now simplify `Comment` a tiny bit:
175 +
176 +```js{5}
177 +function Comment(props) {
178 + return (
179 + <div className="Comment">
180 + <div className="UserInfo">
181 + <Avatar user={props.author} />
182 + <div className="UserInfo-name">
183 + {props.author.name}
184 + </div>
185 + </div>
186 + <div className="Comment-text">
187 + {props.text}
188 + </div>
189 + <div className="Comment-date">
190 + {formatDate(props.date)}
191 + </div>
192 + </div>
193 + );
194 +}
195 +```
196 +
197 +Next, we will extract a `UserInfo` component that renders an `Avatar` next to user's name:
198 +
199 +```js{3-8}
200 +function UserInfo(props) {
201 + return (
202 + <div className="UserInfo">
203 + <Avatar user={props.user} />
204 + <div className="UserInfo-name">
205 + {props.user.name}
206 + </div>
207 + </div>
208 + );
209 +}
210 +```
211 +
212 +This lets us simplify `Comment` even further:
213 +
214 +```js{4}
215 +function Comment(props) {
216 + return (
217 + <div className="Comment">
218 + <UserInfo user={props.author} />
219 + <div className="Comment-text">
220 + {props.text}
221 + </div>
222 + <div className="Comment-date">
223 + {formatDate(props.date)}
224 + </div>
225 + </div>
226 + );
227 +}
228 +```
229 +
230 +[Try it on CodePen.](http://codepen.io/gaearon/pen/rrJNJY?editors=0010)
231 +
232 +Extracting components might seem like grunt work at first, but having a palette of reusable components pays off in larger apps. A good rule of thumb is that if a part of your UI is used several times (`Button`, `Panel`, `Avatar`), or is complex enough on its own (`App`, `FeedStory`, `Comment`), it is a good candidate to be a reusable component.
233 +
234 +## Props are Read-Only
235 +
236 +Whether you declare a component [as a function or a class](#functional-and-class-components), it must never modify its own props. Consider this `sum` function:
237 +
238 +```js
239 +function sum(a, b) {
240 + return a + b;
241 +}
242 +```
243 +
244 +Such functions are called ["pure"](https://en.wikipedia.org/wiki/Pure_function) because they do not attempt to change their inputs, and always return the same result for the same inputs.
245 +
246 +In contrast, this function is impure because it changes its own input:
247 +
248 +```js
249 +function withdraw(account, amount) {
250 + account.total -= amount;
251 +}
252 +```
253 +
254 +React is pretty flexible but it has a single strict rule:
255 +
256 +**All React components must act like pure functions with respect to their props.**
257 +
258 +Of course, application UIs are dynamic and change over time. In the [next section](/react/docs/state-and-lifecycle.html), we will introduce a new concept of "state". State allows React components to change their output over time in response to user actions, network responses, and anything else, without violating this rule.
docs/docs/composition-vs-inheritance.md new
+171
@@ -0,0 +1,171 @@
1 +---
2 +id: composition-vs-inheritance
3 +title: Composition vs Inheritance
4 +permalink: docs/composition-vs-inheritance.html
5 +redirect_from: "/docs/multiple-components.html"
6 +prev: lifting-state-up.html
7 +next: thinking-in-react.html
8 +---
9 +
10 +React has a powerful composition model, and we recommend using composition instead of inheritance to reuse code between components.
11 +
12 +In this section, we will consider a few problems where developers new to React often reach for inheritance, and show how we can solve them with composition.
13 +
14 +## Containment
15 +
16 +Some components don't know their children ahead of time. This is especially common for components like `Sidebar` or `Dialog` that represent generic "boxes".
17 +
18 +We recommend that such components use the special `children` prop to pass children elements directly into their output:
19 +
20 +```js{4}
21 +function FancyBorder(props) {
22 + return (
23 + <div className={'FancyBorder FancyBorder-' + props.color}>
24 + {props.children}
25 + </div>
26 + );
27 +}
28 +```
29 +
30 +This lets other components pass arbitrary children to them by nesting the JSX:
31 +
32 +```js{4-9}
33 +function WelcomeDialog() {
34 + return (
35 + <FancyBorder color="blue">
36 + <h1 className="Dialog-title">
37 + Welcome
38 + </h1>
39 + <p className="Dialog-message">
40 + Thank you for visiting our spacecraft!
41 + </p>
42 + </FancyBorder>
43 + );
44 +}
45 +```
46 +
47 +[Try it on CodePen.](http://codepen.io/gaearon/pen/ozqNOV?editors=0010)
48 +
49 +Anything inside the `<FancyBorder>` JSX tag gets passed into the `FancyBorder` component as a `children` prop. Since `FancyBorder` renders `{props.children}` inside a `<div>`, the passed elements appear in the final output.
50 +
51 +While this is less common, sometimes you might need multiple "holes" in a component. In such cases you may come up with your own convention instead of using `children`:
52 +
53 +```js{5,8,18,21}
54 +function SplitPane(props) {
55 + return (
56 + <div className="SplitPane">
57 + <div className="SplitPane-left">
58 + {props.left}
59 + </div>
60 + <div className="SplitPane-right">
61 + {props.right}
62 + </div>
63 + </div>
64 + );
65 +}
66 +
67 +function App() {
68 + return (
69 + <SplitPane
70 + left={
71 + <Contacts />
72 + }
73 + right={
74 + <Chat />
75 + } />
76 + );
77 +}
78 +```
79 +
80 +[Try it on CodePen.](http://codepen.io/gaearon/pen/gwZOJp?editors=0010)
81 +
82 +React elements like `<Contacts />` and `<Chat />` are just objects, so you can pass them as props like any other data.
83 +
84 +## Specialization
85 +
86 +Sometimes we think about components as being "special cases" of other components. For example, we might say that a `WelcomeDialog` is a special case of `Dialog`.
87 +
88 +In React, this is also achieved by composition, where a more "specific" component renders a more "generic" one and configures it with props:
89 +
90 +```js{5,8,16-18}
91 +function Dialog(props) {
92 + return (
93 + <FancyBorder color="blue">
94 + <h1 className="Dialog-title">
95 + {props.title}
96 + </h1>
97 + <p className="Dialog-message">
98 + {props.message}
99 + </p>
100 + </FancyBorder>
101 + );
102 +}
103 +
104 +function WelcomeDialog() {
105 + return (
106 + <Dialog
107 + title="Welcome"
108 + message="Thank you for visiting our spacecraft!" />
109 + );
110 +}
111 +```
112 +
113 +[Try it on CodePen.](http://codepen.io/gaearon/pen/kkEaOZ?editors=0010)
114 +
115 +Composition works equally well for components defined as classes:
116 +
117 +```js{10,27-31}
118 +function Dialog(props) {
119 + return (
120 + <FancyBorder color="blue">
121 + <h1 className="Dialog-title">
122 + {props.title}
123 + </h1>
124 + <p className="Dialog-message">
125 + {props.message}
126 + </p>
127 + {props.children}
128 + </FancyBorder>
129 + );
130 +}
131 +
132 +class SignUpDialog extends React.Component {
133 + constructor(props) {
134 + super(props);
135 + this.handleChange = this.handleChange.bind(this);
136 + this.handleSignUp = this.handleSignUp.bind(this);
137 + this.state = {login: ''};
138 + }
139 +
140 + render() {
141 + return (
142 + <Dialog title="Mars Exploration Program"
143 + message="How should we refer to you?">
144 + <input value={this.state.login}
145 + onChange={this.handleChange} />
146 + <button onClick={this.handleSignUp}>
147 + Sign Me Up!
148 + </button>
149 + </Dialog>
150 + );
151 + }
152 +
153 + handleChange(e) {
154 + this.setState({login: e.target.value});
155 + }
156 +
157 + handleSignUp() {
158 + alert(`Welcome aboard, ${this.state.login}!`);
159 + }
160 +}
161 +```
162 +
163 +[Try it on CodePen.](http://codepen.io/gaearon/pen/gwZbYa?editors=0010)
164 +
165 +## So What About Inheritance?
166 +
167 +At Facebook, we use React in thousands of components, and we haven't found any use cases where we would recommend creating component inheritance hierarchies.
168 +
169 +Props and composition give you all the flexibility you need to customize a component's look and behavior in an explicit and safe way. Remember that components may accept arbitrary props, including primitive values, React elements, or functions.
170 +
171 +If you want to reuse non-UI functionality between components, we suggest extracting it into a separate JavaScript module. The components may import it and use that function, object, or a class, without extending it.
docs/docs/conditional-rendering.md new
+241
@@ -0,0 +1,241 @@
1 +---
2 +id: conditional-rendering
3 +title: Conditional Rendering
4 +permalink: docs/conditional-rendering.html
5 +prev: handling-events.html
6 +next: lists-and-keys.html
7 +redirect_from: "/tips/false-in-jsx.html"
8 +---
9 +
10 +In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application.
11 +
12 +Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like [`if`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else) or the [conditional operator](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) to create elements representing the current state, and let React update the UI to match them.
13 +
14 +Consider these two components:
15 +
16 +```js
17 +function UserGreeting(props) {
18 + return <h1>Welcome back!</h1>;
19 +}
20 +
21 +function GuestGreeting(props) {
22 + return <h1>Please sign up.</h1>;
23 +}
24 +```
25 +
26 +We'll create a `Greeting` component that displays either of these components depending on whether a user is logged in:
27 +
28 +```javascript{3-7,11,12}
29 +function Greeting(props) {
30 + const isLoggedIn = props.isLoggedIn;
31 + if (isLoggedIn) {
32 + return <UserGreeting />;
33 + } else {
34 + return <GuestGreeting />;
35 + }
36 +}
37 +
38 +ReactDOM.render(
39 + // Try changing to isLoggedIn={true}:
40 + <Greeting isLoggedIn={false} />,
41 + document.getElementById('root')
42 +);
43 +```
44 +
45 +[Try it out on CodePen.](https://codepen.io/gaearon/pen/ZpVxNq?editors=0011)
46 +
47 +This example renders a different greeting depending on the value of `isLoggedIn` prop.
48 +
49 +### Element Variables
50 +
51 +You can use variables to store elements. This can help you conditionally render a part of the component while the rest of the output doesn't change.
52 +
53 +Consider these two new components representing Logout and Login buttons:
54 +
55 +```js
56 +function LoginButton(props) {
57 + return (
58 + <button onClick={props.onClick}>
59 + Login
60 + </button>
61 + );
62 +}
63 +
64 +function LogoutButton(props) {
65 + return (
66 + <button onClick={props.onClick}>
67 + Logout
68 + </button>
69 + );
70 +}
71 +```
72 +
73 +In the example below, we will create a [stateful component](/react/docs/state-and-lifecycle.html#adding-local-state-to-a-class) called `LoginControl`.
74 +
75 +It will render either `<LoginButton />` or `<LogoutButton />` depending on its current state. It will also render a `<Greeting />` from the previous example:
76 +
77 +```javascript{20-25,29,30}
78 +class LoginControl extends React.Component {
79 + constructor(props) {
80 + super(props);
81 + this.handleLoginClick = this.handleLoginClick.bind(this);
82 + this.handleLogoutClick = this.handleLogoutClick.bind(this);
83 + this.state = {isLoggedIn: false};
84 + }
85 +
86 + handleLoginClick() {
87 + this.setState({isLoggedIn: true});
88 + }
89 +
90 + handleLogoutClick() {
91 + this.setState({isLoggedIn: false});
92 + }
93 +
94 + render() {
95 + const isLoggedIn = this.state.isLoggedIn;
96 +
97 + let button = null;
98 + if (isLoggedIn) {
99 + button = <LogoutButton onClick={this.handleLogoutClick} />;
100 + } else {
101 + button = <LoginButton onClick={this.handleLoginClick} />;
102 + }
103 +
104 + return (
105 + <div>
106 + <Greeting isLoggedIn={isLoggedIn} />
107 + {button}
108 + </div>
109 + );
110 + }
111 +}
112 +
113 +ReactDOM.render(
114 + <LoginControl />,
115 + document.getElementById('root')
116 +);
117 +```
118 +
119 +[Try it out on CodePen.](https://codepen.io/gaearon/pen/QKzAgB?editors=0010)
120 +
121 +While declaring a variable and using an `if` statement is a fine way to conditionally render a component, sometimes you might want to use a shorter syntax. There are a few ways to inline conditions in JSX, explained below.
122 +
123 +### Inline If with Logical && Operator
124 +
125 +You may [embed any expressions in JSX](/react/docs/introducing-jsx.html#embedding-expressions-in-jsx) by wrapping them in curly braces. This includes the JavaScript logical `&&` operator. It can be handy for conditionally including an element:
126 +
127 +```js{6-10}
128 +function Mailbox(props) {
129 + const unreadMessages = props.unreadMessages;
130 + return (
131 + <div>
132 + <h1>Hello!</h1>
133 + {unreadMessages.length > 0 &&
134 + <h2>
135 + You have {unreadMessages.length} unread messages.
136 + </h2>
137 + }
138 + </div>
139 + );
140 +}
141 +
142 +const messages = ['React', 'Re: React', 'Re:Re: React'];
143 +ReactDOM.render(
144 + <Mailbox unreadMessages={messages} />,
145 + document.getElementById('root')
146 +);
147 +```
148 +
149 +[Try it on CodePen.](https://codepen.io/gaearon/pen/ozJddz?editors=0010)
150 +
151 +It works because in JavaScript, `true && expression` always evaluates to `expression`, and `false && expression` always evaluates to `false`.
152 +
153 +Therefore, if the condition is `true`, the element right after `&&` will appear in the output. If it is `false`, React will ignore and skip it.
154 +
155 +### Inline If-Else with Conditional Operator
156 +
157 +Another method for conditionally rendering elements inline is to use the JavaScript conditional operator [`condition ? true : false`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator).
158 +
159 +In the example below, we use it to conditionally render a small block of text.
160 +
161 +```javascript{5}
162 +render() {
163 + const isLoggedIn = this.state.isLoggedIn;
164 + return (
165 + <div>
166 + The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
167 + </div>
168 + );
169 +}
170 +```
171 +
172 +It can also be used for larger expressions although it is less obvious what's going on:
173 +
174 +```js{5,7,9}
175 +render() {
176 + const isLoggedIn = this.state.isLoggedIn;
177 + return (
178 + <div>
179 + {isLoggedIn ? (
180 + <LogoutButton onClick={this.handleLogoutClick} />
181 + ) : (
182 + <LoginButton onClick={this.handleLoginClick} />
183 + )}
184 + </div>
185 + );
186 +}
187 +```
188 +
189 +Just like in JavaScript, it is up to you to choose an appropriate style based on what you and your team consider more readable. Also remember that whenever conditions become too complex, it might be a good time to [extract a component](/react/docs/components-and-props.html#extracting-components).
190 +
191 +### Preventing Component from Rendering
192 +
193 +In rare cases you might want a component to hide itself even though it was rendered by another component. To do this return `null` instead of its render output.
194 +
195 +In the example below, the `<WarningBanner />` is rendered depending on the value of the prop called `warn`. If the value of the prop is `false`, then the component does not render:
196 +
197 +```javascript{2-4,29}
198 +function WarningBanner(props) {
199 + if (!props.warn) {
200 + return null;
201 + }
202 +
203 + return (
204 + <div className="warning">
205 + Warning!
206 + </div>
207 + );
208 +}
209 +
210 +class Page extends React.Component {
211 + constructor(props) {
212 + super(props);
213 + this.state = {showWarning: true}
214 + this.handleToggleClick = this.handleToggleClick.bind(this);
215 + }
216 +
217 + handleToggleClick() {
218 + this.setState(prevState => ({
219 + showWarning: !prevState.showWarning
220 + }));
221 + }
222 +
223 + render() {
224 + return (
225 + <div>
226 + <WarningBanner warn={this.state.showWarning} />
227 + <button onClick={this.handleToggleClick}>
228 + {this.state.showWarning ? 'Hide' : 'Show'}
229 + </button>
230 + </div>
231 + );
232 + }
233 +}
234 +
235 +ReactDOM.render(
236 + <Page />,
237 + document.getElementById('root')
238 +);
239 +```
240 +
241 +[Try it out on CodePen.](https://codepen.io/gaearon/pen/Xjoqwm?editors=0010)
docs/docs/context.md renamed
+46 -44
@@ -2,24 +2,26 @@
2 id: context
3 title: Context
4 permalink: docs/context.html
5 -prev: advanced-performance.html
5 ---
6
8 -One of React's biggest strengths is that it's easy to track the flow of data through your React components. When you look at a component, you can easily see exactly which props are being passed in which makes your apps easy to reason about.
7 +With React, it's easy to track the flow of data through your React components. When you look at a component, you can see which props are being passed, which makes your apps easy to reason about.
8
10 -Occasionally, you want to pass data through the component tree without having to pass the props down manually at every level. React's "context" feature lets you do this.
9 +In some cases, you want to pass data through the component tree without having to pass the props down manually at every level.
10 +You can do this directly in React with the powerful "context" API.
11
12 -> Note:
13 ->
14 -> Context is an advanced and experimental feature. The API is likely to change in future releases.
15 ->
16 -> Most applications will never need to use context. Especially if you are just getting started with React, you likely do not want to use context. Using context will make your code harder to understand because it makes the data flow less clear. It is similar to using global variables to pass state through your application.
17 ->
18 -> **If you have to use context, use it sparingly.**
19 ->
20 -> Regardless of whether you're building an application or a library, try to isolate your use of context to a small area and avoid using the context API directly when possible so that it's easier to upgrade when the API changes.
12 +## Why Not To Use Context
13
22 -## Passing info automatically through a tree
14 +The vast majority of applications do not need to use context.
15 +
16 +If you want your application to be stable, don't use context. It is an experimental API and it is likely to break in future releases of React.
17 +
18 +If you aren't familiar with state management libraries like [Redux](https://github.com/reactjs/redux) or [MobX](https://github.com/mobxjs/mobx), don't use context. For many practical applications, these libraries and their React bindings are a good choice for managing state that is relevant to many components. It is far more likely that Redux is the right solution to your problem than that context is the right solution.
19 +
20 +If you aren't an experienced React developer, don't use context. There is usually a better way to implement functionality just using props and state.
21 +
22 +If you insist on using context despite these warnings, try to isolate your use of context to a small area and avoid using the context API directly when possible so that it's easier to upgrade when the API changes.
23 +
24 +## How To Use Context
25
26 Suppose you have a structure like:
27
@@ -55,7 +57,7 @@ class MessageList extends React.Component {
57 }
58 ```
59
58 -In this example, we manually thread through a `color` prop in order to style the `Button` and `Message` components appropriately. Theming is a good example of when you might want an entire subtree to have access to some piece of information (a color). Using context, we can pass this through the tree automatically:
60 +In this example, we manually thread through a `color` prop in order to style the `Button` and `Message` components appropriately. Using context, we can pass this through the tree automatically:
61
62 ```javascript{4,11-13,19,26-28,38-40}
63 class Button extends React.Component {
@@ -104,29 +106,35 @@ By adding `childContextTypes` and `getChildContext` to `MessageList` (the contex
106
107 If `contextTypes` is not defined, then `context` will be an empty object.
108
107 -## Parent-child coupling
109 +## Parent-Child Coupling
110
109 -Context can also let you build an API such as:
111 +Context can also let you build an API where parents and children communicate. For example, one library that works this way is [React Router V4](https://react-router.now.sh/basic):
112
113 ```javascript
112 -<Menu>
113 - <MenuItem>aubergine</MenuItem>
114 - <MenuItem>butternut squash</MenuItem>
115 - <MenuItem>clementine</MenuItem>
116 -</Menu>
114 +const BasicExample = () => (
115 + <Router>
116 + <div>
117 + <ul>
118 + <li><Link to="/">Home</Link></li>
119 + <li><Link to="/about">About</Link></li>
120 + <li><Link to="/topics">Topics</Link></li>
121 + </ul>
122 +
123 + <hr/>
124 +
125 + <Match exactly pattern="/" component={Home} />
126 + <Match pattern="/about" component={About} />
127 + <Match pattern="/topics" component={Topics} />
128 + </div>
129 + </Router>
130 +)
131 ```
132
119 -By passing down the relevant info in the `Menu` component, each `MenuItem` can communicate back to the containing `Menu` component.
120 -
121 -**Before you build components with this API, consider if there are cleaner alternatives.** We're fond of simply passing the items as an array in cases like this:
133 +By passing down some information from the `Router` component, each `Link` and `Match` can communicate back to the containing `Router`.
134
123 -```javascript
124 -<Menu items={['aubergine', 'butternut squash', 'clementine']} />
125 -```
135 +Before you build components with an API similar to this, consider if there are cleaner alternatives. For example, you can pass entire React component as props if you'd like to.
136
127 -Recall that you can also pass entire React components in props if you'd like to.
128 -
129 -## Referencing context in lifecycle methods
137 +## Referencing Context in Lifecycle Methods
138
139 If `contextTypes` is defined within a component, the following lifecycle methods will receive an additional parameter, the `context` object:
140
@@ -148,9 +156,9 @@ void componentDidUpdate(
156 )
157 ```
158
151 -## Referencing context in stateless functional components
159 +## Referencing Context in Stateless Functional Components
160
153 -Stateless functional components are also able to reference `context` if `contextTypes` is defined as a property of the function. The following code shows the `Button` component above written as a stateless functional component.
161 +Stateless functional components are also able to reference `context` if `contextTypes` is defined as a property of the function. The following code shows a `Button` component written as a stateless functional component.
162
163 ```javascript
164 const Button = ({children}, context) =>
@@ -161,7 +169,11 @@ const Button = ({children}, context) =>
169 Button.contextTypes = {color: React.PropTypes.string};
170 ```
171
164 -## Updating context
172 +## Updating Context
173 +
174 +Don't do it.
175 +
176 +React has an API to update context, but it is fundamentally broken and you should not use it.
177
178 The `getChildContext` function will be called when the state or props changes. In order to update data in the context, trigger a local state update with `this.setState`. This will trigger a new context and changes will be received by the children.
179
@@ -198,14 +210,4 @@ MediaQuery.childContextTypes = {
210 };
211 ```
212
201 -## When not to use context
202 -
203 -Just as global variables are best avoided when writing clear code, you should avoid using context in most cases. In particular, think twice before using it to "save typing" and using it instead of passing explicit props.
204 -
205 -The best use cases for context are for implicitly passing down the logged-in user, the current language, or theme information. All of these might otherwise be true globals, but context lets you scope them to a single React subtree.
206 -
207 -Do not use context to pass your model data through components. Threading your data through the tree explicitly is much easier to understand. Using context makes your components more coupled and less reusable, because they behave differently depending on where they're rendered.
208 -
209 -## Known limitations
210 -
211 -If a context value provided by a component changes, descendants that use that value won't update if an intermediate parent returns `false` from `shouldComponentUpdate`. See issue [#2517](https://github.com/facebook/react/issues/2517) for more details.
213 +The problem is, if a context value provided by component changes, descendants that use that value won't update if an intermediate parent returns `false` from `shouldComponentUpdate`. This is totally out of control of the components using context, so there's basically no way to reliably update the context. [This blog post](https://medium.com/@mweststrate/how-to-safely-use-react-context-b7e343eff076) has a good explanation of why this is a problem and how you might get around it.
docs/docs/flux-overview.it-IT.md deleted
-7
@@ -1,7 +0,0 @@
1 ----
2 -id: flux-overview-it-IT
3 -title: Architettura di un'Applicazione Flux
4 -permalink: docs/flux-overview-it-IT.html
5 ----
6 -
7 -Questa pagina è stata spostata sul sito di Flux. [Leggila qui](https://facebook.github.io/flux/docs/overview.html).
docs/docs/flux-overview.ko-KR.md deleted
-7
@@ -1,7 +0,0 @@
1 ----
2 -id: flux-overview-ko-KR
3 -title: Flux 애플리케이션 아키텍쳐
4 -permalink: docs/flux-overview-ko-KR.html
5 ----
6 -
7 -이 페이지는 Flux 웹사이트로 이동되었습니다. [거기서 보세요](https://facebook.github.io/flux/docs/overview.html).
docs/docs/flux-overview.md deleted
-7
@@ -1,7 +0,0 @@
1 ----
2 -id: flux-overview
3 -title: Flux Application Architecture
4 -permalink: docs/flux-overview.html
5 ----
6 -
7 -This page has been moved to the Flux website. [View it there](https://facebook.github.io/flux/docs/overview.html).
docs/docs/flux-overview.zh-CN.md deleted
-7
@@ -1,7 +0,0 @@
1 ----
2 -id: flux-overview-zh-CN
3 -title: Flux 应用架构
4 -permalink: docs/flux-overview-zh-CN.html
5 ----
6 -
7 -本页被移到了 Flux 网站。[点击访问](https://facebook.github.io/flux/docs/overview.html)。
docs/docs/flux-todo-list.it-IT.md deleted
-7
@@ -1,7 +0,0 @@
1 ----
2 -id: flux-todo-list-it-IT
3 -title: Tutorial TodoMVC Flux
4 -permalink: docs/flux-todo-list-it-IT.html
5 ----
6 -
7 -Questa pagina è stata spostata sul sito di Flux. [Leggila qui](https://facebook.github.io/flux/docs/todo-list.html).
docs/docs/flux-todo-list.ko-KR.md deleted
-7
@@ -1,7 +0,0 @@
1 ----
2 -id: flux-todo-list-ko-KR
3 -title: Flux TodoMVC 튜토리얼
4 -permalink: docs/flux-todo-list-ko-KR.html
5 ----
6 -
7 -이 페이지는 Flux 웹사이트로 이동되었습니다. [거기서 보세요](https://facebook.github.io/flux/docs/todo-list.html).
docs/docs/flux-todo-list.md deleted
-7
@@ -1,7 +0,0 @@
1 ----
2 -id: flux-todo-list
3 -title: Flux TodoMVC Tutorial
4 -permalink: docs/flux-todo-list.html
5 ----
6 -
7 -This page has been moved to the Flux website. [View it there](https://facebook.github.io/flux/docs/todo-list.html).
docs/docs/flux-todo-list.zh-CN.md deleted
-7
@@ -1,7 +0,0 @@
1 ----
2 -id: flux-todo-list-zh-CN
3 -title: Flux TodoMVC 教程
4 -permalink: docs/flux-todo-list-zh-CN.html
5 ----
6 -
7 -本页被移到了 Flux 网站。[点击访问](https://facebook.github.io/flux/docs/todo-list.html)。
docs/docs/forms.md new
+428
@@ -0,0 +1,428 @@
1 +---
2 +id: forms
3 +title: Forms
4 +permalink: docs/forms.html
5 +prev: state-and-lifecycle.html
6 +next: lifting-state-up.html
7 +redirect_from: "/tips/controlled-input-null-value.html"
8 +---
9 +
10 +Form components such as `<input>`, `<textarea>`, and `<option>` differ from other native components because they can be mutated via user interactions. These components provide interfaces that make it easier to manage forms in response to user interactions.
11 +
12 +Two types of form components:
13 +
14 +* Controlled Components
15 +* Uncontrolled Components
16 +
17 +You can jump directly to <a href="/react/docs/forms.html#examples">examples</a>.
18 +
19 +## Controlled Components
20 +
21 +A **controlled** form component provides a `value` prop. A **controlled** component does not maintain its own internal state; the component renders purely based on props.
22 +
23 +```javascript
24 +render() {
25 + return <input type="text" value="Hello!" />;
26 +}
27 +```
28 +
29 +User input has no effect on the rendered element because React has declared the value to be "Hello!". To update the value in response to user input, you would use the onChange event:
30 +
31 +```javascript
32 +class Form extends React.Component {
33 + constructor(props) {
34 + super(props);
35 + this.state = {value: ""};
36 + this.handleChange = this.handleChange.bind(this);
37 + this.handleSubmit = this.handleSubmit.bind(this);
38 + }
39 +
40 + handleChange(event) {
41 + this.setState({value: event.target.value});
42 + }
43 +
44 + handleSubmit(event) {
45 + alert("Text field value is: '" + this.state.value + "'");
46 + }
47 +
48 + render() {
49 + return (
50 + <div>
51 + <input type="text"
52 + placeholder="Hello!"
53 + value={this.state.value}
54 + onChange={this.handleChange} />
55 + <button onClick={this.handleSubmit}>Submit</button>
56 + </div>
57 + );
58 + }
59 +}
60 +
61 +ReactDOM.render(<Form />, document.getElementById('root'));
62 +```
63 +
64 +[Try it on CodePen.](https://codepen.io/ericnakagawa/pen/QKkJva?editors=0010)
65 +
66 +In this example, we are accepting the value provided by the user and updating the `value` prop of the `<input>` component. This pattern makes it easy to implement interfaces that respond to or validate user interactions. For example:
67 +
68 +```javascript
69 + handleChange(event) {
70 + this.setState({value: event.target.value.substr(0, 140)});
71 + }
72 +```
73 +
74 +This would accept user input and truncate the value to the first 140 characters.
75 +
76 +### Potential Issues With Checkboxes and Radio Buttons
77 +
78 +Be aware that, in an attempt to normalize change handling for checkbox and radio inputs, React uses a `click` event in place of a `change` event. For the most part this behaves as expected, except when calling `preventDefault` in a `change` handler. `preventDefault` stops the browser from visually updating the input, even if `checked` gets toggled. This can be worked around either by removing the call to `preventDefault`, or putting the toggle of `checked` in a `setTimeout`.
79 +
80 +## Uncontrolled Components
81 +
82 +Form components that do not provide a `value` prop are *uncontrolled*.
83 +
84 +The example below renders an `<input>` control with an empty value. Any user input will be immediately reflected by the rendered element.
85 +
86 +An **uncontrolled** component manages its own state.
87 +
88 +```javascript
89 + render() {
90 + return <input type="text" />;
91 + }
92 +```
93 +
94 +If you wanted to listen to updates to the value, you could use the `onChange` event just like you can with controlled components.
95 +
96 +```javascript
97 +class Form extends React.Component {
98 + constructor(props) {
99 + super(props);
100 + this.state = {value: ""};
101 + this.handleChange = this.handleChange.bind(this);
102 + this.handleSubmit = this.handleSubmit.bind(this);
103 + }
104 +
105 + handleChange(event) {
106 + this.setState({value: event.target.value});
107 + }
108 +
109 + handleSubmit(event) {
110 + alert("Text field value is: '" + this.state.value + "'");
111 + }
112 +
113 + render() {
114 + return (
115 + <div>
116 + <input type="text"
117 + placeholder="Hello!"
118 + value={this.state.value}
119 + onChange={this.handleChange} />
120 + <button onClick={this.handleSubmit}>Submit</button>
121 + </div>
122 + );
123 + }
124 +}
125 +
126 +ReactDOM.render(<Form />, document.getElementById('root'));
127 +```
128 +
129 +[Try it on CodePen.](https://codepen.io/ericnakagawa/pen/XjxyoL?editors=0010)
130 +
131 +###Default Values
132 +
133 +To initialize an uncontrolled component with a non-empty value, you can supply a `defaultValue` prop.
134 +
135 +```javascript
136 + render() {
137 + return <input type="text" defaultValue="Hello!" />;
138 + }
139 +```
140 +
141 +Likewise, `<input type="checkbox">` and `<input type="radio">` support `defaultChecked`, and `<select>` supports `defaultValue`.
142 +
143 +## Interactive Props
144 +
145 +Form components support a few props that are affected via user interactions:
146 +
147 +* `value`, supported by `<input>` and `<textarea>` components.
148 +* `checked`, supported by `<input>` components of type `checkbox` or `radio`.
149 +* `selected`, supported by `<option>` components.
150 +
151 +In HTML, the value of `<textarea>` is set via children. In React, you should use `value` instead.
152 +
153 +Form components allow listening for changes by setting a callback to the `onChange` prop. The `onChange` prop works across browsers to fire in response to user interactions when:
154 +
155 +* The `value` of `<input>` or `<textarea>` changes.
156 +* The `checked` state of `<input>` changes.
157 +* The `selected` state of `<option>` changes.
158 +
159 +Like all DOM events, the `onChange` prop is supported on all native components and can be used to listen to bubbled change events.
160 +
161 +> Note:
162 +>
163 +> For `<input>` and `<textarea>`, `onChange` should generally used instead of — the DOM's built-in [`oninput`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput) event handler.
164 +
165 +## Advanced Topics
166 +
167 +### Why Controlled Components?
168 +
169 +Using form components such as `<input>` in React presents a challenge that is absent when writing traditional form HTML. For example, in HTML:
170 +
171 +```html
172 + <input type="text" name="title" value="Untitled" />
173 +```
174 +
175 +This renders an input *initialized* with the value, `Untitled`. When the user updates the input, the node's `value` *property* will change. However, `node.getAttribute('value')` will still return the value used at initialization time, `Untitled`.
176 +
177 +Unlike HTML, React components must represent the state of the view at any point in time and not only at initialization time. For example, in React:
178 +
179 +```javascript
180 + render() {
181 + return <input type="text" name="title" value="Untitled" />;
182 + }
183 +```
184 +
185 +Since this method describes the view at any point in time, the value of the text input should *always* be `Untitled`.
186 +
187 +### Why Textarea Value?
188 +
189 +In HTML, the value of `<textarea>` is usually set using its children:
190 +
191 +```html
192 + <!-- antipattern: DO NOT DO THIS! -->
193 + <textarea name="description">This is the description.</textarea>
194 +```
195 +
196 +For HTML, this easily allows developers to supply multiline values. However, since React is JavaScript, we do not have string limitations and can use `\n` if we want newlines. In a world where we have `value` and `defaultValue`, it is ambiguous what role children play. For this reason, you should not use children when setting `<textarea>` values:
197 +
198 +```javascript
199 + <textarea name="description" value="This is a description." />
200 +```
201 +
202 +If you *do* decide to use children, they will behave like `defaultValue`.
203 +
204 +### Why Select Value?
205 +
206 +The selected `<option>` in an HTML `<select>` is normally specified through that option's `selected` attribute. In React, in order to make components easier to manipulate, the following format is adopted instead:
207 +
208 +```javascript
209 + <select value="B">
210 + <option value="A">Apple</option>
211 + <option value="B">Banana</option>
212 + <option value="C">Cranberry</option>
213 + </select>
214 +```
215 +
216 +To make an uncontrolled component, `defaultValue` is used instead.
217 +
218 +> Note:
219 +>
220 +> You can pass an array into the `value` attribute, allowing you to select multiple options in a `select` tag: `<select multiple={true} value={['B', 'C']}>`.
221 +
222 +### Imperative operations
223 +
224 +If you need to imperatively perform an operation, you have to obtain a [reference to the DOM node](/react/docs/more-about-refs.html#the-ref-callback-attribute).
225 +For instance, if you want to imperatively submit a form, one approach would be to attach a `ref` to the `form` element and manually call `form.submit()`.
226 +
227 +## Examples
228 +
229 +### Basic Text Input
230 +
231 +```javascript
232 +class Form extends React.Component {
233 + constructor(props) {
234 + super(props);
235 + this.state = {value: ""};
236 + this.handleChange = this.handleChange.bind(this);
237 + this.handleSubmit = this.handleSubmit.bind(this);
238 + }
239 +
240 + handleChange(event) {
241 + this.setState({value: event.target.value});
242 + }
243 +
244 + handleSubmit(event) {
245 + alert("Text field value is: '" + this.state.value + "'");
246 + }
247 +
248 + render() {
249 + return (
250 + <div>
251 + <input type="text" placeholder="edit me"
252 + value={this.state.value} onChange={this.handleChange} />
253 + <button onClick={this.handleSubmit}>Submit</button>
254 + </div>
255 + );
256 + }
257 +}
258 +
259 +ReactDOM.render(<Form />, document.getElementById('root'));
260 +```
261 +
262 +[Try this on CodePen.](https://codepen.io/ericnakagawa/pen/JRmZjz?editors=0010)
263 +
264 +
265 +### Basic Textarea
266 +
267 +```javascript
268 +class Form extends React.Component {
269 + constructor(props) {
270 + super(props);
271 + this.state = {value: ""};
272 + this.handleChange = this.handleChange.bind(this);
273 + this.handleSubmit = this.handleSubmit.bind(this);
274 + }
275 +
276 + handleChange(event) {
277 + this.setState({value: event.target.value});
278 + }
279 +
280 + handleSubmit(event) {
281 + alert("Textarea value is: '" + this.state.value + "'");
282 + }
283 +
284 + render() {
285 + return (
286 + <div>
287 + <textarea
288 + name="description"
289 + value={this.state.value}
290 + onChange={this.handleChange}
291 + />
292 + <button onClick={this.handleSubmit}>Submit</button>
293 + </div>
294 + );
295 + }
296 +}
297 +
298 +ReactDOM.render(<Form />, document.getElementById('root'));
299 +```
300 +
301 +[Try this on CodePen.](https://codepen.io/ericnakagawa/pen/kkAQPp?editors=0010)
302 +
303 +### Basic Select
304 +
305 +```javascript
306 +class Form extends React.Component {
307 + constructor(props) {
308 + super(props);
309 + this.state = {value: "B"};
310 + this.handleChange = this.handleChange.bind(this);
311 + this.handleSubmit = this.handleSubmit.bind(this);
312 + }
313 +
314 + handleChange(event) {
315 + this.setState({value: event.target.value});
316 + }
317 +
318 + handleSubmit(event) {
319 + alert("Select value is: '" + this.state.value + "'");
320 + }
321 +
322 + render() {
323 + return (
324 + <div>
325 + <select value={this.state.value} onChange={this.handleChange}>
326 + <option value="A">Apple</option>
327 + <option value="B">Banana</option>
328 + <option value="C">Cranberry</option>
329 + </select>
330 + <button onClick={this.handleSubmit}>Submit</button>
331 + </div>
332 + );
333 + }
334 +}
335 +
336 +ReactDOM.render(<Form />, document.getElementById('root'));
337 +```
338 +
339 +[Try this on CodePen.](https://codepen.io/ericnakagawa/pen/pExQbL?editors=0010)
340 +
341 +### Basic Radio Button
342 +
343 +```javascript
344 +class Form extends React.Component {
345 + constructor(props) {
346 + super(props);
347 + this.state = {value: "B"};
348 + this.handleChange = this.handleChange.bind(this);
349 + this.handleSubmit = this.handleSubmit.bind(this);
350 + }
351 +
352 + handleChange(event) {
353 + this.setState({value: event.target.value});
354 + }
355 +
356 + handleSubmit(event) {
357 + alert("Radio button value is: '" + this.state.value + "'");
358 + }
359 +
360 + render() {
361 + return (
362 + <div>
363 + <input type="radio" name="choice" value="A" onChange={this.handleChange} /> Option A<br />
364 + <input type="radio" name="choice" value="B" onChange={this.handleChange} defaultChecked={true} /> Option B<br />
365 + <input type="radio" name="choice" value="C" onChange={this.handleChange} /> Option C<br />
366 + <br />
367 + <button onClick={this.handleSubmit}>Submit</button>
368 + </div>
369 + );
370 + }
371 +}
372 +
373 +ReactDOM.render(<Form />, document.getElementById('root'));
374 +```
375 +
376 +[Try this on CodePen.](https://codepen.io/ericnakagawa/pen/WGaYVg?editors=0010)
377 +
378 +
379 +### Basic Checkbox
380 +
381 +```javascript
382 +class Form extends React.Component {
383 + constructor(props) {
384 + super(props);
385 + this.state = {checked: ["B"]};
386 + this.handleChange = this.handleChange.bind(this);
387 + this.handleSubmit = this.handleSubmit.bind(this);
388 + }
389 +
390 + handleChange(event) {
391 + let val = event.target.value;
392 + let checked = this.state.checked.slice(); // copy
393 + if(checked.includes(val)) {
394 + checked.splice(checked.indexOf(val), 1);
395 + } else {
396 + checked.push(val);
397 + }
398 + this.setState({checked: checked})
399 + }
400 +
401 + handleSubmit(event) {
402 + alert("Boxes checked are: '" + this.state.checked + "'");
403 + }
404 +
405 + render() {
406 + return (
407 + <div>
408 + <input type="checkbox" value="A" onChange={this.handleChange} /> Option A<br />
409 + <input type="checkbox" value="B" onChange={this.handleChange} defaultChecked={true} /> Option B<br />
410 + <input type="checkbox" value="C" onChange={this.handleChange} /> Option C<br />
411 + <br />
412 + <button onClick={this.handleSubmit}>Submit</button>
413 + </div>
414 + );
415 + }
416 +}
417 +ReactDOM.render(<Form />, document.getElementById('root'));
418 +```
419 +
420 +[Try it on CodePen.](https://codepen.io/ericnakagawa/pen/kkAzPO?editors=0010)
421 +
422 +### Form Events
423 +
424 +Event names:
425 +
426 +```
427 +onChange onInput onSubmit
428 +```
docs/docs/getting-started.it-IT.md deleted
-123
@@ -1,123 +0,0 @@
1 ----
2 -id: getting-started-it-IT
3 -title: Primi Passi
4 -permalink: docs/getting-started-it-IT.html
5 -next: tutorial-it-IT.html
6 -redirect_from: "docs/index.html"
7 ----
8 -
9 -## JSFiddle
10 -
11 -La maniera più semplice di cominciare ad hackerare con React è usare i seguenti esempi di Hello World su JSFiddle:
12 -
13 - * **[React JSFiddle](https://jsfiddle.net/reactjs/69z2wepo/)**
14 - * [React JSFiddle senza JSX](https://jsfiddle.net/reactjs/5vjqabv3/)
15 -
16 -## Starter Kit
17 -
18 -Scarica lo starter kit per cominciare.
19 -
20 -<div class="buttons-unit downloads">
21 - <a href="/react/downloads/react-{{site.react_version}}.zip" class="button">
22 - Scarica lo Starter Kit {{site.react_version}}
23 - </a>
24 -</div>
25 -
26 -Nella directory principale dello starter kit, crea `helloworld.html` con il seguente contenuto.
27 -
28 -```html
29 -<!DOCTYPE html>
30 -<html>
31 - <head>
32 - <meta charset="UTF-8" />
33 - <title>Ciao React!</title>
34 - <script src="build/react.js"></script>
35 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
36 - </head>
37 - <body>
38 - <div id="example"></div>
39 - <script type="text/babel">
40 - ReactDOM.render(
41 - <h1>Cial, mondo!</h1>,
42 - document.getElementById('example')
43 - );
44 - </script>
45 - </body>
46 -</html>
47 -```
48 -
49 -La sintassi XML all'interno di JavaScript è chiamata JSX; dài un'occhiata alla [sintassi JSX](/react/docs/jsx-in-depth.html) per saperne di più. Allo scopo di tradurla in puro JavaScript usiamo `<script type="text/babel">` e includiamo Babel per effettuare la trasformazione effettiva nel browser.
50 -
51 -### File Separato
52 -
53 -Il tuo codice React JSX può trovarsi in un file a parte. Crea il seguente `src/helloworld.js`.
54 -
55 -```javascript
56 -ReactDOM.render(
57 - <h1>Ciao, mondo!</h1>,
58 - document.getElementById('example')
59 -);
60 -```
61 -
62 -Quindi fai riferimento ad esso da `helloworld.html`:
63 -
64 -```html{10}
65 -<script type="text/babel" src="src/helloworld.js"></script>
66 -```
67 -
68 -Nota che in alcuni browsers (Chrome, ad esempio) falliranno nel caricamento del file a meno che non sia servito tramite HTTP.
69 -
70 -### Trasformazione Offline
71 -
72 -Anzitutto installa gli strumenti da riga di comando di [Babel](http://babeljs.io/) (è richiesto [npm](https://www.npmjs.com/)):
73 -
74 -```
75 -npm install --global babel
76 -```
77 -
78 -Quindi, traduci il tuo file `src/helloworld.js` a semplice JavaScript:
79 -
80 -```
81 -babel src --watch --out-dir build
82 -
83 -```
84 -
85 -Il file `build/helloworld.js` è generato automaticamente ogni qualvolta effettui un cambiamento. Leggi la [documentazione di Babel CLI](http://babeljs.io/docs/usage/cli/) per un uso più avanzato.
86 -
87 -```javascript{2}
88 -ReactDOM.render(
89 - React.createElement('h1', null, 'Ciao, mondo!'),
90 - document.getElementById('example')
91 -);
92 -```
93 -
94 -
95 -Aggiorna il tuo file HTML come segue:
96 -
97 -```html{7,11}
98 -<!DOCTYPE html>
99 -<html>
100 - <head>
101 - <meta charset="UTF-8" />
102 - <title>Ciao React!</title>
103 - <script src="build/react.js"></script>
104 - <!-- Non c'è bisogno di Babel! -->
105 - </head>
106 - <body>
107 - <div id="example"></div>
108 - <script src="build/helloworld.js"></script>
109 - </body>
110 -</html>
111 -```
112 -
113 -## Vuoi CommonJS?
114 -
115 -Se vuoi usare React con [browserify](http://browserify.org/), [webpack](https://webpack.github.io/), o un altro sistema modulare compatibile con CommonJS, usa il [pacchetto npm `react`](https://www.npmjs.com/package/react). In aggiunta, lo strumento di build `jsx` può essere integrato in quasi tutti i sistemi di packaging (non soltanto CommonJS) assai facilmente.
116 -
117 -## Passi Successivi
118 -
119 -Dài un'occhiata [al tutorial](/react/docs/tutorial-it-IT.html) e agli altri esempi nella directory `examples` dello starter kit per saperne di più.
120 -
121 -Abbiamo anche un wiki al quale la comunità contribuisce con [flussi di lavoro, componenti UI, routing, gestione dati etc.](https://github.com/facebook/react/wiki/Complementary-Tools)
122 -
123 -In bocca al lupo, e benvenuto/a!
docs/docs/getting-started.ja-JP.md deleted
-121
@@ -1,121 +0,0 @@
1 ----
2 -id: getting-started-ja-JP
3 -title: 始めてみましょう
4 -permalink: docs/getting-started-ja-JP.html
5 -next: tutorial-ja-JP.html
6 -redirect_from: "docs/index-ja-JP.html"
7 ----
8 -
9 -## JSFiddle
10 -
11 -React でのハッキングを始めるにあたり、一番簡単なものとして次の JSFiddle で動いている Hello World の例を取り上げます。
12 -
13 - * **[React JSFiddle](https://jsfiddle.net/reactjs/69z2wepo/)**
14 - * [React JSFiddle without JSX](https://jsfiddle.net/reactjs/5vjqabv3/)
15 -
16 -## スターターキット
17 -
18 -始めるためにスターターキットをダウンロードしましょう。
19 -
20 -<div class="buttons-unit downloads">
21 - <a href="/react/downloads/react-{{site.react_version}}.zip" class="button">
22 - Download Starter Kit {{site.react_version}}
23 - </a>
24 -</div>
25 -
26 -スターターキットのルートディレクトリに `helloworld.html` を作り、次のように書いてみましょう。
27 -
28 -```html
29 -<!DOCTYPE html>
30 -<html>
31 - <head>
32 - <meta charset="UTF-8" />
33 - <title>Hello React!</title>
34 - <script src="build/react.js"></script>
35 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
36 - </head>
37 - <body>
38 - <div id="example"></div>
39 - <script type="text/babel">
40 - ReactDOM.render(
41 - <h1>Hello, world!</h1>,
42 - document.getElementById('example')
43 - );
44 - </script>
45 - </body>
46 -</html>
47 -```
48 -
49 -JavaScript の中に書かれた XML シンタックスは JSX と呼ばれるものです(JSX の詳しいことについては [JSX syntax](/react/docs/jsx-in-depth.html) を読んでください)。ここでは JSX から vanilla JavaScript への変換をブラウザ内で行わせるため、先程のコードには `<script type="text/jsx">` と書いており、加えて `JSXTransformer.js` を読み込ませています。
50 -
51 -### ファイルの分割
52 -
53 -React の JSX コードは別ファイルに分離することができます。 次のような `src/helloworld.js` を作ってみましょう。
54 -
55 -```javascript
56 -ReactDOM.render(
57 - <h1>Hello, world!</h1>,
58 - document.getElementById('example')
59 -);
60 -```
61 -
62 -それが終わったら、`helloworld.js` への参照を `helloworld.html` に書き込みましょう。
63 -
64 -```html{10}
65 -<script type="text/babel" src="src/helloworld.js"></script>
66 -```
67 -
68 -### オフラインでの変換
69 -
70 -まずはコマンドラインツールをインストールしましょう([npm](https://www.npmjs.com/) が必要です)。
71 -
72 -```
73 -npm install -g react-tools
74 -```
75 -
76 -インストールが終わったら、先程書いた `src/helloworld.js` ファイルを生の JavaScript に変換してみましょう。
77 -
78 -```
79 -jsx --watch src/ build/
80 -
81 -```
82 -
83 -すると、`src/helloword.js` に変更を加えるごとに `build/helloworld.js` が自動で生成されるようになります。
84 -
85 -```javascript{2}
86 -ReactDOM.render(
87 - React.createElement('h1', null, 'Hello, world!'),
88 - document.getElementById('example')
89 -);
90 -```
91 -
92 -
93 -最後に HTML ファイルを以下のように書き換えましょう。
94 -
95 -```html{7,11}
96 -<!DOCTYPE html>
97 -<html>
98 - <head>
99 - <meta charset="UTF-8" />
100 - <title>Hello React!</title>
101 - <script src="build/react.js"></script>
102 - <!-- Babel は必要ありません! -->
103 - </head>
104 - <body>
105 - <div id="example"></div>
106 - <script src="build/helloworld.js"></script>
107 - </body>
108 -</html>
109 -```
110 -
111 -## CommonJS を使うには
112 -
113 -React を [browserify](http://browserify.org/) や [webpack](https://webpack.github.io/)、または CommonJS 準拠の他のモジュールシステムと一緒に使いたい場合、 [`react` npm package](https://www.npmjs.com/package/react) を使ってみてください。また、`jsx` ビルドツールをパッケージングシステム(CommonJS に限らず)に導入することも非常に簡単です。
114 -
115 -## 次にすること
116 -
117 -[チュートリアル](/react/docs/tutorial-ja-JP.html) や、スターターキットの `examples` ディレクトリに入っている他の例を読んでみてください。
118 -
119 -また、[ワークフロー、UIコンポーネント、ルーティング、データマネジメントなど](https://github.com/facebook/react/wiki/Complementary-Tools)の方面で貢献しているコミュニティの wiki もあります。
120 -
121 -幸運を祈ります!React へようこそ!
docs/docs/getting-started.ko-KR.md deleted
-150
@@ -1,150 +0,0 @@
1 ----
2 -id: getting-started-ko-KR
3 -title: 시작해보기
4 -permalink: docs/getting-started-ko-KR.html
5 -next: tutorial-ko-KR.html
6 -redirect_from: "docs/index-ko-KR.html"
7 ----
8 -
9 -## JSFiddle
10 -
11 -React를 시작하는 가장 빠른 방법은 다음의 Hello World JSFiddle 예제를 따라 해 보는 것입니다.
12 -
13 - * **[React JSFiddle](https://jsfiddle.net/reactjs/69z2wepo/)**
14 - * [React JSFiddle without JSX](https://jsfiddle.net/reactjs/5vjqabv3/)
15 -
16 -## npm으로 React 사용하기
17 -
18 -[browserify](http://browserify.org/), [webpack](https://webpack.github.io/) 같은 CommonJS 모듈 시스템과 함께 React를 사용하시는 것을 권장합니다. [`react`](https://www.npmjs.com/package/react), [`react-dom`](https://www.npmjs.com/package/react-dom) npm 패키지를 사용하세요.
19 -
20 -```js
21 -// main.js
22 -var React = require('react');
23 -var ReactDOM = require('react-dom');
24 -
25 -ReactDOM.render(
26 - <h1>Hello, world!</h1>,
27 - document.getElementById('example')
28 -);
29 -```
30 -
31 -browserify를 설치한 후에 React DOM을 설치하고 bundle을 빌드합니다.
32 -
33 -```sh
34 -$ npm install --save react react-dom babelify babel-preset-react
35 -$ browserify -t [ babelify --presets [ react ] ] main.js -o bundle.js
36 -```
37 -
38 -> 주의:
39 ->
40 -> ES2015를 사용하고 있다면, `babel-preset-es2015` 패키지도 설치할 필요가 있습니다.
41 -
42 -## npm 없이 Quick Start 하기
43 -
44 -만약 당신이 npm을 사용할 준비가 아직 안되었다면, 미리빌드된 React와 React DOM 파일이 포함된 초심자용 키트를 다운로드 받을 수 있습니다.
45 -
46 -<div class="buttons-unit downloads">
47 - <a href="/react/downloads/react-{{site.react_version}}.zip" class="button">
48 - 초심자용 키트 내려받기 {{site.react_version}}
49 - </a>
50 -</div>
51 -
52 -초심자용 키트의 최상위 디렉터리에 아래의 내용대로 `helloworld.html` 파일을 생성합니다.
53 -
54 -```html
55 -<!DOCTYPE html>
56 -<html>
57 - <head>
58 - <meta charset="UTF-8" />
59 - <title>Hello React!</title>
60 - <script src="build/react.js"></script>
61 - <script src="build/react-dom.js"></script>
62 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
63 - </head>
64 - <body>
65 - <div id="example"></div>
66 - <script type="text/babel">
67 - ReactDOM.render(
68 - <h1>Hello, world!</h1>,
69 - document.getElementById('example')
70 - );
71 - </script>
72 - </body>
73 -</html>
74 -```
75 -
76 -JavaScript 안에 보이는 XML 구문은 JSX라고 합니다; 더 자세한 내용은 [JSX syntax](/react/docs/jsx-in-depth-ko-KR.html)을 확인하세요. 일반적인 JavaScript로 번역하기 위해 `<script type="text/babel">`를 사용하고 Babel을 포함하는 것으로 실제로 브라우저에서 변환작업을 수행합니다.
77 -
78 -### 파일의 분리
79 -
80 -React JSX 코드는 분리된 파일로 존재할 수 있습니다. 다음 내용으로 `src/helloworld.js`를 생성해보세요.
81 -
82 -```javascript
83 -ReactDOM.render(
84 - <h1>Hello, world!</h1>,
85 - document.getElementById('example')
86 -);
87 -```
88 -
89 -그다음 `helloworld.html`에서 참조합니다:
90 -
91 -```html{10}
92 -<script type="text/babel" src="src/helloworld.js"></script>
93 -```
94 -
95 -크롬 같은 몇몇 브라우저에서는 HTTP를 통해 제공되는 파일이 아니면 로드에 실패하므로 주의하세요.
96 -
97 -### 오프라인 변환
98 -
99 -먼저 [Babel](http://babeljs.io/) 커맨드라인 도구를 설치합니다. ([npm](https://www.npmjs.com/) 필요):
100 -
101 -```
102 -npm install --global babel-cli
103 -npm install babel-preset-react
104 -```
105 -
106 -그다음, `src/helloworld.js` 파일을 일반 JavaScript 파일로 변환합니다:
107 -
108 -```
109 -babel --presets react src --watch --out-dir build
110 -```
111 -
112 -> 주의:
113 ->
114 -> ES2015를 사용하고 있다면, `babel-preset-es2015` 패키지도 설치할 필요가 있습니다.
115 -
116 -수정할 때마다 `build/helloworld.js` 파일이 자동생성됩니다. 더 자세한 사용법은 [Babel CLI 문서](http://babeljs.io/docs/usage/cli/)를 읽어보세요.
117 -
118 -```javascript{2}
119 -ReactDOM.render(
120 - React.createElement('h1', null, 'Hello, world!'),
121 - document.getElementById('example')
122 -);
123 -```
124 -
125 -아래의 내용대로 HTML 파일을 업데이트합니다:
126 -
127 -```html{8,12}
128 -<!DOCTYPE html>
129 -<html>
130 - <head>
131 - <meta charset="UTF-8" />
132 - <title>Hello React!</title>
133 - <script src="build/react.js"></script>
134 - <script src="build/react-dom.js"></script>
135 - <!-- Babel은 이제 불필요합니다! -->
136 - </head>
137 - <body>
138 - <div id="example"></div>
139 - <script src="build/helloworld.js"></script>
140 - </body>
141 -</html>
142 -```
143 -
144 -## 다음 단계로
145 -
146 -더 알아보려면 [튜토리얼](/react/docs/tutorial-ko-KR.html)과 초심자용 키트의 `examples` 디렉터리에서 다른 예제들을 확인해 보세요.
147 -
148 -커뮤니티의 기여로 운영되는 Wiki도 있습니다: [워크플로우, UI 컴포넌트, 라우팅, 데이터 관리 등](https://github.com/facebook/react/wiki/Complementary-Tools)
149 -
150 -React의 세계에 오신 것을 환영합니다. 행운을 빌어요!
docs/docs/getting-started.md deleted
-85
@@ -1,85 +0,0 @@
1 ----
2 -id: getting-started
3 -title: Getting Started
4 -permalink: docs/getting-started.html
5 -next: tutorial.html
6 -redirect_from: "docs/index.html"
7 ----
8 -
9 -## JSFiddle
10 -
11 -The easiest way to start hacking on React is using the following JSFiddle Hello World examples:
12 -
13 - * **[React JSFiddle](https://jsfiddle.net/reactjs/69z2wepo/)**
14 - * [React JSFiddle without JSX](https://jsfiddle.net/reactjs/5vjqabv3/)
15 -
16 -## Create React App
17 -
18 -**[Create React App](http://github.com/facebookincubator/create-react-app)** is a new officially supported way to create single-page React applications. It offers a modern build setup with no configuration. It requires Node 4 or higher.
19 -
20 -Note that it has [some limitations](https://github.com/facebookincubator/create-react-app#limitations) and is only useful for single-page applications. If you need more flexibility, or if you want to integrate React into an existing project, consider other options below.
21 -
22 -## Starter Pack
23 -
24 -If you're just getting started, you can download the starter kit. The starter kit includes prebuilt copies of React and React DOM for the browser, as well as a collection of usage examples to help you get started.
25 -
26 -<div class="buttons-unit downloads">
27 - <a href="/react/downloads/react-{{site.react_version}}.zip" class="button">
28 - Download Starter Kit {{site.react_version}}
29 - </a>
30 -</div>
31 -
32 -In the root directory of the starter kit, create a `helloworld.html` with the following contents.
33 -
34 -```html
35 -<!DOCTYPE html>
36 -<html>
37 - <head>
38 - <meta charset="UTF-8" />
39 - <title>Hello React!</title>
40 - <script src="build/react.js"></script>
41 - <script src="build/react-dom.js"></script>
42 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
43 - </head>
44 - <body>
45 - <div id="example"></div>
46 - <script type="text/babel">
47 - ReactDOM.render(
48 - <h1>Hello, world!</h1>,
49 - document.getElementById('example')
50 - );
51 - </script>
52 - </body>
53 -</html>
54 -```
55 -
56 -The XML syntax inside of JavaScript is called JSX; check out the [JSX syntax](/react/docs/jsx-in-depth.html) to learn more about it. In order to translate it to vanilla JavaScript we use `<script type="text/babel">` and include Babel to actually perform the transformation in the browser. Open the html from a browser and you should already be able to see the greeting!
57 -
58 -### Separate File
59 -
60 -Your React JSX code can live in a separate file. Create the following `src/helloworld.js`.
61 -
62 -```javascript
63 -ReactDOM.render(
64 - <h1>Hello, world!</h1>,
65 - document.getElementById('example')
66 -);
67 -```
68 -
69 -Then reference it from `helloworld.html`:
70 -
71 -```html{10}
72 -<script type="text/babel" src="src/helloworld.js"></script>
73 -```
74 -
75 -Note that some browsers (Chrome, e.g.) will fail to load the file unless it's served via HTTP.
76 -
77 -## Using React with npm or Bower
78 -
79 -You can also use React with package managers like npm or Bower. You can learn more in our [Package Managers](/react/docs/package-management.html) section.
80 -
81 -## Next Steps
82 -
83 -Check out [the tutorial](/react/docs/tutorial.html) and the other examples in the starter kit's `examples` directory to learn more.
84 -
85 -Good luck, and welcome!
docs/docs/getting-started.zh-CN.md deleted
-168
@@ -1,168 +0,0 @@
1 ----
2 -id: getting-started-zh-CN
3 -title: 入门教程
4 -permalink: docs/getting-started-zh-CN.html
5 -next: tutorial-zh-CN.html
6 -redirect_from: "docs/index-zh-CN.html"
7 ----
8 -
9 -## JSFiddle
10 -
11 -开始 Hack React 的最简单的方法是用下面 JSFiddle 的Hello Worlds:
12 -
13 - * **[React JSFiddle](https://jsfiddle.net/reactjs/69z2wepo/)**
14 - * [React JSFiddle without JSX](https://jsfiddle.net/reactjs/5vjqabv3/)
15 -
16 -## 通过 npm 使用 React
17 -
18 -我们建议在 React 中使用 CommonJS 模块系统,比如 [browserify](http://browserify.org/) 或 [webpack](https://webpack.github.io/)。使用 [`react`](https://www.npmjs.com/package/react) 和 [`react-dom`](https://www.npmjs.com/package/react-dom) npm 包.
19 -
20 -```js
21 -// main.js
22 -var React = require('react');
23 -var ReactDOM = require('react-dom');
24 -
25 -ReactDOM.render(
26 - <h1>Hello, world!</h1>,
27 - document.getElementById('example')
28 -);
29 -```
30 -
31 -要用 browserify 安装 React DOM 和构建你的包。
32 -
33 -```sh
34 -$ npm install --save react react-dom babelify babel-preset-react
35 -$ browserify -t [ babelify --presets [ react ] ] main.js -o bundle.js
36 -```
37 -
38 -要用 webpack 安装 React DOM 和构建你的包:
39 -
40 -```sh
41 -$ npm install --save react react-dom babel-preset-react
42 -$ webpack
43 -```
44 -
45 -> 注意:
46 ->
47 -> 如果你正在使用 ES2015, 你将要使用 `babel-preset-es2015` 包.
48 -
49 -**注意:** 默认情况下,React 将会在开发模式,很缓慢,不建议用于生产。要在生产模式下使用 React,设置环境变量 `NODE_ENV` 为 `production` (使用 envify 或者 webpack's DefinePlugin)。例如:
50 -
51 -```js
52 -new webpack.DefinePlugin({
53 - "process.env": {
54 - NODE_ENV: JSON.stringify("production")
55 - }
56 -});
57 -```
58 -
59 -## 不用 npm 的快速开始
60 -
61 -如果你现在还没准备要使用npm,你可以下载这个已经包含了预构建的 React 和 React DOM 拷贝的入门套件.
62 -
63 -<div class="buttons-unit downloads">
64 - <a href="/react/downloads/react-{{site.react_version}}.zip" class="button">
65 - 下载入门套件 {{site.react_version}}
66 - </a>
67 -</div>
68 -
69 -在入门教程包的根目录,创建一个含有如下代码的 `helloworld.html`。
70 -
71 -```html
72 -<!DOCTYPE html>
73 -<html>
74 - <head>
75 - <meta charset="UTF-8" />
76 - <title>Hello React!</title>
77 - <script src="build/react.js"></script>
78 - <script src="build/react-dom.js"></script>
79 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
80 - </head>
81 - <body>
82 - <div id="example"></div>
83 - <script type="text/babel">
84 - ReactDOM.render(
85 - <h1>Hello, world!</h1>,
86 - document.getElementById('example')
87 - );
88 - </script>
89 - </body>
90 -</html>
91 -```
92 -
93 -在 JavaScript 代码里写着 XML 格式的代码称为 JSX;可以去 [JSX 语法](/react/docs/jsx-in-depth.html) 里学习更多 JSX 相关的知识。为了把 JSX 转成标准的 JavaScript,我们用 `<script type="text/babel">` 标签,并引入 Babel 来完成在浏览器里的代码转换。在浏览器里打开这个html,你应该可以看到成功的消息!
94 -
95 -### 分离文件
96 -
97 -你的 React JSX 代码文件可以写在另外的文件里。新建下面的 `src/helloworld.js`。
98 -
99 -```javascript
100 -ReactDOM.render(
101 - <h1>Hello, world!</h1>,
102 - document.getElementById('example')
103 -);
104 -```
105 -
106 -然后在 `helloworld.html` 引用该文件:
107 -
108 -```html{10}
109 -<script type="text/babel" src="src/helloworld.js"></script>
110 -```
111 -
112 -注意一些浏览器(比如 Chrome )会在使用 HTTP 以外的协议加载文件时失败。
113 -
114 -### 离线转换
115 -
116 -先安装[Babel](http://babeljs.io/)命令行工具(需要 [npm](https://www.npmjs.com/)):
117 -
118 -```
119 -npm install --global babel-cli
120 -npm install babel-preset-react
121 -```
122 -
123 -然后把你的 `src/helloworld.js` 文件转成标准的 JavaScript:
124 -
125 -```
126 -babel --presets react src --watch --out-dir build
127 -```
128 -
129 -> 注意:
130 ->
131 -> 如果你正在使用 ES2015, 你将需要使用 `babel-preset-es2015` 包.
132 -
133 -`build/helloworld.js` 会在你对文件进行修改时自动生成。 阅读 [Babel CLI 文档](http://babeljs.io/docs/usage/cli/) 了解高级用法。
134 -
135 -```javascript{2}
136 -ReactDOM.render(
137 - React.createElement('h1', null, 'Hello, world!'),
138 - document.getElementById('example')
139 -);
140 -```
141 -
142 -
143 -对照下面更新你的 HTML 代码
144 -
145 -```html{8,12}
146 -<!DOCTYPE html>
147 -<html>
148 - <head>
149 - <meta charset="UTF-8" />
150 - <title>Hello React!</title>
151 - <script src="build/react.js"></script>
152 - <script src="build/react-dom.js"></script>
153 - <!-- 不需要 Babel! -->
154 - </head>
155 - <body>
156 - <div id="example"></div>
157 - <script src="build/helloworld.js"></script>
158 - </body>
159 -</html>
160 -```
161 -
162 -## 下一步
163 -
164 -去看看[入门教程](/react/docs/tutorial-zh-CN.html) 和入门教程包 `examples` 目录下的其它例子学习更多。
165 -
166 -我们还有一个社区开发者共建的 Wiki:[workflows, UI-components, routing, data management etc.](https://github.com/facebook/react/wiki/Complementary-Tools)
167 -
168 -恭喜你,欢迎来到 React 的世界。
docs/docs/handling-events.md new
+139
@@ -0,0 +1,139 @@
1 +---
2 +id: handling-events
3 +title: Handling Events
4 +permalink: docs/handling-events.html
5 +prev: state-and-lifecycle.html
6 +next: conditional-rendering.html
7 +---
8 +
9 +Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences:
10 +
11 +* React events are named using camelCase, rather than lowercase.
12 +* With JSX you pass a function as the event handler, rather than a string.
13 +
14 +For example, the HTML:
15 +
16 +```html
17 +<button onclick="activateLasers()">
18 + Activate Lasers
19 +</button>
20 +```
21 +
22 +is slightly different in React:
23 +
24 +```js{1}
25 +<button onClick={activateLasers}>
26 + Activate Lasers
27 +</button>
28 +```
29 +
30 +Another difference is that you cannot return `false` to prevent default behavior in React. You must call `preventDefault` explicitly. For example, with plain HTML, to prevent the default link behavior of opening a new page, you can write:
31 +
32 +```html
33 +<a href="#" onclick="console.log('The link was clicked.'); return false">
34 + Click me
35 +</a>
36 +```
37 +
38 +In React, this could instead be:
39 +
40 +```js{2-5,8}
41 +function ActionLink() {
42 + function handleClick(e) {
43 + e.preventDefault();
44 + console.log('The link was clicked.');
45 + }
46 +
47 + return (
48 + <a href="#" onClick={handleClick}>
49 + Click me
50 + </a>
51 + );
52 +}
53 +```
54 +
55 +Here, `e` is a synthetic event. React defines these synthetic events according to the [W3C spec](https://www.w3.org/TR/DOM-Level-3-Events/), so you don't need to worry about cross-browser compatibility. See the [`SyntheticEvent`](/react/docs/events.html) reference guide to learn more.
56 +
57 +When using React you should generally not need to call `addEventListener` to add listeners to a DOM element after it is created. Instead, just provide a listener when the element is initially rendered.
58 +
59 +When you define a component using an [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes), a common pattern is for an event handler to be a method on the class. For example, this `Toggle` component renders a button that lets the user toggle between "ON" and "OFF" states:
60 +
61 +```js{6,7,10-14,18}
62 +class Toggle extends React.Component {
63 + constructor(props) {
64 + super(props);
65 + this.state = {isToggleOn: true};
66 +
67 + // This binding is necessary to make `this` work in the callback
68 + this.handleClick = this.handleClick.bind(this);
69 + }
70 +
71 + handleClick() {
72 + this.setState(prevState => ({
73 + isToggleOn: !prevState.isToggleOn
74 + }));
75 + }
76 +
77 + render() {
78 + return (
79 + <button onClick={this.handleClick}>
80 + {this.state.isToggleOn ? 'ON' : 'OFF'}
81 + </button>
82 + );
83 + }
84 +}
85 +
86 +ReactDOM.render(
87 + <Toggle />,
88 + document.getElementById('root')
89 +);
90 +```
91 +
92 +[Try it on CodePen.](http://codepen.io/gaearon/pen/xEmzGg?editors=0010)
93 +
94 +You have to be careful about the meaning of `this` in JSX callbacks. In JavaScript, class methods are not [bound](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind) by default. If you forget to bind `this.toggle` and pass it to `onClick`, `this` will be `undefined` when the function is actually called.
95 +
96 +This is not React-specific behavior; it is a part of [how functions work in JavaScript](https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/). Generally, if you refer to a method without `()` after it, such as `onClick={this.handleClick}`, you should bind that method.
97 +
98 +If calling `bind` annoys you, there are two ways you can get around this. If you are using the experimental [property initializer syntax](https://babeljs.io/docs/plugins/transform-class-properties/), you can use property initializers to correctly bind callbacks:
99 +
100 +```js{2-6}
101 +class LoggingButton extends React.Component {
102 + // This syntax ensures `this` is bound within handleClick.
103 + // Warning: this is *experimental* syntax.
104 + handleClick = () => {
105 + console.log('this is:', this);
106 + }
107 +
108 + render() {
109 + return (
110 + <button onClick={this.handleClick}>
111 + Click me
112 + </button>
113 + );
114 + }
115 +}
116 +```
117 +
118 +This syntax is enabled by default in [Create React App](https://github.com/facebookincubator/create-react-app).
119 +
120 +If you aren't using property initializer syntax, you can use an [arrow function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) in the callback:
121 +
122 +```js{7-9}
123 +class LoggingButton extends React.Component {
124 + handleClick() {
125 + console.log('this is:', this);
126 + }
127 +
128 + render() {
129 + // This syntax ensures `this` is bound within handleClick
130 + return (
131 + <button onClick={(e) => this.handleClick(e)}>
132 + Click me
133 + </button>
134 + );
135 + }
136 +}
137 +```
138 +
139 +The problem with this syntax is that a different callback is created each time the `LoggingButton` renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor to avoid this sort of performance problem.
docs/docs/hello-world.md new
+28
@@ -0,0 +1,28 @@
1 +---
2 +id: hello-world
3 +title: Hello World
4 +permalink: docs/hello-world.html
5 +prev: installation.html
6 +next: introducing-jsx.html
7 +---
8 +
9 +The easiest way to get started with React is to use [this Hello World example code on CodePen](http://codepen.io/gaearon/pen/ZpvBNJ?editors=0010). You don't need to install anything; you can just open it in another tab and follow along as we go through examples. If you'd rather use a local development environment, check out the [Installation](/docs/installation.html) page.
10 +
11 +The smallest React example looks like this:
12 +
13 +```js
14 +ReactDOM.render(
15 + <h1>Hello, world!</h1>,
16 + document.getElementById('root')
17 +);
18 +```
19 +
20 +It renders a header saying "Hello World" on the page.
21 +
22 +The next few sections will gradually introduce you to using React. We will examine the building blocks of React apps: elements and components. Once you master them, you can create complex apps from small reusable pieces.
23 +
24 +## A Note on JavaScript
25 +
26 +React is a JavaScript library, and so it assumes you have a basic understanding of the JavaScript language. If you don't feel very confident, we recommend [refreshing your JavaScript knowledge](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) so you can follow along more easily.
27 +
28 +We also use some of the ES6 syntax in the examples. We try to use it sparingly because it's still relatively new, but we encourage you to get familiar with [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), [classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), [template literals](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals), [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let), and [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) statements. You can use <a href="http://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Creact&experimental=false&loose=false&spec=false&code=const%20element%20%3D%20%3Ch1%3EHello%2C%20world!%3C%2Fh1%3E%3B%0Aconst%20container%20%3D%20document.getElementById('root')%3B%0AReactDOM.render(element%2C%20container)%3B%0A">Babel REPL</a> to check what ES6 code compiles to.
docs/docs/installation.md new
+82
@@ -0,0 +1,82 @@
1 +---
2 +id: installation
3 +title: Installation
4 +permalink: docs/installation.html
5 +redirect_from: "docs/index.html"
6 +redirect_from: "downloads.html"
7 +redirect_from: "docs/getting-started.html"
8 +redirect_from: "docs/tooling-integration.html"
9 +redirect_from: "/docs/package-management.html"
10 +redirect_from: "/docs/language-tooling.html"
11 +redirect_from: "/docs/environments.html"
12 +next: hello-world.html
13 +---
14 +
15 +React is flexible and can be used in a variety of projects. You can create new apps with it, but you can also gradually introduce it into an existing codebase without doing a rewrite.
16 +
17 +## Trying Out React
18 +
19 +If you're just interested in playing around with React, you can use CodePen. Try starting from [this Hello World example code](http://codepen.io/gaearon/pen/rrpgNB?editors=0010). You don't need to install anything; you can just modify the code and see if it works.
20 +
21 +If you prefer to use your own text editor, you can also <a href="/react/downloads/single-file-example.html" download="hello.html">download this HTML file</a>, edit it, and open it from the local filesystem in your browser. It does a slow runtime code transformation, so don't use it in production.
22 +
23 +## Creating a Single Page Application
24 +
25 +[Create React App](http://github.com/facebookincubator/create-react-app) is the best way to starting building a new React single page application. It sets up your development environment so that you can use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production.
26 +
27 +```bash
28 +npm install -g create-react-app
29 +create-react-app hello-world
30 +cd hello-world
31 +npm start
32 +```
33 +
34 +Create React App doesn't handle backend logic or databases; it just creates a frontend build pipeline, so you can use it with any backend you want. It uses Webpack, Babel and ESLint under the hood, but configures them for you.
35 +
36 +## Adding React to an Existing Application
37 +
38 +### Using npm
39 +
40 +We recommend using React from npm with a bundler like [Browserify](http://browserify.org/) or [webpack](https://webpack.github.io/). If you use npm for client package management, you can install React with:
41 +
42 +```bash
43 +npm install --save react react-dom
44 +```
45 +
46 +and import it from your code with something like:
47 +
48 +```js
49 +import React from 'react';
50 +import ReactDOM from 'react-dom';
51 +
52 +ReactDOM.render(
53 + <h1>Hello, world!</h1>,
54 + document.getElementById('root')
55 +);
56 +```
57 +
58 +This code renders into an HTML element with the id of `root` so you need `<div id="root"></div>` somewhere in your HTML file. When you use React in this way, you should be transpiling your JavaScript using Babel with the `es2015` and `react` presets. To use React in production mode, set the environment variable `NODE_ENV` to `"production"`.
59 +
60 +If you use Bower, React is available via the `react` package.
61 +
62 +### Enabling ES6 and JSX
63 +
64 +We recommend using React with Babel to let you use ES6 and JSX in your JavaScript code. ES6 is a set of modern JavaScript features that make development easier, and JSX is an extension to the JavaScript language that works nicely with React. The [Babel setup instructions](https://babeljs.io/docs/setup/) explain how to configure Babel in many different build environments. Make sure you install `babel-preset-react` and `babel-preset-es2015` and enable them in your `.babelrc`, and you're good to go.
65 +
66 +### Using a CDN
67 +
68 +If you don't want to use npm to manage client packages, the `react` and `react-dom` npm packages also provide UMD distributions in `dist` folders, which are hosted on a CDN:
69 +
70 +```html
71 +<script src="https://unpkg.com/react@15/dist/react.js"></script>
72 +<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
73 +```
74 +
75 +To load a specific version of `react` and `react-dom`, replace `15` with the version number.
76 +
77 +Minified production versions of React are available at:
78 +
79 +```html
80 +<script src="https://unpkg.com/react@15/dist/react.min.js"></script>
81 +<script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>
82 +```
docs/docs/introducing-jsx.md new
+161
@@ -0,0 +1,161 @@
1 +---
2 +id: introducing-jsx
3 +title: Introducing JSX
4 +permalink: docs/introducing-jsx.html
5 +prev: hello-world.html
6 +next: rendering-elements.html
7 +---
8 +
9 +Consider this variable declaration:
10 +
11 +```js
12 +const element = <h1>Hello, world!</h1>;
13 +```
14 +
15 +This funny tag syntax is neither a string nor HTML.
16 +
17 +It is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript.
18 +
19 +JSX produces React "elements". We will explore rendering them to the DOM in the [next section](/react/docs/rendering-elements.html). Below, you can find the basics of JSX necessary to get you started.
20 +
21 +### Embedding Expressions in JSX
22 +
23 +You can embed any [JavaScript expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Expressions) in JSX by wrapping it in curly braces.
24 +
25 +For example, `2 + 2`, `user.name`, and `formatName(user)` are all valid expressions:
26 +
27 +```js{12}
28 +function formatName(user) {
29 + return user.firstName + ' ' + user.lastName;
30 +}
31 +
32 +const user = {
33 + firstName: 'Harper',
34 + lastName: 'Perez'
35 +};
36 +
37 +const element = (
38 + <h1>
39 + Hello, {formatName(user)}!
40 + </h1>
41 +);
42 +
43 +ReactDOM.render(
44 + element,
45 + document.getElementById('root')
46 +);
47 +```
48 +
49 +[Try it on CodePen.](http://codepen.io/gaearon/pen/PGEjdG?editors=0010)
50 +
51 +We wrapped JSX in parentheses and split it over multiple lines for readability. This also helps avoid the pitfalls of [automatic semicolon insertion](http://stackoverflow.com/q/2846283).
52 +
53 +### JSX is an Expression Too
54 +
55 +After compilation, JSX expressions become regular JavaScript objects.
56 +
57 +This means that you can use JSX inside of `if` statements and `for` loops, assign it to variables, accept it as arguments, and return it from functions:
58 +
59 +```js{3,5}
60 +function getGreeting(user) {
61 + if (user) {
62 + return <h1>Hello, {formatName(user.name)}!</h1>;
63 + } else {
64 + return <h1>Hello, Stranger.</h1>;
65 + }
66 +}
67 +```
68 +
69 +### Specifying Attributes with JSX
70 +
71 +You may use quotes to specify string literals as attributes:
72 +
73 +```js
74 +const element = <div tabIndex="0"></div>;
75 +```
76 +
77 +You may also use curly braces to embed a JavaScript expression in an attribute:
78 +
79 +```js
80 +const element = <img src={user.avatarUrl}></img>;
81 +```
82 +
83 +### Specifying Children with JSX
84 +
85 +If a tag is empty, you may close it immediately with `/>`, like XML:
86 +
87 +```js
88 +const element = <img src={user.avatarUrl} />;
89 +```
90 +
91 +JSX tags may contain children:
92 +
93 +```js
94 +const element = (
95 + <div>
96 + <h1>Hello!</h1>
97 + <h2>Good to see you here.</h2>
98 + </div>
99 +);
100 +```
101 +
102 +>**Caveat:**
103 +>
104 +>Since JSX is closer to JavaScript than HTML, React DOM uses `camelCase` property naming convention instead of HTML attribute names.
105 +>
106 +>For example, `class` becomes [`className`](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) in JSX, and `tabindex` becomes [`tabIndex`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/tabIndex).
107 +
108 +### JSX Prevents Injection Attacks
109 +
110 +It is safe to embed user input in JSX:
111 +
112 +```js
113 +const title = response.potentiallyMaliciousInput;
114 +// This is safe:
115 +const element = <h1>{title}</h1>;
116 +```
117 +
118 +By default, React DOM escapes any values embedded in JSX before rendering them.
119 +
120 +### JSX Represents Objects
121 +
122 +Babel compiles JSX down to `React.createElement()` calls.
123 +
124 +These two examples are identical:
125 +
126 +```js
127 +const element = (
128 + <h1 className="greeting">
129 + Hello, world!
130 + </h1>
131 +);
132 +```
133 +
134 +```js
135 +const element = React.createElement(
136 + 'h1',
137 + {className: 'greeting'},
138 + 'Hello, world!'
139 +);
140 +```
141 +
142 +`React.createElement()` performs a few checks to help you write bug-free code but essentially it creates an object like this:
143 +
144 +```js
145 +// Note: this structure is simplified
146 +const element = {
147 + type: 'h1',
148 + props: {
149 + className: 'greeting',
150 + children: 'Hello, world'
151 + }
152 +};
153 +```
154 +
155 +These objects are called "React elements". You can think of them as descriptions of what you want to see on the screen. React reads these objects and uses them to construct the DOM and keep it up to date.
156 +
157 +We will explore rendering React elements to the DOM in the next section.
158 +
159 +>**Tip:**
160 +>
161 +>We recommend searching for a "Babel" syntax scheme for your editor of choice so that both ES6 and JSX code is properly highlighted.
docs/docs/jsx-in-depth.md new
+336
@@ -0,0 +1,336 @@
1 +---
2 +id: jsx-in-depth
3 +title: JSX In Depth
4 +permalink: docs/jsx-in-depth.html
5 +redirect_from: "/docs/jsx-spread.html"
6 +redirect_from: "/docs/jsx-gotchas.html"
7 +redirect_from: "/tips/if-else-in-JSX.html"
8 +redirect_from: "/tips/self-closing-tag.html"
9 +redirect_from: "/tips/maximum-number-of-jsx-root-nodes.html"
10 +redirect_from: "/tips/children-props-type.html"
11 +---
12 +
13 +Fundamentally, JSX just provides syntactic sugar for the `React.createElement(component, props, ...children)` function. The JSX code:
14 +
15 +```js
16 +<MyButton color="blue" shadowSize={2}>Click Me</MyButton>
17 +```
18 +
19 +compiles into:
20 +
21 +```js
22 +React.createElement(MyButton, {color: "blue", shadowSize: 2}, 'Click Me')
23 +```
24 +
25 +You can also use the self-closing form of the tag if there are no children. So:
26 +
27 +```js
28 +<div className="sidebar" />
29 +```
30 +
31 +compiles into:
32 +
33 +```js
34 +React.createElement('div', {className: 'sidebar'}, null)
35 +```
36 +
37 +If you want to test out how some specific JSX is converted into JavaScript, you can try out [the online Babel compiler](https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Creact%2Cstage-0&code=function%20hello()%20%7B%0A%20%20return%20%3Cdiv%3EHello%20world!%3C%2Fdiv%3E%3B%0A%7D).
38 +
39 +## Specifying The React Element Type
40 +
41 +The first part of a JSX tag determines the type of the React element.
42 +
43 +Capitalized types indicate that the JSX tag is referring to a React component. These tags get compiled into a direct reference to the named variable, so if you use the JSX `<Foo />` expression, `Foo` must be in scope.
44 +
45 +Since JSX compiles into calls to `React.createElement`, the `React` library must also always be in scope from your JSX code.
46 +
47 +For example, both of the imports are necessary in this code, even though 'React' and 'CustomButton' are not directly referenced from JavaScript:
48 +
49 +```js
50 +import React from 'react';
51 +import CustomButton from './CustomButton';
52 +
53 +function WarningButton() {
54 + return <CustomButton color="red" />;
55 +}
56 +```
57 +
58 +If you don't use a JavaScript bundler and added React as a script tag, it is already in scope as a React global.
59 +
60 +You can also refer to a React component using dot-notation from within JSX. This is convenient if you have a single module that exports many React components. For example, if `MyComponents.DatePicker` is a component, you can use it directly from JSX with:
61 +
62 +```js
63 +import React from 'react';
64 +
65 +var MyComponents = {
66 + DatePicker: function(props) {
67 + return <div>imagine a {props.color} datepicker here</div>;
68 + }
69 +}
70 +
71 +function BlueDatePicker() {
72 + return <MyComponents.DatePicker color="blue"} />;
73 +}
74 +```
75 +
76 +When an element type starts with a lowercase letter, it refers to a built-in component like `<div>` or `<span>` and results in a string `'div'` or `'span'` passed to `React.createElement`. Types that start with a capital letter like `<Foo />` compile to `React.createElement(Foo)` and correspond to a component defined or imported in your JavaScript file.
77 +
78 +We recommend naming components with a capital letter. If you do have a component that starts with a lowercase letter, assign it to a capitalized variable before using it in JSX.
79 +
80 +For example, this code will not run as expected:
81 +
82 +```js
83 +import React from 'react';
84 +
85 +function hello(props) {
86 + // This use of <div> is legitimate because div is a valid HTML tag
87 + return <div>Hello {props.toWhat}</div>;
88 +}
89 +
90 +function HelloWorld() {
91 + // This code attempts to create an HTML <hello> tag and fails
92 + return <hello toWhat="World" />;
93 +}
94 +```
95 +
96 +You cannot use a general expression as the React element type. If you do want to use a general expression to indicate the type of the element, just assign it to a capitalized variable first. This often comes up when you want to render a different component based on a prop:
97 +
98 +```js
99 +import React from 'react';
100 +import { PhotoStory, VideoStory } from './stories';
101 +
102 +const components = {
103 + photo: <PhotoStory />,
104 + video: <VideoStory />,
105 +};
106 +
107 +function Story1(props) {
108 + // Not valid JSX
109 + return <components[props.story] />;
110 +}
111 +
112 +function render2(props) {
113 + var MyComponent = components[props.story];
114 +
115 + // Valid JSX
116 + return <MyComponent />;
117 +}
118 +```
119 +
120 +## Props in JSX
121 +
122 +There are several different ways to specify props in JSX.
123 +
124 +### JavaScript Expressions
125 +
126 +You can pass any JavaScript expression as a prop, by surrounding it with `{}`. For example, in this JSX:
127 +
128 +```js
129 +<MyComponent foo={1 + 2 + 3 + 4} />
130 +```
131 +
132 +For `MyComponent`, The value of `props.foo` will be `10` because the expression `1 + 2 + 3 + 4` gets evaluated.
133 +
134 +`if` statements and `for` loops are not expressions in JavaScript, so they can't be used in JSX directly. Instead, you can put these in the surrounding code. For example:
135 +
136 +```js
137 +function NumberDescriber(props) {
138 + var description;
139 + if (props.number % 2 == 0) {
140 + description = <strong>even</strong>;
141 + } else {
142 + description = <i>odd</i>;
143 + }
144 + return <div>{props.number} is an {description} number</div>;
145 +}
146 +```
147 +
148 +### String Literals
149 +
150 +You can pass a string literal as a prop. These two JSX expressions are equivalent:
151 +
152 +```js
153 +<MyComponent message="hello world" />
154 +
155 +<MyComponent message={"hello world"} />
156 +```
157 +
158 +When you pass a string literal, its value is HTML-unescaped. So these two JSX expressions are equivalent:
159 +
160 +```js
161 +<MyComponent message="&lt;3" />
162 +
163 +<MyComponent message={"<3"} />
164 +```
165 +
166 +This behavior is usually not relevant. It's only mentioned here for completeness.
167 +
168 +### Props Default to "True"
169 +
170 +If you pass no value for a prop, it defaults to `true`. These two JSX expressions are equivalent:
171 +
172 +```js
173 +<MyTextBox autocomplete />
174 +
175 +<MyTextBox autocomplete={true} />
176 +```
177 +
178 +In general, we don't recommend using this because it can be confused with the ES6 object shorthand `{foo}` which is short for {foo: foo} rather than `{foo: true}`. This behavior is just there so that it matches the behavior of HTML.
179 +
180 +### Spread Attributes
181 +
182 +If you already have `props` as an object, and you want to pass it in JSX, you can use `...` as a "spread" operator to pass the whole props object. These two render functions are equivalent:
183 +
184 +```js
185 +function render1() {
186 + var props = {left: 'ben', right: 'hector'};
187 + return <MyComponent {...props} />;
188 +}
189 +
190 +function render2() {
191 + return <MyComponent left="ben" right="hector" />;
192 +}
193 +```
194 +
195 +Spread attributes can be useful when you are building generic containers. However, they can also make your code messy by making it easy to pass a lot of irrelevant props to components that don't care about them. We recommend that you use this syntax sparingly.
196 +
197 +## Children in JSX
198 +
199 +In JSX expressions that contain both an opening tag and a closing tag, the content between those tags is passed as a special prop: `props.children`. There are several different ways to pass children:
200 +
201 +### String Literals
202 +
203 +You can put a string between the opening and closing tags and `props.children` will just be that string. This is useful for many of the built-in HTML elements. For example:
204 +
205 +```js
206 +<MyComponent>Hello world!</MyComponent>
207 +```
208 +
209 +This is valid JSX, and `props.children` in `MyComponent` will simply be the string `"Hello world!"`. HTML is unescaped, so you can generally write JSX just like you would write HTML in this way:
210 +
211 +```html
212 +<div>This is valid HTML &amp; JSX at the same time.</div>
213 +```
214 +
215 +JSX removes whitespace at the beginning and ending of a line. It also removes blank lines. New lines adjacent to tags are removed; new lines that occur in the middle of string literals are condensed into a single space. So these all render to the same thing:
216 +
217 +```js
218 +<div>Hello World</div>
219 +
220 +<div>
221 + Hello World
222 +</div>
223 +
224 +<div>
225 + Hello
226 + World
227 +</div>
228 +
229 +<div>
230 +
231 + Hello World
232 +</div>
233 +```
234 +
235 +### JSX Children
236 +
237 +You can provide more JSX elements as the children. This is useful for displaying nested components:
238 +
239 +```js
240 +<MyContainer>
241 + <MyFirstComponent />
242 + <MySecondComponent />
243 +</MyContainer>
244 +```
245 +
246 +You can mix together different types of children, so you can use string literals together with JSX children. This is another way in which JSX is like HTML, so that this is both valid JSX and valid HTML:
247 +
248 +```html
249 +<div>
250 + Here is a list:
251 + <ul>
252 + <li>Item 1</li>
253 + <li>Item 2</li>
254 + </ul>
255 +</div>
256 +```
257 +
258 +A React component can't return multiple React elements, but a single JSX expression can have multiple children, so if you want a component to render multiple things you can wrap it in a `div` like this.
259 +
260 +### JavaScript Expressions
261 +
262 +You can pass any JavaScript expression as children, by enclosing it within `{}`. For example, these expressions are equivalent:
263 +
264 +```js
265 +<MyComponent>foo</MyComponent>
266 +
267 +<MyComponent>{'foo'}</MyComponent>
268 +```
269 +
270 +This is often useful for rendering a list of JSX expressions of arbitrary length. For example, this renders an HTML list:
271 +
272 +```js
273 +function Item(props) {
274 + return <li>{props.message}</li>;
275 +}
276 +
277 +function renderTodoList() {
278 + var todos = ['finish doc', 'submit pr', 'nag dan to review'];
279 + return (
280 + <ul>
281 + {todos.map((message) => <Item key={message} message={message} />)}
282 + </ul>
283 + );
284 +}
285 +```
286 +
287 +JavaScript expressions can be mixed with other types of children. This is often useful in lieu of string templates:
288 +
289 +```js
290 +function Hello(props) {
291 + return <div>Hello {props.addressee}!</div>;
292 +}
293 +```
294 +
295 +Normally, JavaScript expressions inserted in JSX will evaluate to a string, a React element, or a list of those things. However, `props.children` works just like any other prop in that it can pass any sort of data, not just the sorts that React knows how to render. For example, if you have a custom component, you could have it take a callback as `props.children`:
296 +
297 +```js
298 +function ListOfTenThings() {
299 + return (
300 + <Repeat numTimes={10}>
301 + {(index) => <div key={index}>This is item {index} in the list</div>}
302 + </Repeat>
303 + );
304 +}
305 +
306 +// Calls the children callback numTimes to produce a repeated component
307 +function Repeat(props) {
308 + var items = [];
309 + for (var i = 0; i < numTimes; i++) {
310 + items.push(props.children(i));
311 + }
312 + return <div>{items}</div>
313 +}
314 +```
315 +
316 +Children passed to a custom component can be anything, as long as that component transforms them into something React can understand before rendering. This usage is not common, but it works if you want to stretch what JSX is capable of.
317 +
318 +`false`, `null`, 'undefined', and 'true' are valid children. They simply don't render. These JSX expressions will all render to the same thing:
319 +
320 +```js
321 +<div />
322 +
323 +<div></div>
324 +
325 +<div>{false}</div>
326 +
327 +<div>{null}</div>
328 +
329 +<div>{true}</div>
330 +```
331 +
332 +This can be useful to conditionally render React elements. This JSX only renders a `<Header />` if `showHeader` is true:
333 +
334 +```js
335 +<div>{showHeader && <Header />}<Content /></div>
336 +```
docs/docs/lifting-state-up.md new
+239
@@ -0,0 +1,239 @@
1 +---
2 +id: lifting-state-up
3 +title: Lifting State Up
4 +permalink: docs/lifting-state-up.html
5 +prev: state-and-lifecycle.html
6 +next: composition-vs-inheritance.html
7 +---
8 +
9 +Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor. Let's see how this works in action.
10 +
11 +In this section, we will create a temperature calculator that calculates whether the water would boil at a given temperature.
12 +
13 +We will start with a component called `BoilingVerdict`. It accepts the `celsius` temperature as a prop, and prints whether it is enough to boil the water:
14 +
15 +```js{3,5}
16 +function BoilingVerdict(props) {
17 + if (props.celsius >= 100) {
18 + return <p>The water would boil.</p>;
19 + } else {
20 + return <p>The water would not boil.</p>;
21 + }
22 +}
23 +```
24 +
25 +Next, we will create a component called `Calculator`. It renders an `<input>` that lets you enter the temperature, and keeps its value in `this.state.value`.
26 +
27 +Additionally, it renders the `BoilingVerdict` for the current input value.
28 +
29 +```js{5,9,13,17-21}
30 +class Calculator extends React.Component {
31 + constructor(props) {
32 + super(props);
33 + this.handleChange = this.handleChange.bind(this);
34 + this.state = {value: ''};
35 + }
36 +
37 + handleChange(e) {
38 + this.setState({value: e.target.value});
39 + }
40 +
41 + render() {
42 + const value = this.state.value;
43 + return (
44 + <fieldset>
45 + <legend>Enter temperature in Celsius:</legend>
46 + <input
47 + value={value}
48 + onChange={this.handleChange} />
49 + <BoilingVerdict
50 + celsius={parseFloat(value)} />
51 + </fieldset>
52 + );
53 + }
54 +}
55 +```
56 +
57 +[Try it on CodePen.](http://codepen.io/gaearon/pen/Gjxgrj?editors=0010)
58 +
59 +## Adding a Second Input
60 +
61 +Our new requirement is that, in addition to a Celsius input, we provide a Fahrenheit input, and they are kept in sync.
62 +
63 +We can start by extracting a `TemperatureInput` component from `Calculator`. We will add a new `scale` prop to it that can either be `"c"` or `"f"`:
64 +
65 +```js{1-4,19,22}
66 +const scaleNames = {
67 + c: 'Celsius',
68 + f: 'Fahrenheit'
69 +};
70 +
71 +class TemperatureInput extends React.Component {
72 + constructor(props) {
73 + super(props);
74 + this.handleChange = this.handleChange.bind(this);
75 + this.state = {value: ''};
76 + }
77 +
78 + handleChange(e) {
79 + this.setState({value: e.target.value});
80 + }
81 +
82 + render() {
83 + const value = this.state.value;
84 + const scale = this.props.scale;
85 + return (
86 + <fieldset>
87 + <legend>Enter temperature in {scaleNames[scale]}:</legend>
88 + <input value={value}
89 + onChange={this.handleChange} />
90 + </fieldset>
91 + );
92 + }
93 +}
94 +```
95 +
96 +We can now change the `Calculator` to render two separate temperature inputs:
97 +
98 +```js{5,6}
99 +class Calculator extends React.Component {
100 + render() {
101 + return (
102 + <div>
103 + <TemperatureInput scale="c" />
104 + <TemperatureInput scale="f" />
105 + </div>
106 + );
107 + }
108 +}
109 +```
110 +
111 +[Try it on CodePen.](http://codepen.io/gaearon/pen/NRrzOL?editors=0010)
112 +
113 +We have two inputs now, but when you enter the temperature in one of them, the other doesn't update. This contradicts our requirement: we want to keep them in sync.
114 +
115 +We also can't display the `BoilingVerdict` from `Calculator`. The `Calculator` doesn't know the current temperature because it is hidden inside the `TemperatureInput`.
116 +
117 +## Lifting State Up
118 +
119 +First, we will write two functions to convert from Celsius to Fahrenheit and back:
120 +
121 +```js
122 +function toCelsius(fahrenheit) {
123 + return (fahrenheit - 32) * 5 / 9;
124 +}
125 +
126 +function toFahrenheit(celsius) {
127 + return (celsius * 9 / 5) + 32;
128 +}
129 +```
130 +
131 +These two functions convert numbers. We will write another function that takes a string `value` and a converter function as arguments and returns a string. We will use it to calculate the value of one input based on the other input.
132 +
133 +It returns an empty string on an invalid `value`, and it keeps the output rounded to the third decimal place:
134 +
135 +```js
136 +function tryConvert(value, convert) {
137 + const input = parseFloat(value);
138 + if (Number.isNaN(input)) {
139 + return '';
140 + }
141 + const output = convert(input);
142 + const rounded = Math.round(output * 1000) / 1000;
143 + return rounded.toString();
144 +}
145 +```
146 +
147 +For example, `tryConvert('abc', toCelsius)` returns an empty string, and `tryConvert('10.22', toFahrenheit)` returns `'50.396'`.
148 +
149 +Next, we will remove the state from `TemperatureInput`.
150 +
151 +Instead, it will receive both `value` and the `onChange` handler by props:
152 +
153 +```js{8,12}
154 +class TemperatureInput extends React.Component {
155 + constructor(props) {
156 + super(props);
157 + this.handleChange = this.handleChange.bind(this);
158 + }
159 +
160 + handleChange(e) {
161 + this.props.onChange(e.target.value);
162 + }
163 +
164 + render() {
165 + const value = this.props.value;
166 + const scale = this.props.scale;
167 + return (
168 + <fieldset>
169 + <legend>Enter temperature in {scaleNames[scale]}:</legend>
170 + <input value={value}
171 + onChange={this.handleChange} />
172 + </fieldset>
173 + );
174 + }
175 +}
176 +```
177 +
178 +If several components need access to the same state, it is a sign that the state should be lifted up to their closest common ancestor instead. In our case, this is the `Calculator`. We will store the current `value` and `scale` in its state.
179 +
180 +We could have stored the value of both inputs but it turns out to be unnecessary. It is enough to store the value of the most recently changed input, and the scale that it represents. We can then infer the value of the other input based on the current `value` and `scale` alone.
181 +
182 +The inputs stay in sync because their values are computed from the same state:
183 +
184 +```js{6,10,14,18-21,27-28,31-32,34}
185 +class Calculator extends React.Component {
186 + constructor(props) {
187 + super(props);
188 + this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
189 + this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
190 + this.state = {value: '', scale: 'c'};
191 + }
192 +
193 + handleCelsiusChange(value) {
194 + this.setState({scale: 'c', value});
195 + }
196 +
197 + handleFahrenheitChange(value) {
198 + this.setState({scale: 'f', value});
199 + }
200 +
201 + render() {
202 + const scale = this.state.scale;
203 + const value = this.state.value;
204 + const celsius = scale === 'f' ? tryConvert(value, toCelsius) : value;
205 + const fahrenheit = scale === 'c' ? tryConvert(value, toFahrenheit) : value;
206 +
207 + return (
208 + <div>
209 + <TemperatureInput
210 + scale="c"
211 + value={celsius}
212 + onChange={this.handleCelsiusChange} />
213 + <TemperatureInput
214 + scale="f"
215 + value={fahrenheit}
216 + onChange={this.handleFahrenheitChange} />
217 + <BoilingVerdict
218 + celsius={parseFloat(celsius)} />
219 + </div>
220 + );
221 + }
222 +}
223 +```
224 +
225 +[Try it on CodePen.](http://codepen.io/gaearon/pen/ozdyNg?editors=0010)
226 +
227 +Now, no matter which input you edit, `this.state.value` and `this.state.scale` in the `Calculator` get updated. One of the inputs gets the value as is, so any user input is preserved, and the other input value is always recalculated based on it.
228 +
229 +## Lessons Learned
230 +
231 +There should be a single "source of truth" for any data that changes in a React application. Usually, the state is first added to the component that needs it for rendering. Then, if other components also need it, you can lift it up to their closest common ancestor. Instead of trying to sync the state between different components, you should rely on the [top-down data flow](/react/docs/state-and-lifecycle.html#the-data-flows-down).
232 +
233 +Lifting state involves writing more "boilerplate" code than two-way binding approaches, but as a benefit, it takes less work to find and isolate bugs. Since any state "lives" in some component and that component alone can change it, the surface area for bugs is greatly reduced. Additionally, you can implement any custom logic to reject or transform user input.
234 +
235 +If something can be derived from either props or state, it probably shouldn't be in the state. For example, instead of storing both `celsiusValue` and `fahrenheitValue`, we store just the last edited `value` and its `scale`. The value of the other input can always be calculated from them in the `render()` method. This lets us clear or apply rounding to the other field without losing any precision in the user input.
236 +
237 +When you see something wrong in the UI, you can use [React Developer Tools](https://github.com/facebook/react-devtools) to inspect the props and move up the tree until you find the component responsible for updating the state. This lets you trace the bugs to their source:
238 +
239 +<img src="/react/img/docs/react-devtools-state.gif" alt="Monitoring State in React DevTools" width="100%">
docs/docs/lists-and-keys.md new
+299
@@ -0,0 +1,299 @@
1 +---
2 +id: lists-and-keys
3 +title: Lists and Keys
4 +permalink: docs/lists-and-keys.html
5 +prev: conditional-rendering.html
6 +next: forms.html
7 +---
8 +
9 +First, let's review how you transform lists in JavaScript.
10 +
11 +Given the code below, we use the [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) function to take an array of `numbers` and double their values. We assign the new array returned by `map()` to the variable `doubled` and log it:
12 +
13 +```javascript{2}
14 +const numbers = [1, 2, 3, 4, 5];
15 +const doubled = numbers.map((number) => number * 2);
16 +console.log(doubled);
17 +```
18 +
19 +This code logs `[2, 4, 6, 8, 10]` to the console.
20 +
21 +In React, transforming arrays into lists of [elements](/react/docs/rendering-elements.html) is nearly identical.
22 +
23 +### Rendering Multiple Components
24 +
25 +You can build collections of elements and [include them in JSX](/react/docs/introducing-jsx.html#embedding-expressions-in-jsx) using curly braces `{}`.
26 +
27 +Below, we loop through the `numbers` array using the Javascript [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) function. We return an `<li>` element for each item. Finally, we assign the resulting array of elements to `listItems`:
28 +
29 +```javascript{2-4}
30 +const numbers = [1, 2, 3, 4, 5];
31 +const listItems = numbers.map((number) =>
32 + <li>{number}</li>
33 +);
34 +```
35 +
36 +We include the entire `listItems` array inside a `<ul>` element, and [render it to the DOM](/react/docs/rendering-elements.html#rendering-an-element-into-the-dom):
37 +
38 +```javascript{2}
39 +ReactDOM.render(
40 + <ul>{listItems}</ul>,
41 + document.getElementById('root')
42 +);
43 +```
44 +
45 +[Try it out on Codepen.](https://codepen.io/gaearon/pen/GjPyQr?editors=0011)
46 +
47 +This code displays a bullet list of numbers between 1 and 5.
48 +
49 +### Basic List Component
50 +
51 +Usually you would render lists inside a [component](/react/docs/components-and-props.html).
52 +
53 +We can refactor the previous example into a component that accepts an array of `numbers` and outputs an unordered list of elements.
54 +
55 +```javascript{3-5,7,13}
56 +function NumberList(props) {
57 + const numbers = props.numbers;
58 + const listItems = numbers.map((number) =>
59 + <li>{number}</li>
60 + );
61 + return (
62 + <ul>{listItems}</ul>
63 + );
64 +}
65 +
66 +const numbers = [1, 2, 3, 4, 5];
67 +ReactDOM.render(
68 + <NumberList numbers={numbers} />,
69 + document.getElementById('root')
70 +);
71 +```
72 +
73 +When you run this code, you'll be given a warning that a key should be provided for list items. A "key" is a special string attribute you need to include when creating lists of elements. We'll discuss why it's important in the next section.
74 +
75 +Let's assign a `key` to our list items inside `numbers.map()` and fix the missing key issue.
76 +
77 +```javascript{4}
78 +function NumberList(props) {
79 + const numbers = props.numbers;
80 + const listItems = numbers.map((number) =>
81 + <li key={number.toString()}>
82 + {number}
83 + </li>
84 + );
85 + return (
86 + <ul>{listItems}</ul>
87 + );
88 +}
89 +
90 +const numbers = [1, 2, 3, 4, 5];
91 +ReactDOM.render(
92 + <NumberList numbers={numbers} />,
93 + document.getElementById('root')
94 +);
95 +```
96 +
97 +[Try it out on Codepen.](https://codepen.io/gaearon/pen/jrXYRR?editors=0011)
98 +
99 +## Keys
100 +
101 +Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:
102 +
103 +```js{3}
104 +const numbers = [1, 2, 3, 4, 5];
105 +const listItems = numbers.map((number) =>
106 + <li key={number.toString()}>
107 + {number}
108 + </li>
109 +);
110 +```
111 +
112 +The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys:
113 +
114 +```js{2}
115 +const todoItems = todos.map((todo) =>
116 + <li key={todo.id}>
117 + {todo.text}
118 + </li>
119 +);
120 +```
121 +
122 +When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort:
123 +
124 +```js{2,3}
125 +const todoItems = todos.map((todo, index) =>
126 + // Only do this if items have no stable IDs
127 + <li key={index}>
128 + {todo.text}
129 + </li>
130 +);
131 +```
132 +
133 +We don't recommend using indexes for keys if the items can reorder, as that would be slow. You may read an [in-depth explanation about why keys are necessary](/react/docs/reconciliation.html#recursing-on-children) if you're interested.
134 +
135 +### Extracting Components with Keys
136 +
137 +Keys only make sense in the context of the surrounding array.
138 +
139 +For example, if you [extract](/react/docs/components-and-props.html#extracting-components) a `Number` component, you should keep the key on the `<Number />` elements in the array rather than on the root `<li>` element in the `Number` itself.
140 +
141 +**Example: Incorrect Key Usage**
142 +
143 +```javascript{4,5,14,15}
144 +function Number(props) {
145 + const value = props.value;
146 + return (
147 + // Wrong! There is no need to specify the key here:
148 + <li key={value.toString()}>
149 + {value}
150 + </li>
151 + );
152 +}
153 +
154 +function NumberList(props) {
155 + const numbers = props.numbers;
156 + const listItems = numbers.map((item) =>
157 + // Wrong! The key should have been specified here:
158 + <Number value={number} />
159 + );
160 + return (
161 + <ul>
162 + {listItems}
163 + </ul>
164 + );
165 +}
166 +
167 +const numbers = [1, 2, 3, 4, 5];
168 +ReactDOM.render(
169 + <NumberList numbers={numbers} />,
170 + document.getElementById('root')
171 +);
172 +```
173 +
174 +**Example: Correct Key Usage**
175 +
176 +```javascript{2,3,9,10}
177 +function Number(props) {
178 + // Correct! There is no need to specify the key here:
179 + return <li>{props.value}</li>;
180 +}
181 +
182 +function NumberList(props) {
183 + const numbers = props.numbers;
184 + const listItems = numbers.map((number) =>
185 + // Correct! Key should be specified inside the array.
186 + <Number key={number.toString()}
187 + value={number} />
188 + );
189 + return (
190 + <ul>
191 + {listItems}
192 + </ul>
193 + );
194 +}
195 +
196 +const numbers = [1, 2, 3, 4, 5];
197 +ReactDOM.render(
198 + <NumberList numbers={numbers} />,
199 + document.getElementById('root')
200 +);
201 +```
202 +
203 +[Try it out on Codepen.](https://codepen.io/gaearon/pen/ozJEPy?editors=0010)
204 +
205 +A good rule of thumb is that elements inside the `map()` call need keys.
206 +
207 +### Keys Must Only Be Unique Among Siblings
208 +
209 +Keys used within arrays should be unique among their siblings. However they don't need to be globally unique. We can use the same keys when we produce two different arrays:
210 +
211 +```js{2,5,11,12,19,21}
212 +function Blog(props) {
213 + const sidebar = (
214 + <ul>
215 + {props.posts.map((post) =>
216 + <li key={post.id}>
217 + {post.title}
218 + </li>
219 + )}
220 + </ul>
221 + );
222 + const content = props.posts.map((post) =>
223 + <div key={post.id}>
224 + <h3>{post.title}</h3>
225 + <p>{post.content}</p>
226 + </div>
227 + );
228 + return (
229 + <div>
230 + {sidebar}
231 + <hr />
232 + {content}
233 + </div>
234 + );
235 +}
236 +
237 +const posts = [
238 + {id: 1, title: 'Hello World', content: 'Welcome to learning React!'},
239 + {id: 2, title: 'Installation', content: 'You can install React from npm.'}
240 +];
241 +ReactDOM.render(
242 + <Blog posts={posts} />,
243 + document.getElementById('root')
244 +);
245 +```
246 +
247 +[Try it out on CodePen.](https://codepen.io/gaearon/pen/NRZYGN?editors=0010)
248 +
249 +Keys serve as a hint to React but they don't get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name:
250 +
251 +```js{3,4}
252 +const content = posts.map((post) =>
253 + <Post
254 + key={post.id}
255 + id={post.id}
256 + title={post.title} />
257 +);
258 +```
259 +
260 +With the example above, the `Post` component can read `props.id`, but not `props.key`.
261 +
262 +### Embedding map() in JSX
263 +
264 +In the examples above we declared a separate `listItems` variable and included it in JSX:
265 +
266 +```js{3-6}
267 +function NumberList(props) {
268 + const numbers = props.numbers;
269 + const listItems = numbers.map((number) =>
270 + <Number key={number.toString()}
271 + value={number} />
272 + );
273 + return (
274 + <ul>
275 + {listItems}
276 + </ul>
277 + );
278 +}
279 +```
280 +
281 +JSX allows [embedding any expressions](/react/docs/introducing-jsx.html#embedding-expressions-in-jsx) in curly braces so we could inline the `map()` result:
282 +
283 +```js{5-8}
284 +function NumberList(props) {
285 + const numbers = props.numbers;
286 + return (
287 + <ul>
288 + {numbers.map((number) =>
289 + <Number key={number.toString()}
290 + value={number} />
291 + )}
292 + </ul>
293 + );
294 +}
295 +```
296 +
297 +[Try it out on CodePen.](https://codepen.io/gaearon/pen/BLvYrB?editors=0010)
298 +
299 +Sometimes this results in clearer code, but this style can also be abused. Like in JavaScript, it is up to you to decide whether it is worth extracting a variable for readability. Keep in mind that if the `map()` body is too nested, it might be a good time to [extract a component](/react/docs/components-and-props.html#extracting-components).
docs/docs/optimizing-performance.md new
+230
@@ -0,0 +1,230 @@
1 +---
2 +id: optimizing-performance
3 +title: Optimizing Performance
4 +permalink: docs/optimizing-performance.html
5 +redirect_from: "/docs/advanced-performance.html"
6 +---
7 +
8 +Internally, React uses several clever techniques to minimize the number of costly DOM operations required to update the UI. For many applications, using React will lead to a fast user interface without doing much work to specifically optimize for performance. Nevertheless, there are several ways you can speed up your React application.
9 +
10 +## Use The Production Build
11 +
12 +If you're benchmarking or experiencing performance problems in your React apps, make sure you're testing with the minified production build:
13 +
14 +* For Create React App, you need to run `npm run build` and follow the instructions.
15 +* For single-file builds, we offer production-ready `.min.js` versions.
16 +* For Browserify, you need to run it with `NODE_ENV=production`.
17 +* For Webpack, you need to add this to plugins in your production config:
18 +
19 +```js
20 +new webpack.DefinePlugin({
21 + 'process.env': {
22 + NODE_ENV: JSON.stringify('production')
23 + }
24 +}),
25 +new webpack.optimize.UglifyJsPlugin()
26 +```
27 +
28 +The development build includes extra warnings that are helpful when building your apps, but it is slower due to the extra bookkeeping it does.
29 +
30 +## Avoid Reconciliation
31 +
32 +React builds and maintains an internal representation of the rendered UI. It includes the React elements you return from your components. This representation lets React avoid creating DOM nodes and accessing existing ones beyond necessity, as that can be slower than operations on JavaScript objects. Sometimes it is referred to as a "virtual DOM", but it works the same way on React Native.
33 +
34 +When a component's props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM.
35 +
36 +In some cases, your component can speed all of this up by overriding the lifecycle function `shouldComponentUpdate`, which is triggered before the re-rendering process starts. The default implementation of this function returns `true`, leaving React to perform the update:
37 +
38 +```javascript
39 +shouldComponentUpdate(nextProps, nextState) {
40 + return true;
41 +}
42 +```
43 +
44 +If you know that in some situations your component doesn't need to update, you can return `false` from `shouldComponentUpdate` instead, to skip the whole rendering process, including calling `render()` on this component and below.
45 +
46 +## shouldComponentUpdate In Action
47 +
48 +Here's a subtree of components. For each one, `SCU` indicates what `shouldComponentUpdate` returned, and `vDOMEq` indicates whether the rendered React elements were equivalent. Finally, the circle's color indicates whether the component had to be reconciled or not.
49 +
50 +<figure><img src="/react/img/docs/should-component-update.png" /></figure>
51 +
52 +Since `shouldComponentUpdate` returned `false` for the subtree rooted at C2, React did not attempt to render C2, and thus didn't even have to invoke `shouldComponentUpdate` on C4 and C5.
53 +
54 +For C1 and C3, `shouldComponentUpdate` returned `true`, so React had to go down to the leaves and check them. For C6 `shouldComponentUpdate` returned `true`, and since the rendered elements weren't equivalent React had to update the DOM.
55 +
56 +The last interesting case is C8. React had to render this component, but since the React elements it returned were equal to the previously rendered ones, it didn't have to update the DOM.
57 +
58 +Note that React only had to do DOM mutations for C6, which was inevitable. For C8, it bailed out by comparing the rendered React elements, and for C2's subtree and C7, it didn't even have to compare the elements as we bailed out on `shouldComponentUpdate`, and `render` was not called.
59 +
60 +## Examples
61 +
62 +If the only way your component ever changes is when the `props.color` or the `state.count` variable changes, you could have `shouldComponentUpdate` check that:
63 +
64 +```javascript
65 +class CounterButton extends React.Component {
66 + constructor(props) {
67 + super(props);
68 + this.state = {count: 1};
69 + }
70 +
71 + shouldComponentUpdate(nextProps, nextState) {
72 + if (this.props.color !== nextProps.color) {
73 + return true;
74 + }
75 + if (this.state.count !== nextState.count) {
76 + return true;
77 + }
78 + return false;
79 + }
80 +
81 + render() {
82 + <button
83 + color={this.props.color}
84 + onClick={() => this.setState(state => ({count: state.count + 1}))}>
85 + Count: {this.state.count}
86 + </button>
87 + }
88 +}
89 +```
90 +
91 +In this code, `shouldComponentUpdate` is just checking if there is any change in `props.color` or `state.count`. If those values don't change, the component doesn't update. If your component got more complex, you could use a similar pattern of doing a "shallow comparison" between all the fields of `props` and `state` to determine if the component should update. This pattern is common enough that React provides a helper to use this logic - just inherit from `React.PureComponent`. So this code is a simpler way to achieve the same thing:
92 +
93 +```js
94 +class CounterButton extends React.PureComponent {
95 + constructor(props) {
96 + super(props);
97 + this.state = {count: 1};
98 + }
99 +
100 + render() {
101 + <button
102 + color={this.props.color}
103 + onClick={() => this.setState(state => ({count: state.count + 1}))}>
104 + Count: {this.state.count}
105 + </button>
106 + }
107 +}
108 +```
109 +
110 +Most of the time, you can use `React.PureComponent` instead of writing your own `shouldComponentUpdate`. It only does a shallow comparison, so you can't use it if the props or state may have been mutated in a way that a shallow comparison would miss.
111 +
112 +This can be a problem with more complex data structures. For example, let's say you want a `ListOfWords` component to render a comma-separated list of words, with a parent `WordAdder` component that lets you click a button to add a word to the list. This code does *not* work correctly:
113 +
114 +```javascript
115 +class ListOfWords extends React.PureComponent {
116 + render() {
117 + return <div>{this.props.words.join(',')}</div>;
118 + }
119 +}
120 +
121 +class WordAdder extends React.Component {
122 + constructor(props) {
123 + super(props);
124 + this.state = {
125 + words: ['marklar']
126 + };
127 + this.handleClick = this.handleClick.bind(this);
128 + }
129 +
130 + handleClick() {
131 + // This section is bad style and causes a bug
132 + const words = this.state.words;
133 + words.push('marklar');
134 + this.setState({words: words});
135 + }
136 +
137 + render() {
138 + return (
139 + <div>
140 + <button onClick={this.handleClick} />
141 + <ListOfWords words={this.state.words} />
142 + </div>
143 + );
144 + }
145 +}
146 +```
147 +
148 +The problem is that `PureComponent` will do a simple comparison between the old and new values of `this.props.words`. Since this code mutates the `words` array in the `handleClick` method of `WordAdder`, the old and new values of `this.props.words` will compare as equal, even though the actual words in the array have changed. The `ListOfWords` will thus not update even though it has new words that shoud be rendered.
149 +
150 +## The Power Of Not Mutating Data
151 +
152 +The simplest way to avoid this problem is to avoid mutating values that you are using as props or state. For example, the `handleClick` method above could be rewritten using `concat` as:
153 +
154 +```javascript
155 +handleClick() {
156 + this.setState(prevState => ({
157 + words: prevState.words.concat(['marklar'])
158 + }));
159 +}
160 +```
161 +
162 +ES6 supports a [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator) for arrays which can make this easier. If you're using Create React App, this syntax is available by default.
163 +
164 +```js
165 +handleClick() {
166 + this.setState(prevState => ({
167 + words: [...prevState.words, 'marklar'],
168 + }));
169 +};
170 +```
171 +
172 +You can also rewrite code that mutates objects to avoid mutation, in a similar way. For example, let's say we have an object named `colormap` and we want to write a function that changes `colormap.right` to be `'blue'`. We could write:
173 +
174 +```js
175 +function updateColorMap(colormap) {
176 + colormap.right = 'blue';
177 +}
178 +```
179 +
180 +To write this without mutating the original object, we can use [Object.assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) method:
181 +
182 +```js
183 +function updateColorMap(colormap) {
184 + return Object.assign({}, colormap, {right: 'blue'});
185 +}
186 +```
187 +
188 +`updateColorMap` now returns a new object, rather than mutating the old one. `Object.assign` is in ES6 and requires a polyfill.
189 +
190 +There is a JavaScript proposal to add [object spread properties](https://github.com/sebmarkbage/ecmascript-rest-spread) to make it easier to update objects without mutation as well:
191 +
192 +```js
193 +function updateColorMap(colormap) {
194 + return {...colormap, right: 'blue'};
195 +}
196 +```
197 +
198 +If you're using Create React App, both `Object.assign` and the object spread syntax are available by default.
199 +
200 +## Using Immutable Data Structures
201 +
202 +[Immutable.js](https://github.com/facebook/immutable-js) is another way to solve this problem. It provides immutable, persistent collections that work via structural sharing:
203 +
204 +* *Immutable*: once created, a collection cannot be altered at another point in time.
205 +* *Persistent*: new collections can be created from a previous collection and a mutation such as set. The original collection is still valid after the new collection is created.
206 +* *Structural Sharing*: new collections are created using as much of the same structure as the original collection as possible, reducing copying to a minimum to improve performance.
207 +
208 +Immutability makes tracking changes cheap. A change will always result in a new object so we only need to check if the reference to the object has changed. For example, in this regular JavaScript code:
209 +
210 +```javascript
211 +var x = { foo: "bar" };
212 +var y = x;
213 +y.foo = "baz";
214 +x === y; // true
215 +```
216 +
217 +Although `y` was edited, since it's a reference to the same object as `x`, this comparison returns `true`. You can write similar code with immutable.js:
218 +
219 +```javascript
220 +var SomeRecord = Immutable.Record({ foo: null });
221 +var x = new SomeRecord({ foo: 'bar' });
222 +var y = x.set('foo', 'baz');
223 +x === y; // false
224 +```
225 +
226 +In this case, since a new reference is returned when mutating `x`, we can safely assume that `x` has changed.
227 +
228 +Two other libraries that can help use immutable data are [seamless-immutable](https://github.com/rtfeldman/seamless-immutable) and [immutability-helper](https://github.com/kolodny/immutability-helper).
229 +
230 +Immutable data structures provide you with a cheap way to track changes on objects, which is all we need to implement `shouldComponentUpdate`. This can often provide you with a nice performance boost.
docs/docs/react-without-es6.md new
+221
@@ -0,0 +1,221 @@
1 +---
2 +id: react-without-es6
3 +title: React Without ES6
4 +permalink: docs/react-without-es6.html
5 +---
6 +
7 +Normally you would define a React component as a plain JavaScript class:
8 +
9 +```javascript
10 +class Greeting extends React.Component {
11 + render() {
12 + return <h1>Hello, {this.props.name}</h1>;
13 + }
14 +}
15 +```
16 +
17 +If you don't use ES6 yet, you may use the `React.createClass` helper instead:
18 +
19 +
20 +```javascript
21 +var Greeting = React.createClass({
22 + render: function() {
23 + return <h1>Hello, {this.props.name}</h1>;
24 + }
25 +});
26 +```
27 +
28 +The API of ES6 classes is similar to `React.createClass` with a few exceptions.
29 +
30 +## Declaring Prop Types and Default Props
31 +
32 +With functions and ES6 classes, `propTypes` and `defaultProps` are defined as properties on the components themselves:
33 +
34 +```javascript
35 +class Greeting extends React.Component {
36 + // ...
37 +}
38 +
39 +Greeting.propTypes = {
40 + name: React.PropTypes.string
41 +};
42 +
43 +Greeting.defaultProps = {
44 + name: 'Mary'
45 +};
46 +```
47 +
48 +With `React.createClass()`, you need to define `propTypes` as a property on the passed object, and `getDefaultProps()` as a function on it:
49 +
50 +```javascript
51 +var Greeting = React.createClass({
52 + propTypes: {
53 + name: React.PropTypes.string
54 + },
55 +
56 + getDefaultProps: function() {
57 + return {
58 + name: 'Mary'
59 + };
60 + },
61 +
62 + // ...
63 +
64 +});
65 +```
66 +
67 +## Setting the Initial State
68 +
69 +In ES6 classes, you can define the initial state by assigning `this.state` in the constructor:
70 +
71 +```javascript
72 +class Counter extends React.Component {
73 + constructor(props) {
74 + super(props);
75 + this.state = {count: props.initialCount};
76 + }
77 + // ...
78 +}
79 +```
80 +
81 +With `React.createClass()`, you have to provide a separate `getInitialState` method that returns the initial state:
82 +
83 +```javascript
84 +var Counter = React.createClass({
85 + getInitialState: function() {
86 + return {count: this.props.initialCount};
87 + },
88 + // ...
89 +});
90 +```
91 +
92 +## Autobinding
93 +
94 +In React components declared as ES6 classes, methods follow the same semantics as regular ES6 classes. This means that they don't automatically bind `this` to the instance. You'll have to explicitly use `.bind(this)` in the constructor:
95 +
96 +```javascript
97 +class SayHello extends React.Component {
98 + constructor(props) {
99 + super(props);
100 + // This line is important!
101 + this.handleClick = this.handleClick.bind(this);
102 + }
103 +
104 + handleClick() {
105 + alert('Hello!');
106 + }
107 +
108 + render() {
109 + // Because `this.handleClick` is bound, we can use it as an event handler.
110 + return (
111 + <button onClick={this.handleClick}>
112 + Say hello
113 + </button>
114 + );
115 + }
116 +}
117 +```
118 +
119 +With `React.createClass()`, this is not necessary because it binds all methods:
120 +
121 +```javascript
122 +var SayHello = React.createClass({
123 + handleClick: function() {
124 + alert('Hello!');
125 + },
126 +
127 + render: function() {
128 + return (
129 + <button onClick={this.handleClick}>
130 + Say hello
131 + </button>
132 + );
133 + }
134 +});
135 +```
136 +
137 +This means writing ES6 classes comes with a little more boilerplate code for event handlers, but the upside is slightly better performance in large applications.
138 +
139 +If the boilerplate code is too unattractive to you, you may enable the **experimental** [Class Properties](https://babeljs.io/docs/plugins/transform-class-properties/) syntax proposal with Babel:
140 +
141 +
142 +```javascript
143 +class SayHello extends React.Component {
144 + // WARNING: this syntax is experimental!
145 + // Using an arrow here binds the method:
146 + handleClick = () => {
147 + alert('Hello!');
148 + }
149 +
150 + render() {
151 + return (
152 + <button onClick={this.handleClick}>
153 + Say hello
154 + </button>
155 + );
156 + }
157 +}
158 +```
159 +
160 +Please note that the syntax above is **experimental** and the syntax may change, or the proposal might not make it into the language.
161 +
162 +If you'd rather play it safe, you have a few options:
163 +
164 +* Bind methods in the constructor.
165 +* Use arrow functions, e.g. `onClick={(e) => this.handleClick(e)})`.
166 +* Keep using `React.createClass()`.
167 +
168 +## Mixins
169 +
170 +>**Note:**
171 +>
172 +>ES6 launched without any mixin support. Therefore, there is no support for mixins when you use React with ES6 classes.
173 +>
174 +>**We also found numerous issues in codebases using mixins, [and don't recommend using them in the new code](/react/blog/2016/07/13/mixins-considered-harmful.html).**
175 +>
176 +>This section exists only for the reference.
177 +
178 +Sometimes very different components may share some common functionality. These are sometimes called [cross-cutting concerns](https://en.wikipedia.org/wiki/Cross-cutting_concern). [`React.createClass`](/react/docs/top-level-api.html#react.createclass) lets you use a legacy `mixins` system for that.
179 +
180 +One common use case is a component wanting to update itself on a time interval. It's easy to use `setInterval()`, but it's important to cancel your interval when you don't need it anymore to save memory. React provides [lifecycle methods](/react/docs/working-with-the-browser.html#component-lifecycle) that let you know when a component is about to be created or destroyed. Let's create a simple mixin that uses these methods to provide an easy `setInterval()` function that will automatically get cleaned up when your component is destroyed.
181 +
182 +```javascript
183 +var SetIntervalMixin = {
184 + componentWillMount: function() {
185 + this.intervals = [];
186 + },
187 + setInterval: function() {
188 + this.intervals.push(setInterval.apply(null, arguments));
189 + },
190 + componentWillUnmount: function() {
191 + this.intervals.forEach(clearInterval);
192 + }
193 +};
194 +
195 +var TickTock = React.createClass({
196 + mixins: [SetIntervalMixin], // Use the mixin
197 + getInitialState: function() {
198 + return {seconds: 0};
199 + },
200 + componentDidMount: function() {
201 + this.setInterval(this.tick, 1000); // Call a method on the mixin
202 + },
203 + tick: function() {
204 + this.setState({seconds: this.state.seconds + 1});
205 + },
206 + render: function() {
207 + return (
208 + <p>
209 + React has been running for {this.state.seconds} seconds.
210 + </p>
211 + );
212 + }
213 +});
214 +
215 +ReactDOM.render(
216 + <TickTock />,
217 + document.getElementById('example')
218 +);
219 +```
220 +
221 +If a component is using multiple mixins and several mixins define the same lifecycle method (i.e. several mixins want to do some cleanup when the component is destroyed), all of the lifecycle methods are guaranteed to be called. Methods defined on mixins run in the order mixins were listed, followed by a method call on the component.
docs/docs/react-without-jsx.md new
+52
@@ -0,0 +1,52 @@
1 +---
2 +id: react-without-jsx
3 +title: React Without JSX
4 +permalink: docs/react-without-jsx.html
5 +---
6 +
7 +JSX is not a requirement for using React. Using React without JSX is especially convenient when you don't want to set up compilation in your build environment.
8 +
9 +Each JSX element is just syntactic sugar for calling `React.createElement(component, props, ...children)`. So, anything you can do with JSX can also be done with just plain JavaScript.
10 +
11 +For example, this code written with JSX:
12 +
13 +```js
14 +class Hello extends React.Component {
15 + render() {
16 + return <div>Hello {this.props.toWhat}</div>;
17 + }
18 +}
19 +
20 +ReactDOM.render(
21 + <Hello toWhat="World" />,
22 + document.getElementById('root')
23 +);
24 +```
25 +
26 +can be compiled to this code that does not use JSX:
27 +
28 +```js
29 +class Hello extends React.Component {
30 + render() {
31 + return React.createElement('div', null, `Hello ${this.props.toWhat}`);
32 + }
33 +}
34 +
35 +ReactDOM.render(React.createElement(Hello, {toWhat: 'World'}, null),
36 + document.getElementById('root'));
37 +```
38 +
39 +If you're curious to see more examples of how JSX is converted to JavaScript, you can try out [the online Babel compiler](https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Creact%2Cstage-0&code=function%20hello()%20%7B%0A%20%20return%20%3Cdiv%3EHello%20world!%3C%2Fdiv%3E%3B%0A%7D).
40 +
41 +The component can either be provided as a string, or as a subclass of `React.Component`, or a plain function for stateless components.
42 +
43 +If you get tired of typing `React.createElement` so much, one common pattern is to assign a shorthand:
44 +
45 +```js
46 +var e = React.createElement;
47 +
48 +ReactDOM.render(e('div', null, 'Hello World'),
49 + document.getElementById('root'));
50 +```
51 +
52 +If you use this shorthand form for `React.createElement`, it can be almost as convenient to use React without JSX.
docs/docs/reconciliation.md new
+153
@@ -0,0 +1,153 @@
1 +---
2 +id: reconciliation
3 +title: Reconciliation
4 +permalink: docs/reconciliation.html
5 +---
6 +
7 +React provides a declarative API so that you don't have to worry about exactly what changes on every update. This makes writing applications a lot easier, but it might not be obvious how this is implemented within React. This article explains the choices we made in React's "diffing" algorithm so that component updates are predictable while being fast enough for high-performance apps.
8 +
9 +## Motivation
10 +
11 +When you use React, at a single point in time you can think of the `render()` function as creating a tree of React elements. On the next state or props update, that `render()` function will return a different tree of React elements. React then needs to figure out how to efficiently update the UI to match the most recent tree.
12 +
13 +There are some generic solutions to this algorithmic problem of generating the minimum number of operations to transform one tree into another. However, the [state of the art algorithms](http://grfia.dlsi.ua.es/ml/algorithms/references/editsurvey_bille.pdf) have a complexity in the order of O(n<sup>3</sup>) where n is the number of elements in the tree.
14 +
15 +If we used this in React, displaying 1000 elements would require in the order of one billion comparisons. This is far too expensive. Instead, React implements a heuristic O(n) algorithm based on two assumptions:
16 +
17 +1. Two elements of different types will produce different trees.
18 +2. The developer can hint at which child elements may be stable across different renders with a `key` prop.
19 +
20 +In practice, these assumptions are valid for almost all practical use cases.
21 +
22 +## The Diffing Algorithm
23 +
24 +When diffing two trees, React first compares the the two root elements. The behavior is different depending on the types of the root elements.
25 +
26 +### Elements Of Different Types
27 +
28 +Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch. Going from `<a>` to `<img>`, or from `<Article>` to `<Comment>`, or from `<Button>` to `<div>` - any of those will lead to a full rebuild.
29 +
30 +When tearing down a tree, old DOM nodes are destroyed. Component instances receive `componentWillUnmount()`. When building up a new tree, new DOM nodes are inserted into the DOM. Component instances receive `componentWillMount()` and then `componentDidMount()`. Any state associated with the old tree is lost.
31 +
32 +Any componts below the root will also get unmounted and have their state destroyed. For example, when diffing:
33 +
34 +```xml
35 +<div>
36 + <Counter />
37 +</div>
38 +
39 +<span>
40 + <Counter />
41 +</span>
42 +```
43 +
44 +This will destroy the old `Counter` and remount a new one.
45 +
46 +### DOM Elements Of The Same Type
47 +
48 +When comparing two React DOM elements of the same type, React looks at the attributes of both, keeps the same underlying DOM node, and only updates the changed attributes. For example:
49 +
50 +```xml
51 +<div className="before" title="stuff" />
52 +
53 +<div className="after" title="stuff" />
54 +```
55 +
56 +By comparing these two elements, React knows to only modify the `className` on the underlying DOM node.
57 +
58 +When updating `style`, React also knows to update only the properties that changed. For example:
59 +
60 +```xml
61 +<div style={{'{{'}}color: 'red', fontWeight: 'bold'}} />
62 +
63 +<div style={{'{{'}}color: 'green', fontWeight: 'bold'}} />
64 +```
65 +
66 +When converting between these two elements, React knows to only modify the `color` style, not the `fontWeight`.
67 +
68 +After handling the DOM node, React then recurses on the children.
69 +
70 +### Component Elements Of The Same Type
71 +
72 +When a component updates, the instance stays the same, so that state is maintained across renders. React updates the props of the underlying component instance to match the new element, and calls `componentWillReceiveProps()` and `componentWillUpdate()` on the underlying instance.
73 +
74 +Next, the `render()` method is called and the diff algorithm recurses on the previous result and the new result.
75 +
76 +### Recursing On Children
77 +
78 +By default, when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there's a difference.
79 +
80 +For example, when adding an element at the end of the children, converting between these two trees works well:
81 +
82 +```xml
83 +<ul>
84 + <li>first</li>
85 + <li>second</li>
86 +</ul>
87 +
88 +<ul>
89 + <li>first</li>
90 + <li>second</li>
91 + <li>third</li>
92 +</ul>
93 +```
94 +
95 +React will match the two `<li>first</li>` trees, match the two `<li>second</li>` trees, and then insert the `<li>third</li>` tree.
96 +
97 +If you implement it naively, inserting an element at the beginning has worse performance. For example, converting between these two trees works poorly:
98 +
99 +```xml
100 +<ul>
101 + <li>Duke</li>
102 + <li>Villanova</li>
103 +</ul>
104 +
105 +<ul>
106 + <li>Connecticut</li>
107 + <li>Duke</li>
108 + <li>Villanova</li>
109 +</ul>
110 +```
111 +
112 +React will mutate every child instead of realizing it can keep the `<li>Duke</li>` and `<li>Villanova</li>` subtrees intact. This inefficiency can be a problem.
113 +
114 +### Keys
115 +
116 +In order to solve this issue, React supports a `key` attribute. When children have keys, React uses the key to match children in the original tree with children in the subsequent tree. For example, adding a `key` to our inefficient example above can make the tree conversion efficient:
117 +
118 +```xml
119 +<ul>
120 + <li key="2015"}>Duke</li>
121 + <li key="2016"}>Villanova</li>
122 +</ul>
123 +
124 +<ul>
125 + <li key="2014"}>Connecticut</li>
126 + <li key="2015"}>Duke</li>
127 + <li key="2016"}>Villanova</li>
128 +</ul>
129 +```
130 +
131 +Now React knows that the element with key `'2014'` is the new one, and the elements with the keys `'2015'` and `'2016'` have just moved.
132 +
133 +In practice, finding a key is usually not hard. The element you are going to display may already have a unique ID, so the key can just come from your data:
134 +
135 +```js
136 +<li key={item.id}>{item.name}</li>
137 +```
138 +
139 +When that's not the case, you can add a new ID property to your model or hash some parts of the content to generate a key. The key only has to be unique among its siblings, not globally unique.
140 +
141 +As a last resort, you can pass item's index in the array as a key. This can work well if the items are never reordered, but reorders will be slow.
142 +
143 +## Tradeoffs
144 +
145 +It is important to remember that the reconciliation algorithm is an implementation detail. React could rerender the whole app on every action; the end result would be the same. We are regularly refining the heuristics in order to make common use cases faster.
146 +
147 +In the current implementation, you can express the fact that a subtree has been moved amongst its siblings, but you cannot tell that it has moved somewhere else. The algorithm will rerender that full subtree.
148 +
149 +Because React relies on heuristics, if the assumptions behind them are not met, performance will suffer.
150 +
151 +1. The algorithm will not try to match subtrees of different component types. If you see yourself alternating between two component types with very similar output, you may want to make it the same type. In practice, we haven't found this to be an issue.
152 +
153 +2. Keys should be stable, predictable, and unique. Unstable keys (like those produced by `Math.random()`) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.
docs/docs/ref-01-top-level-api.it-IT.md deleted
-195
@@ -1,195 +0,0 @@
1 ----
2 -id: top-level-api-it-IT
3 -title: API di Livello Elevato
4 -permalink: docs/top-level-api-it-IT.html
5 -next: component-api-it-IT.html
6 -redirect_from: "/docs/reference.html"
7 ----
8 -
9 -## React
10 -
11 -`React` è il punto di ingresso alla libreria React. Se stai usando uno dei pacchetti precompilati, è disponibile come variabile globale; se stai usando i moduli CommonJS puoi richiederlo con `require()`.
12 -
13 -
14 -### React.Component
15 -
16 -```javascript
17 -class Component
18 -```
19 -
20 -Questa è la classe base per i componenti React quando sono definiti usando le classi ES6. Vedi [Componenti Riutilizzabili](/react/docs/reusable-components.html#es6-classes) per usare le classi ES6 con React. Per i metodi forniti dalla classe base, vedi la [API dei Componenti](/react/docs/component-api.html).
21 -
22 -
23 -### React.createClass
24 -
25 -```javascript
26 -ReactClass createClass(object specification)
27 -```
28 -
29 -Crea la classe di un componente, data una specifica. Un componente implementa un metodo `render` che restituisce **un singolo** figlio. Tale figlio può avere una struttura di fogli arbitrariamente profonda. Una cosa che rende i componenti diversi dalle classi prototipiche standard è che non hai bisogno di chiamare `new` su di esse. Sono delle convenienti astrazioni che costruiscono (attraverso `new`) istanze dietro le quinte per te.
30 -
31 -Per maggiori informazioni sull'oggetto specifica, vedi [Specifiche dei Componenti e Ciclo di Vita](/react/docs/component-specs.html).
32 -
33 -
34 -### React.createElement
35 -
36 -```javascript
37 -ReactElement createElement(
38 - string/ReactClass type,
39 - [object props],
40 - [children ...]
41 -)
42 -```
43 -
44 -Crea e restituisce un nuovo `ReactElement` del tipo desiderato. L'argomento `type` può essere una stringa contenente il nome di un tag HTML (ad es. 'div', 'span', etc), oppure una `ReactClass` (creata attraverso `React.createClass`).
45 -
46 -
47 -### React.cloneElement
48 -
49 -```
50 -ReactElement cloneElement(
51 - ReactElement element,
52 - [object props],
53 - [children ...]
54 -)
55 -```
56 -
57 -Clona e restituisce un nuovo `ReactElement` usando `element` come punto di partenza. L'elemento risultante avrà le proprietà dell'elemento originale, con le nuove proprietà unite in maniera superficiale. I figli esistenti sono sostituiti dai figli passati come `children`. Diversamente da `React.addons.cloneWithProps`, `key` e `ref` dell'elemento originale saranno preservati. Non esiste alcun comportamento speciale per riunire le proprietà (diversamente da `cloneWithProps`). Vedi l'[articolo del blog sulla v0.13 RC2](/react/blog/2015/03/03/react-v0.13-rc2.html) per maggiori dettagli.
58 -
59 -
60 -### React.createFactory
61 -
62 -```javascript
63 -factoryFunction createFactory(
64 - string/ReactClass type
65 -)
66 -```
67 -
68 -Restituisce una funzione che produce ReactElements di un tipo desiderato. Come `React.createElement`,
69 -l'argomento `type` può essere sia la stringa contenente il nome di un tag HTML (ad es. 'div', 'span', etc), oppure una
70 -`ReactClass`.
71 -
72 -
73 -### ReactDOM.render
74 -
75 -```javascript
76 -ReactComponent render(
77 - ReactElement element,
78 - DOMElement container,
79 - [function callback]
80 -)
81 -```
82 -
83 -Effettua il rendering di un ReactElement nel DOM all'interno dell'elemento `container` fornito e restituisce un [riferimento](/react/docs/more-about-refs-it-IT.html) al componente (oppure restituisce `null` per i [componenti privi di stato](/react/docs/reusable-components-it-IT.html#stateless-functions)).
84 -
85 -Se il rendering del ReactElement è stato precedentemente effettuato all'interno di `container`, questa operazione effettuerà un aggiornamento su di esso e modificherà il DOM in modo necessario a riflettere il più recente componente React.
86 -
87 -Se la callback opzionale è fornita, sarà eseguita dopo che il rendering o l'aggiornamento del componente sono stati effettuati.
88 -
89 -> Nota:
90 ->
91 -> `ReactDOM.render()` controlla i contenuti del nodo contenitore che viene passato come argomento `container`. Gli elementi DOM
92 -> esistenti al suo interno sono sostituiti quando viene chiamata la prima volta. Le chiamate successive usano l'algoritmo di
93 -> differenza di React per aggiornamenti efficienti.
94 ->
95 -> `ReactDOM.render()` non modifica il nodo contenitore (modifica soltanto i figli del contenitore). In
96 -> futuro potrebbe essere possibile inserire un componente in un nodo DOM esistente senza sovrascrivere i figli esistenti.
97 -
98 -
99 -### ReactDOM.unmountComponentAtNode
100 -
101 -```javascript
102 -boolean unmountComponentAtNode(DOMElement container)
103 -```
104 -
105 -Rimuove un componente React montato nel DOM e ripulisce i suoi gestori di evento e lo stato. Se nessun componente è stato montato nel contenitore `container`, chiamare questa funzione non ha alcun effetto. Restituisce `true` se il componente è stato smontato e `false` se non è stato trovato un componente da smontare.
106 -
107 -
108 -### ReactDOM.renderToString
109 -
110 -```javascript
111 -string renderToString(ReactElement element)
112 -```
113 -
114 -Effettua il rendering di un ReactElement come il suo HTML iniziale. Questo dovrebe essere utilizzato soltanto lato server. React restituirà una stringa di HTML. Puoi usare questo metodo per generare HTML sul server e inviare il markup come risposta alla richiesta iniziale per un più rapido caricamento della pagina, e permettere ai motori di ricerca di effettuare il crawling della tua pagina per ottimizzazione SEO.
115 -
116 -Se chiami `ReactDOM.render()` su un nodo che possiede già questo markup generato lato server, React lo preserverà e vi attaccherà soltanto i gestori di eventi, permettendoti di avere una esperienza di primo caricamento altamente efficiente.
117 -
118 -
119 -### ReactDOM.renderToStaticMarkup
120 -
121 -```javascript
122 -string renderToStaticMarkup(ReactElement element)
123 -```
124 -
125 -Simile a `renderToString`, eccetto che non crea attributi DOM aggiuntivi come `data-react-id`, che React utilizza internamente. Questo è utile se vuoi usare React come un semplice generatore di pagine statiche, in quanto eliminare gli attributi aggiuntivi può risparmiare parecchi byte.
126 -
127 -
128 -### ReactDOM.isValidElement
129 -
130 -```javascript
131 -boolean isValidElement(* object)
132 -```
133 -
134 -Verifica che `object` sia un ReactElement.
135 -
136 -
137 -### ReactDOM.findDOMNode
138 -
139 -```javascript
140 -DOMElement findDOMNode(ReactComponent component)
141 -```
142 -Se questo componente è stato montato nel DOM, restituisce il corrispondente elemento DOM nativo del browser. Questo metodo è utile per leggere i valori dal DOM, come i valori dei campi dei moduli ed effettuare misure sul DOM. Quando `render` restituisce `null` o `false`, `findDOMNode` restituisce `null`.
143 -
144 -> Nota:
145 ->
146 -> `findDOMNode()` è una via di fuga usata per accedere al nodo DOM sottostante. Nella maggior parte dei casi, l'uso di questa via di fuga è scoraggiato perché viola l'astrazione del componente. Tuttavia, esistono delle situazioni in cui questo è necessario (ad esempio, potresti aver bisogno di trovare un nodo DOM per posizionarlo in maniera assoluta oppure determinarne la larghezza visualizzata misurata in pixel).
147 -
148 ->
149 -> `findDOMNode()` funziona soltanto su componenti montati (cioè, componenti che sono stati posizionati nel DOM). Se provi a chiamarlo su un componente che non è stato ancora montato (come chiamare `findDOMNode()` in `render()` su un componente che deve ancora essere creato) lancerà un'eccezione.
150 -
151 -### React.DOM
152 -
153 -`React.DOM` fornisce convenienti utilità che espongono `React.createElement` per componenti del DOM. Questi dovrebbero essere usate soltanto quando non si utilizza JSX. Ad esempio, `React.DOM.div(null, 'Ciao Mondo!')`
154 -
155 -
156 -### React.PropTypes
157 -
158 -`React.PropTypes` include tipi che possono essere usati con l'oggetto `propTypes` di un componente per validare le proprietà passate ai tuoi componenti. Per maggiori informazioni su `propTypes`, vedi [Componenti Riutilizzabili](/react/docs/reusable-components.html).
159 -
160 -
161 -### React.Children
162 -
163 -`React.Children` fornisce utilitià per gestire la struttura dati opaca `this.props.children`.
164 -
165 -#### React.Children.map
166 -
167 -```javascript
168 -object React.Children.map(object children, function fn [, object thisArg])
169 -```
170 -
171 -Invoca `fn` su ciascuno dei diretti discendenti contenuti in `children`, con `this` impostato a `thisArg`. Se `children` è un oggetto annidato o un array, esso verrà attraversato: ad `fn` non saranno mai passati gli oggetti contenitori. Se `children` è `null` o `undefined` restituisce `null` o `undefined` anziché un oggetto vuoto.
172 -
173 -#### React.Children.forEach
174 -
175 -```javascript
176 -React.Children.forEach(object children, function fn [, object thisArg])
177 -```
178 -
179 -Come `React.Children.map()` con la differenza che non restituisce un oggetto.
180 -
181 -#### React.Children.count
182 -
183 -```javascript
184 -number React.Children.count(object children)
185 -```
186 -
187 -Restituisce il numero totale di componenti in `children`, uguale al numero di volte che una callback passata a `map` o `forEach` verrebbe invocata.
188 -
189 -#### React.Children.only
190 -
191 -```javascript
192 -object React.Children.only(object children)
193 -```
194 -
195 -Restituisce il figlio unico contenuto in `children`, altrimenti lancia un'eccezione.
docs/docs/ref-01-top-level-api.ja-JP.md deleted
-172
@@ -1,172 +0,0 @@
1 ----
2 -id: top-level-api-ja-JP
3 -title: Top-Level API
4 -permalink: docs/top-level-api-ja-JP.html
5 -next: component-api-ja-JP.html
6 -redirect_from: "/docs/reference-ja-JP.html"
7 ----
8 -
9 -## React
10 -
11 -`React` はReactのライブラリに対するエントリーポイントです。事前にビルドされたパッケージを使用する場合は、グローバルで使用可能です。CommonJSのモジュールを使用する場合は、 `require()` できます。
12 -
13 -
14 -### React.Component
15 -
16 -```javascript
17 -class Component
18 -```
19 -
20 -これは、ES6のクラスを使用して定義されている場合の、Reactコンポーネントに対する基底クラスです。ReactでES6のクラスを使用する方法については、[再利用可能なコンポーネント](/react/docs/reusable-components-ja-JP.html#es6-classes)をご覧ください。基底クラスからどのメソッドが実際に提供されるかについては、[コンポーネントAPI](/react/docs/component-api-ja-JP.html)をご覧ください。
21 -
22 -### React.createClass
23 -
24 -```javascript
25 -ReactClass createClass(object specification)
26 -```
27 -
28 -与えられた仕様に基づいてコンポーネントクラスを作成します。コンポーネントは **ある単一の** 子要素を返す `render` メソッドを実行します。その子要素は勝手に深い子要素の構造を保持しています。コンポーネントが標準的なプロトタイプのクラスと異なっている部分は、newを呼ぶ必要がないということです。それらは内部で(newを行う)インスタンスを構築する便利なラッパーです。
29 -
30 -specificationオブジェクトについての情報は、[コンポーネントのスペックとライフサイクル](/react/docs/component-specs-ja-JP.html)をご覧ください。
31 -
32 -### React.createElement
33 -
34 -```javascript
35 -ReactElement createElement(
36 - string/ReactClass type,
37 - [object props],
38 - [children ...]
39 -)
40 -```
41 -
42 -与えられた型の `ReactElement` を作成し、返します。type引数はhtmlタグ名(例えば、'div'、'span'など)の文字列にも`ReactClass`(`React.createClass` によって作成される)にもなり得ます。
43 -
44 -### React.cloneElement
45 -
46 -```
47 -ReactElement cloneElement(
48 - ReactElement element,
49 - [object props],
50 - [children ...]
51 -)
52 -```
53 -
54 -`element` をスターティングポイントとして使用する新しい `ReactElement` をクローンして返します。
55 -結果として生まれる要素はオリジナルの要素のpropsと新しいpropsを暗にマージしたものを保持しています。新しい子要素は現存する子要素を置き換えます。 `React.addons.cloneWithProps` と異なり、オリジナルの要素から得られた `key` と `ref` は保存されます。(`cloneWithProps` とは異なり)propsをマージする際に特別な動きは行いません。詳細については、[v0.13 RC2 blog記事](/react/blog/2015/03/03/react-v0.13-rc2.html)をご覧ください。
56 -
57 -### React.createFactory
58 -
59 -```javascript
60 -factoryFunction createFactory(
61 - string/ReactClass type
62 -)
63 -```
64 -
65 -与えられた型のReactElementsを生成する関数を返します。 `React.createElement` と同様に、type引数はhtmlタグ名(例えば、'div'、'span'など)の文字列にも`ReactClass` にもなり得ます。
66 -
67 -### React.render
68 -
69 -```javascript
70 -ReactComponent render(
71 - ReactElement element,
72 - DOMElement container,
73 - [function callback]
74 -)
75 -```
76 -
77 -与えられた `container` によってReactElementをDOMにレンダリングし、コンポーネントへの参照を返します。
78 -
79 -もしReactElementが事前に `container` にレンダリングされていた場合は、更新を行い、DOMが最新のReactのコンポーネントを表すように変化させます。
80 -
81 -オプションのコールバックが与えられた場合は、コンポーネントがレンダリングされたり、更新された後に実行されます。
82 -
83 -> 注意:
84 -> `React.render()` は渡されたコンテナーノードの内容を制御します。内部に存在するDOM要素は最初に呼ばれた際に置き換えられます。その後に呼ばれた場合は、ReactのDOMの差分アルゴリズムを使用して、効率的に更新されます。
85 ->
86 -> `React.render()` はコンテナーノードの変更は行いません(コンテナの子要素のみ変更を行います)。今後、存在する子要素を上書きすることなく、存在するDOMノードにコンポーネントを挿入することが可能になるでしょう。
87 -
88 -### React.unmountComponentAtNode
89 -
90 -```javascript
91 -boolean unmountComponentAtNode(DOMElement container)
92 -```
93 -
94 -マウントされたReactのコンポーネントをDOMから削除し、そのイベントハンドラとstateをクリーンアップします。コンテナにコンポーネントがマウントされていない場合は、この関数を呼んでも何も行われません。コンポーネントがアンマウントされた場合は `true` を返し、アンマウントするコンポーネントが存在しない場合は `false` を返します。
95 -
96 -### React.renderToString
97 -
98 -```javascript
99 -string renderToString(ReactElement element)
100 -```
101 -
102 -ReactElementを最初にHTMLにレンダリングします。これはサーバでのみ使用されるべきです。ReactはHTML文字列を返します。このメソッドを、サーバでHTMLを生成し、最初のリクエストに対してマークアップを送るのに使用することができます。そうすることで、ページロードが速くなり、サーチエンジンはSEOの目的でページをクロールします。
103 -
104 -既にサーバでレンダリングされたマークアップを保持しているノードで `React.render()` を呼んだ場合は、Reactはそれを保護し、イベントハンドラを加えます。そうすることで、最初のローディングのパフォーマンスがとても良くなります。
105 -
106 -### React.renderToStaticMarkup
107 -
108 -```javascript
109 -string renderToStaticMarkup(ReactElement element)
110 -```
111 -
112 -`renderToString` に似ていますが、Reactが内部で使用する `data-react-id` のような外部のDOM属性を作成しません。Reactを、単純な静的なページを生成するために使用したい場合は有用です。外部の属性を取り除くことでメモリを節約することができます。
113 -
114 -### React.isValidElement
115 -
116 -```javascript
117 -boolean isValidElement(* object)
118 -```
119 -
120 -オブジェクトがReactElementであるかどうか調査します。
121 -
122 -### React.findDOMNode
123 -
124 -```javascript
125 -DOMElement findDOMNode(ReactComponent component)
126 -```
127 -
128 -このコンポーネントがDOMにマウントされた場合は、対応するネイティブブラウザのDOM要素を返します。このメソッドはDOMの外の値を読み込む場合に有用です。例えば、formフィールドの値やDOMの測定を行う場合があります。 `render` が `null` や `false` を返した場合は、 `findDOMNode` は `null` を返します。
129 -
130 -### React.DOM
131 -
132 -`React.DOM` はDOMコンポーネントのための `React.createElement` の周りの便利なラッパーを提供します。JSXを使用しない場合にのみ使用すべきです。例えば、 `React.DOM.div(null, 'Hello World!')` のように。
133 -
134 -### React.PropTypes
135 -
136 -`React.PropTypes` はコンポーネントに与えられたpropsをバリデーションするためにコンポーネントの `propTypes` と使用できる型を含んでいます。 `propTypes` についての更なる情報は、[再利用可能なコンポーネント](/react/docs/reusable-components-ja-JP.html)をご覧ください。
137 -
138 -### React.Children
139 -
140 -`React.Children` は `this.props.children` の不透明なデータ構造を扱うユーティリティを提供します。
141 -
142 -#### React.Children.map
143 -
144 -```javascript
145 -object React.Children.map(object children, function fn [, object thisArg])
146 -```
147 -
148 -全ての `children` を含む子要素に対して、 `fn` を実行します。 `this` は `thisArg` にセットされます。 `children` がネストしたオブジェクトや配列だった場合は、実行されません。 `fn` はコンテナのオブジェクトから渡されません。子要素が `null` か `undefined` だった場合は、空のオブジェクトではなく `null` か `undefined` を返します。
149 -
150 -#### React.Children.forEach
151 -
152 -```javascript
153 -React.Children.forEach(object children, function fn [, object thisArg])
154 -```
155 -
156 -`React.Children.map()` に似ていますが、オブジェクトを返しはしません。
157 -
158 -#### React.Children.count
159 -
160 -```javascript
161 -number React.Children.count(object children)
162 -```
163 -
164 -`children` の中のコンポーネントの合計数を返します。 `map` や `forEach` に渡されるコールバックが実行される数と等しくなります。
165 -
166 -#### React.Children.only
167 -
168 -```javascript
169 -object React.Children.only(object children)
170 -```
171 -
172 -`children` の単一の子要素を返します。それ以外の場合は例外をスローします。
docs/docs/ref-01-top-level-api.ko-KR.md deleted
-206
@@ -1,206 +0,0 @@
1 ----
2 -id: top-level-api-ko-KR
3 -title: 최상위 API
4 -permalink: docs/top-level-api-ko-KR.html
5 -next: component-api-ko-KR.html
6 -redirect_from: "/docs/reference-ko-KR.html"
7 ----
8 -
9 -## React
10 -
11 -`React`는 React 라이브러리의 진입점입니다. 미리 빌드된 패키지를 사용하는 경우 전역 변수로 접근할 수 있습니다. CommonJS 모듈을 사용하는 경우에는 `require()`로 불러올 수 있습니다.
12 -
13 -
14 -### React.Component
15 -
16 -```javascript
17 -class Component
18 -```
19 -
20 -ES6 클래스 구문을 사용해 React 컴포넌트를 정의했을 때 기본 클래스가 되는 부분입니다. 어떻게 ES6 클래스 구문을 사용해 React를 다루는지는 [재사용가능한 컴포넌트](/react/docs/reusable-components-ko-KR.html#es6-클래스)를 확인하세요. 기본 클래스에서 실제 제공되는 메소드들에는 어떤것이 있는지 알아보려면 [컴포넌트 API](/react/docs/component-api-ko-KR.html)를 확인하세요.
21 -
22 -
23 -### React.createClass
24 -
25 -```javascript
26 -ReactClass createClass(object specification)
27 -```
28 -
29 -주어진 명세에 따라 컴포넌트 클래스를 만듭니다. 컴포넌트는 단 하나의 자식만을 리턴하는 `render` 메소드를 구현합니다. 그 자식은 임의 깊이의 자식 구조를 가질 수 있습니다. 컴포넌트가 일반적인 프로토타입 기반의 클래스와 다른 점은 생성할 때 `new` 연산자를 사용하지 않아도 된다는 것입니다. 컴포넌트는 (`new` 연산자를 통해) 내부 인스턴스를 만들어 주는 편의 래퍼(wrapper)입니다.
30 -
31 -명세 객체에 대한 자세한 정보는 [컴포넌트 명세와 생명주기](/react/docs/component-specs-ko-KR.html)를 참고하세요.
32 -
33 -
34 -### React.createElement
35 -
36 -```javascript
37 -ReactElement createElement(
38 - string/ReactClass type,
39 - [object props],
40 - [children ...]
41 -)
42 -```
43 -
44 -주어진 타입의 새 `ReactElement`를 만들고 리턴합니다. `type` 인자는 HTML 태그명 문자열 (예: 'div', 'span' 등) 또는 (`React.createClass`로 만든) `ReactClass`입니다.
45 -
46 -
47 -### React.cloneElement
48 -
49 -```
50 -ReactElement cloneElement(
51 - ReactElement element,
52 - [object props],
53 - [children ...]
54 -)
55 -```
56 -
57 -`element`를 시작점으로 새로운 `ReactElement`를 클론해 반환합니다. 반환된 엘리먼트에는 원본의 props와 새로운 props가 얕게 병합됩니다. 새 자식은 존재하는 자식을 교체할 것입니다. `React.addons.cloneWithProps`와는 다르게, 원본 엘리먼트의 `key`와 `ref`는 보존될 것입니다. `cloneWithProps`와는 달리 props이 병합되는데는 어떠한 특별한 동작도 없습니다. [v0.13 RC2 블로그 포스트](/react/blog/2015/03/03/react-v0.13-rc2.html)에서 추가적인 내용을 확인하세요.
58 -
59 -
60 -### React.createFactory
61 -
62 -```javascript
63 -factoryFunction createFactory(
64 - string/ReactClass type
65 -)
66 -```
67 -
68 -주어진 타입의 ReactElement를 만들어주는 함수를 리턴합니다. `React.createElement`와 마찬가지로 `type` 인자는 HTML 태그명 문자열 (예: 'div', 'span' 등) 또는 `ReactClass`입니다.
69 -
70 -
71 -### React.isValidElement
72 -
73 -```javascript
74 -boolean isValidElement(* object)
75 -```
76 -
77 -주어진 객체가 ReactElement인지 확인합니다.
78 -
79 -
80 -### React.DOM
81 -
82 -`React.DOM`은 DOM 컴포넌트에 대해 `React.createElement`의 편의 래퍼(wrapper)를 제공합니다. JSX를 사용하지 않는 경우에만 사용하십시오. 예를 들어, `React.DOM.div(null, 'Hello World!')`와 같이 사용할 수 있습니다.
83 -
84 -
85 -### React.PropTypes
86 -
87 -`React.PropTypes`는 컴포넌트에 넘어오는 props가 올바른지 검사할 수 있는 컴포넌트의 `propTypes` 객체에 들어가는 타입을 가집니다. `propTypes`에 대한 자세한 정보는 [재사용 가능한 컴포넌트](/react/docs/reusable-components-ko-KR.html)를 참고하세요.
88 -
89 -
90 -### React.Children
91 -
92 -`React.Children`은 불투명한 자료 구조인 `this.props.children`를 다룰 수 있는 유틸리티를 제공합니다.
93 -
94 -#### React.Children.map
95 -
96 -```javascript
97 -array React.Children.map(object children, function fn [, object thisArg])
98 -```
99 -
100 -`children`의 바로 밑에 있는 모든 자식에 `fn`을 호출합니다. 이 때 `this`는 `thisArg`로 설정됩니다. `children`이 중첩된 객체나 배열일 경우 그 안의 값을 순회합니다. 따라서 `fn`에 컨테이너 객체가 넘어가는 일은 일어나지 않습니다. `children`이 `null`이거나 `undefined`면 배열 대신 `null` 또는 `undefined`를 리턴합니다.
101 -
102 -#### React.Children.forEach
103 -
104 -```javascript
105 -React.Children.forEach(object children, function fn [, object thisArg])
106 -```
107 -
108 -`React.Children.map()`과 비슷하지만 배열을 리턴하지 않습니다.
109 -
110 -#### React.Children.count
111 -
112 -```javascript
113 -number React.Children.count(object children)
114 -```
115 -
116 -`children`에 들어있는 컴포넌트의 총 갯수를 리턴합니다. 이 갯수는 `map`이나 `forEach`에 넘긴 콜백이 호출되는 횟수와 동일합니다.
117 -
118 -#### React.Children.only
119 -
120 -```javascript
121 -object React.Children.only(object children)
122 -```
123 -
124 -`children`에 단 하나의 자식이 있을 때 그 자식을 리턴합니다. 그 밖의 경우에는 예외를 발생시킵니다.
125 -
126 -#### React.Children.toArray
127 -
128 -```javascript
129 -array React.Children.toArray(object children)
130 -```
131 -
132 -불투명한 자료구조인 `children`를 개별 자식마다 키를 할당해 평면 배열로 리턴합니다. 이는 render 메소드 내에서 자식의 컬렉션을 조작할 때, 특히 `this.props.children`을 넘기기 전에 재정렬하거나 재단할 때 유용합니다.
133 -
134 -## ReactDOM
135 -
136 -`react-dom` 패키지는 앱의 최상위 레벨에서 사용될 DOM 고유의 메소드를 제공하며, 원한다면 리액트 외부모델을 위한 출구로 사용될 수 있습니다. 대부분의 컴포넌트는 이 모듈을 사용할 필요가 없습니다.
137 -
138 -### ReactDOM.render
139 -
140 -```javascript
141 -ReactComponent render(
142 - ReactElement element,
143 - DOMElement container,
144 - [function callback]
145 -)
146 -```
147 -
148 -주어진 ReactElement를 `container` 인자에 넘어온 DOM 안에 렌더링하고 컴포넌트의 [레퍼런스](/react/docs/more-about-refs-ko-KR.html)를 컴포넌트에 리턴합니다. [상태가 없는 컴포넌트](/react/docs/reusable-components-ko-KR.html#상태를-가지지-않는-함수)에서는 `null`을 리턴합니다.
149 -
150 -어떤 ReactElement가 이미 `container`에 렌더링 된 적이 있다면, 그것을 업데이트한 뒤 React 컴포넌트의 최신 상태를 반영하기 위해 꼭 필요한 만큼만 DOM을 변경합니다.
151 -
152 -콜백 인자를 넘기면 컴포넌트가 렌더링되거나 업데이트 된 다음 호출됩니다.
153 -
154 -> 주의:
155 ->
156 -> `ReactDOM.render()`는 넘어온 컨테이너 노드의 내용을 교체합니다. 안에 있는 DOM 엘리먼트는 첫 호출을 할 때 교체됩니다. 그 후의 호출에는 효율석으로 업데이트하기 위해 React의 DOM diff 알고리즘을 사용합니다.
157 ->
158 -> `ReactDOM.render()`는 컨테이너 노드를 수정하지 않습니다. (컨테이너의 자식만 수정함) 추후에 기존 자식들을 덮어쓰지 않고 이미 있는 DOM 노드에 컴포넌트를 삽입하는 것도 지원할 가능성이 있습니다.
159 -
160 -
161 -### ReactDOM.unmountComponentAtNode
162 -
163 -```javascript
164 -boolean unmountComponentAtNode(DOMElement container)
165 -```
166 -
167 -DOM에 마운트된 React 컴포넌트를 제거하고 이벤트 핸들러 및 state를 정리합니다. 컨테이너에 마운트된 컴포넌트가 없는 경우에는 호출해도 아무 동작을 하지 않습니다. 컴포넌트가 마운트 해제된 경우 `true`를, 마운트 해제할 컴포넌트가 없으면 `false`를 리턴합니다.
168 -
169 -
170 -### ReactDOM.findDOMNode
171 -
172 -```javascript
173 -DOMElement findDOMNode(ReactComponent component)
174 -```
175 -이 컴포넌트가 DOM에 마운트된 경우 해당하는 네이티브 브라우저 DOM 엘리먼트를 리턴합니다. 이 메소드는 폼 필드의 값이나 DOM의 크기/위치 등 DOM에서 정보를 읽을 때 유용합니다. **대부분의 경우, DOM 노드에 ref를 쓸 수 있으며 `findDOMNode`를 사욯할 필요는 없습니다.** `render`가 `null`이나 `false`를 리턴할 때 `findDOMNode()`는 `null`을 리턴합니다.
176 -
177 -> 주의:
178 ->
179 -> `findDOMNode()`는 기본 DOM 노드에 접근하기 위한 출구입니다. 컴포넌트 추상화를 파괴하기 때문에 대부분의 경우 이것의 사용은 권장되지 않습니다.
180 ->
181 -> `findDOMNode()`는 마운트된 컴포넌트에서만 작동합니다. 이는 컴포넌트가 DOM에 위치해야 함을 뜻합니다. 만약 아직 생성되기전의 컴포넌트에서 `render()`에서 `findDOMNode()`를 호출하는 등 컴포넌트가 마운트 되기 이전에 이를 호출한다면, 예외가 던져질 것입니다.
182 ->
183 -> `findDOMNode()`는 상태가없는 컴포넌트에서 쓸 수 없습니다.
184 -
185 -## ReactDOMServer
186 -
187 -`react-dom/server` 패키지는 서버단에서 컴포넌트를 렌더할 수 있도록 해 줍니다.
188 -
189 -### ReactDOMServer.renderToString
190 -
191 -```javascript
192 -string renderToString(ReactElement element)
193 -```
194 -
195 -주어진 ReactElement의 최초 HTML을 렌더링합니다. 이 함수는 서버에서만 사용해야 합니다. React가 HTML 문자열을 리턴합니다. HTML을 서버에서 생성하고 마크업을 최초 요청에 내려보내서, 페이지 로딩을 빠르게 하거나 검색 엔진이 크롤링할 수 있도록 하는 SEO 목적으로 이 메소드를 사용할 수 있습니다.
196 -
197 -또한 이 메소드로 서버에서 렌더링한 마크업을 포함한 노드에 `ReactDOM.render()`를 호출하면, React는 마크업을 보존하고 이벤트 핸들러만 붙이므로 최초 로딩을 매우 빠르게 느껴지게 할 수 있습니다.
198 -
199 -
200 -### ReactDOMServer.renderToStaticMarkup
201 -
202 -```javascript
203 -string renderToStaticMarkup(ReactElement element)
204 -```
205 -
206 -`renderToString`와 비슷하지만 `data-react-id`처럼 React에서 내부적으로 사용하는 추가적인 DOM 어트리뷰트를 만들지 않습니다. 추가적인 어트리뷰트를 제거하면 생성되는 마크업의 용량을 줄일 수 있기 때문에 React를 단순한 정적 페이지 생성기로 사용할 때 유용합니다.
docs/docs/ref-01-top-level-api.md deleted
-219
@@ -1,219 +0,0 @@
1 ----
2 -id: top-level-api
3 -title: Top-Level API
4 -permalink: docs/top-level-api.html
5 -next: component-api.html
6 -redirect_from: "/docs/reference.html"
7 ----
8 -
9 -## React
10 -
11 -`React` is the entry point to the React library. If you're using one of the prebuilt packages it's available as a global; if you're using CommonJS modules you can `require()` it.
12 -
13 -
14 -### React.Component
15 -
16 -```javascript
17 -class Component
18 -```
19 -
20 -This is the base class for React Components when they're defined using ES6 classes. See [Reusable Components](/react/docs/reusable-components.html#es6-classes) for how to use ES6 classes with React. For what methods are actually provided by the base class, see the [Component API](/react/docs/component-api.html).
21 -
22 -
23 -### React.createClass
24 -
25 -```javascript
26 -ReactClass createClass(object specification)
27 -```
28 -
29 -Create a component class, given a specification. A component implements a `render` method which returns **one single** child. That child may have an arbitrarily deep child structure. One thing that makes components different than standard prototypal classes is that you don't need to call new on them. They are convenience wrappers that construct backing instances (via new) for you.
30 -
31 -For more information about the specification object, see [Component Specs and Lifecycle](/react/docs/component-specs.html).
32 -
33 -
34 -### React.createElement
35 -
36 -```javascript
37 -ReactElement createElement(
38 - string/ReactClass type,
39 - [object props],
40 - [children ...]
41 -)
42 -```
43 -
44 -Create and return a new `ReactElement` of the given type. The type argument can be either an
45 -html tag name string (eg. 'div', 'span', etc), or a `ReactClass` (created via `React.createClass`).
46 -
47 -
48 -### React.cloneElement
49 -
50 -```
51 -ReactElement cloneElement(
52 - ReactElement element,
53 - [object props],
54 - [children ...]
55 -)
56 -```
57 -
58 -Clone and return a new `ReactElement` using `element` as the starting point. The resulting element will have the original element's props with the new props merged in shallowly. New children will replace existing children. Unlike `React.addons.cloneWithProps`, `key` and `ref` from the original element will be preserved. There is no special behavior for merging any props (unlike `cloneWithProps`). See the [v0.13 RC2 blog post](/react/blog/2015/03/03/react-v0.13-rc2.html) for additional details.
59 -
60 -
61 -### React.createFactory
62 -
63 -```javascript
64 -factoryFunction createFactory(
65 - string/ReactClass type
66 -)
67 -```
68 -
69 -Return a function that produces ReactElements of a given type. Like `React.createElement`, the type argument can be either an html tag name string (eg. 'div', 'span', etc), or a `ReactClass`.
70 -
71 -
72 -### React.isValidElement
73 -
74 -```javascript
75 -boolean isValidElement(* object)
76 -```
77 -
78 -Verifies the object is a ReactElement.
79 -
80 -
81 -### React.DOM
82 -
83 -`React.DOM` provides convenience wrappers around `React.createElement` for DOM components. These should only be used when not using JSX. For example, `React.DOM.div(null, 'Hello World!')`
84 -
85 -
86 -### React.PropTypes
87 -
88 -`React.PropTypes` includes types that can be used with a component's `propTypes` object to validate props being passed to your components. For more information about `propTypes`, see [Reusable Components](/react/docs/reusable-components.html).
89 -
90 -
91 -### React.Children
92 -
93 -`React.Children` provides utilities for dealing with the `this.props.children` opaque data structure.
94 -
95 -#### React.Children.map
96 -
97 -```javascript
98 -array React.Children.map(object children, function fn [, object thisArg])
99 -```
100 -
101 -Invoke `fn` on every immediate child contained within `children` with `this` set to `thisArg`. If `children` is a [keyed fragment](/react/docs/create-fragment.html) or array it will be traversed: `fn` will never be passed the container objects. If children is `null` or `undefined` returns `null` or `undefined` rather than an array.
102 -
103 -#### React.Children.forEach
104 -
105 -```javascript
106 -React.Children.forEach(object children, function fn [, object thisArg])
107 -```
108 -
109 -Like `React.Children.map()` but does not return an array.
110 -
111 -#### React.Children.count
112 -
113 -```javascript
114 -number React.Children.count(object children)
115 -```
116 -
117 -Return the total number of components in `children`, equal to the number of times that a callback passed to `map` or `forEach` would be invoked.
118 -
119 -#### React.Children.only
120 -
121 -```javascript
122 -object React.Children.only(object children)
123 -```
124 -
125 -Return the only child in `children`. Throws otherwise.
126 -
127 -#### React.Children.toArray
128 -
129 -```javascript
130 -array React.Children.toArray(object children)
131 -```
132 -
133 -Return the `children` opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice `this.props.children` before passing it down.
134 -
135 -> Note:
136 ->
137 -> `React.Children.toArray()` changes keys to preserve the semantics of nested arrays when flattening lists of children. That is, `toArray` prefixes each key in the returned array so that each element's key is scoped to the input array containing it.
138 -
139 -## ReactDOM
140 -
141 -The `react-dom` package provides DOM-specific methods that can be used at the top level of your app and as an escape hatch to get outside of the React model if you need to. Most of your components should not need to use this module.
142 -
143 -### ReactDOM.render
144 -
145 -```javascript
146 -render(
147 - ReactElement element,
148 - DOMElement container,
149 - [function callback]
150 -)
151 -```
152 -
153 -Render a ReactElement into the DOM in the supplied `container` and return a [reference](/react/docs/more-about-refs.html) to the component (or returns `null` for [stateless components](/react/docs/reusable-components.html#stateless-functions)).
154 -
155 -If the ReactElement was previously rendered into `container`, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React component.
156 -
157 -If the optional callback is provided, it will be executed after the component is rendered or updated.
158 -
159 -> Note:
160 ->
161 -> `ReactDOM.render()` controls the contents of the container node you pass in. Any existing DOM elements
162 -> inside are replaced when first called. Later calls use React’s DOM diffing algorithm for efficient
163 -> updates.
164 ->
165 -> `ReactDOM.render()` does not modify the container node (only modifies the children of the container). In
166 -> the future, it may be possible to insert a component to an existing DOM node without overwriting
167 -> the existing children.
168 ->
169 -> `ReactDOM.render()` currently returns a reference to the root `ReactComponent` instance. However, using this return value is legacy
170 -> and should be avoided because future versions of React may render components asynchronously in some cases. If you need a reference to the root `ReactComponent` instance, the preferred solution is to attach a
171 -> [callback ref](/react/docs/more-about-refs.html#the-ref-callback-attribute) to the root element.
172 -
173 -
174 -### ReactDOM.unmountComponentAtNode
175 -
176 -```javascript
177 -boolean unmountComponentAtNode(DOMElement container)
178 -```
179 -
180 -Remove a mounted React component from the DOM and clean up its event handlers and state. If no component was mounted in the container, calling this function does nothing. Returns `true` if a component was unmounted and `false` if there was no component to unmount.
181 -
182 -
183 -### ReactDOM.findDOMNode
184 -
185 -```javascript
186 -DOMElement findDOMNode(ReactComponent component)
187 -```
188 -If this component has been mounted into the DOM, this returns the corresponding native browser DOM element. This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements. **In most cases, you can attach a ref to the DOM node and avoid using `findDOMNode` at all.** When `render` returns `null` or `false`, `findDOMNode` returns `null`.
189 -
190 -> Note:
191 ->
192 -> `findDOMNode()` is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction.
193 ->
194 -> `findDOMNode()` only works on mounted components (that is, components that have been placed in the DOM). If you try to call this on a component that has not been mounted yet (like calling `findDOMNode()` in `render()` on a component that has yet to be created) an exception will be thrown.
195 ->
196 -> `findDOMNode()` cannot be used on stateless components.
197 -
198 -## ReactDOMServer
199 -
200 -The `react-dom/server` package allows you to render your components on the server.
201 -
202 -### ReactDOMServer.renderToString
203 -
204 -```javascript
205 -string renderToString(ReactElement element)
206 -```
207 -
208 -Render a ReactElement to its initial HTML. This should only be used on the server. React will return an HTML string. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
209 -
210 -If you call `ReactDOM.render()` on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
211 -
212 -
213 -### ReactDOMServer.renderToStaticMarkup
214 -
215 -```javascript
216 -string renderToStaticMarkup(ReactElement element)
217 -```
218 -
219 -Similar to `renderToString`, except this doesn't create extra DOM attributes such as `data-reactid`, that React uses internally. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save lots of bytes.
docs/docs/ref-01-top-level-api.zh-CN.md deleted
-211
@@ -1,211 +0,0 @@
1 ----
2 -id: top-level-api-zh-CN
3 -title: Top-Level API
4 -permalink: docs/top-level-api-zh-CN.html
5 -next: component-api-zh-CN.html
6 -redirect_from: "/docs/reference-zh-CN.html"
7 ----
8 -
9 -## React
10 -
11 -`React` 是 React 库的入口点。如果你使用预编译包中的一个,则 `React` 为全局变量;如果你使用 CommonJS 模块,你可以 `require()` 它。
12 -
13 -
14 -### React.Component
15 -
16 -```javascript
17 -class Component
18 -```
19 -
20 -当使用ES6 类定义时,React.Component是 React 组件的基类。如何在React中使用 ES6 class 请参见 [可重用组件](/react/docs/reusable-components-zh-CN.html#es6-classes)。基类实际提供了哪些方法 请参见 [组件 API](/react/docs/component-api-zh-CN.html).
21 -
22 -
23 -### React.createClass
24 -
25 -```javascript
26 -ReactClass createClass(object specification)
27 -```
28 -
29 -给定一份规格(specification),创建一个组件类。组件通常要实现一个 `render()` 方法,它返回 **单个的** 子级。该子级可能包含任意深度的子级结构。组件与标准原型类的不同之处在于,你不需要对它们调用 new。 它们是为你在后台构造实例(通过 new)的便利的包装器。
30 -
31 -更多关于规格对象(specification object)的信息,请见 [组件规格和生命周期](/react/docs/component-specs-zh-CN.html) 。
32 -
33 -
34 -### React.createElement
35 -
36 -```javascript
37 -ReactElement createElement(
38 - string/ReactClass type,
39 - [object props],
40 - [children ...]
41 -)
42 -```
43 -
44 -创建并返回一个新的给定类型的 `ReactElement`。type 参数既可以是一个 html 标签名字符串(例如. “div”,“span”,等等),也可以是一个 `ReactClass` (用 `React.createClass` 创建的)。
45 -
46 -
47 -
48 -### React.cloneElement
49 -
50 -```
51 -ReactElement cloneElement(
52 - ReactElement element,
53 - [object props],
54 - [children ...]
55 -)
56 -```
57 -
58 -使用 `element` 作为起点,克隆并返回一个新的 `ReactElement` 。生成的 element 将会拥有原始 element 的 props 与新的 props 的浅合并。新的子级将会替换现存的子级。 不同于 `React.addons.cloneWithProps`,来自原始 element 的 `key` 和 `ref` 将会保留。对于合并任何 props 没有特别的行为(不同于 `cloneWithProps`)。更多细节详见[v0.13 RC2 blog post](/react/blog/2015/03/03/react-v0.13-rc2.html) 。
59 -
60 -
61 -### React.createFactory
62 -
63 -```javascript
64 -factoryFunction createFactory(
65 - string/ReactClass type
66 -)
67 -```
68 -
69 -返回一个生成给定类型的 ReactElements 的函数。如同 `React.createElement`,type 参数既可以是一个 html 标签名字符串(例如. “div”,“span”,等等),也可以是一个 `ReactClass` 。
70 -
71 -
72 -### React.isValidElement
73 -
74 -```javascript
75 -boolean isValidElement(* object)
76 -```
77 -
78 -验证对象是否是一个 ReactElement。
79 -
80 -
81 -### React.DOM
82 -
83 -`React.DOM` 用 `React.createElement` 为 DOM 组件提供了便利的包装器。该方式应该只在不使用 JSX 的时使用。例如,`React.DOM.div(null, 'Hello World!')`。
84 -
85 -
86 -### React.PropTypes
87 -
88 -`React.PropTypes` 包含了能与 组件的`propTypes` 对象一起使用的类型,用以验证传入你的组件的 props。更多有关 `propTypes` 的信息,请见 [可重用组件](/react/docs/reusable-components-zh-CN.html)。
89 -
90 -
91 -### React.Children
92 -
93 -`React.Children` 为处理 `this.props.children` 这个不透明的数据结构提供了工具。
94 -
95 -#### React.Children.map
96 -
97 -```javascript
98 -array React.Children.map(object children, function fn [, object thisArg])
99 -```
100 -
101 -在每一个包含在 `children` 中的直接子级上调用 `fn` ,`fn`中的 `this` 设置为 `thisArg`。如果 `children` 是一个嵌套的对象或者数组,它将被遍历:不会传入容器对象到 `fn` 中。如果 children 是 `null` 或者 `undefined`,则返回 `null` 或者 `undefined` 而不是一个空数组。
102 -
103 -#### React.Children.forEach
104 -
105 -```javascript
106 -React.Children.forEach(object children, function fn [, object thisArg])
107 -```
108 -
109 -类似 `React.Children.map()`,但是不返回数组。
110 -
111 -#### React.Children.count
112 -
113 -```javascript
114 -number React.Children.count(object children)
115 -```
116 -
117 -返回 `children` 中的组件总数,相等于传递给 `map` 或者 `forEach` 的回调函数应被调用次数。
118 -
119 -#### React.Children.only
120 -
121 -```javascript
122 -object React.Children.only(object children)
123 -```
124 -
125 -返回 `children` 中仅有的子级。否则抛出异常。
126 -
127 -#### React.Children.toArray
128 -
129 -```javascript
130 -array React.Children.toArray(object children)
131 -```
132 -
133 -以赋key给每个child的平坦的数组形式,返回不透明的 `children` 数据结构.如果你想操纵你的渲染方法的子级的合集这很有用,尤其如果你想在 `this.props.children` 传下之前渲染或者切割.
134 -
135 -## ReactDOM
136 -
137 -`react-dom` 包提供了 具体的DOM方法,这些方法可以在你的app的顶层作为一个你需要时脱离React模式的安全舱口 被使用.你的大多数组件不需要使用这个模块.
138 -
139 -### ReactDOM.render
140 -
141 -```javascript
142 -ReactComponent render(
143 - ReactElement element,
144 - DOMElement container,
145 - [function callback]
146 -)
147 -```
148 -
149 -渲染一个 ReactElement 到 DOM 里提供的 `容器(container)`中,并返回一个对 组件(或者返回 `null` 对于 [无状态组件](/react/docs/reusable-components-zh-CN.html#无状态函数)) 的[引用](/react/docs/more-about-refs.html)
150 -
151 -如果 ReactElement 之前被渲染到了 `container` 中,这将对它执行一次更新,并仅变动需要变动的 DOM 来反映最新的 React 组件。
152 -
153 -如果提供了可选的回调函数,则该函数将会在组件渲染或者更新之后被执行。
154 -
155 -> 注意:
156 ->
157 -> `ReactDOM.render()` 控制你传入的 container 节点的内容。
158 -> 当初次调用时,任何现存于内的 DOM 元素将被替换。
159 -> 其后的调用使用 React的 diffing 算法来有效率的更新。
160 ->
161 -> `ReactDOM.render()` 不会修改 container 节点(只修改 container 的子级)。
162 -> 将来,也许能够直接插入一个组件到已经存在的 DOM 节点而不覆盖
163 -> 现有的子级。
164 -
165 -
166 -### ReactDOM.unmountComponentAtNode
167 -
168 -```javascript
169 -boolean unmountComponentAtNode(DOMElement container)
170 -```
171 -
172 -从 DOM 中移除已经挂载的 React 组件,并清除它的事件处理器和 state。如果在 container 中没有组件被挂载,调用此函数将什么都不做。如果组件被卸载返回 `true`,如果没有组件被卸载返回 `false`。
173 -
174 -
175 -### ReactDOM.findDOMNode
176 -
177 -```javascript
178 -DOMElement findDOMNode(ReactComponent component)
179 -```
180 -如果这个组件已经被挂载到了 DOM,它返回相应的浏览器原生的 DOM 元素。这个方法对于读取 DOM 的值很有用,比如表单域的值和执行 DOM 的测量。**在大多数情况下,你可以连接一个ref到DOM节点上,并避免使用 `findDOMNode`** 如果 `render` 返回 `null` 或者 `false`, `findDOMNode` 返回 `null`.
181 -
182 -> 注意:
183 ->
184 -> `findDOMNode()` 是一个用来访问底层DOM节点的安全舱口.大多数情况下,使用这个安全舱口是不被鼓励的,因为它穿破了组件的抽象.
185 ->
186 -> `findDOMNode()` 只在已挂载的组件上工作(即是,已经被放置到DOM里的组件).如果你尝试在没有被挂载的组件上调用这个方法(比如在 一个没有被创建的组件的`render()`里 调用 `findDOMNode()` )会抛出一个异常.
187 ->
188 -> `findDOMNode()` 不能用在无状态组件.
189 -
190 -## ReactDOMServer
191 -
192 -`react-dom/server` 允许你在服务器上渲染你的组件.
193 -
194 -### ReactDOMServer.renderToString
195 -
196 -```javascript
197 -string renderToString(ReactElement element)
198 -```
199 -
200 -把 ReactElement 渲染为它原始的 HTML 。这应该仅在服务器端使用。React 将会返回一个 HTML 字符串。你可以用这种方法在服务器端生成 HTML,然后在初始请求下传这些标记,以获得更快的页面加载速度及允许搜索引擎抓取页面(便于 SEO)。
201 -
202 -如果在一个在已经有了这种服务器预渲染标记的节点上面调用 `ReactDOM.render()`,React 将会维护该节点,仅绑定事件处理器,让你有一个非常高效的初次加载体验。
203 -
204 -
205 -### ReactDOMServer.renderToStaticMarkup
206 -
207 -```javascript
208 -string renderToStaticMarkup(ReactElement element)
209 -```
210 -
211 -类似于 `renderToString` ,除了不创建额外的 DOM 属性,比如 `data-react-id`,这仅在 React 内部使用的属性。如果你想用 React 做一个简单的静态页面生成器,这是很有用的,因为去除额外的属性能够节省很多字节。
docs/docs/ref-02-component-api.it-IT.md deleted
-94
@@ -1,94 +0,0 @@
1 ----
2 -id: component-api-it-IT
3 -title: API dei Componenti
4 -permalink: docs/component-api-it-IT.html
5 -prev: top-level-api-it-IT.html
6 -next: component-specs-it-IT.html
7 ----
8 -
9 -## React.Component
10 -
11 -Istanze di un React Component sono create internamente a React durante il rendering. Queste istanze sono riutilizzate in rendering successivi, e possono essere accedute dai metodi del tuo componente come `this`. L'unica maniera di ottenere un riferimento a una istanza di un React Component fuori da React è conservare il valore restituito da `ReactDOM.render`. All'interno di altri Component, puoi utilizzare [i ref](/react/docs/more-about-refs.html) per ottenere il medesimo risultato.
12 -
13 -
14 -### setState
15 -
16 -```javascript
17 -void setState(
18 - function|object nextState,
19 - [function callback]
20 -)
21 -```
22 -Effettua una combinazione di `nextState` nello stato attuale. Questo è il metodo principale che va usato per scatenare aggiornamenti della UI da gestori di eventi e callback di richieste al server.
23 -
24 -Il primo argomento può essere un oggetto (contenente zero o più chiavi da aggiornare) o una funzione (con argomenti `state` e `props`) che restituisce un oggetto contenente chiavi da aggiornare.
25 -
26 -Ecco come utilizzarla passando un oggetto:
27 -
28 -```javascript
29 -setState({mykey: 'my new value'});
30 -```
31 -
32 -È anche possibile passare una funzione con la firma `function(state, props)`. Questo può essere utile in certi casi quando desideri accodare un aggiornamento atomico che consulta i valori precedenti di state+props prima di impostare i nuovi valori. Ad esempio, supponi che vogliamo incrementare un valore nello stato:
33 -
34 -```javascript
35 -setState(function(previousState, currentProps) {
36 - return {myInteger: previousState.myInteger + 1};
37 -});
38 -```
39 -
40 -Il secondo parametro (opzionale) è una funzione callback che verrà eseguita quando `setState` ha terminato e il rendering del componente è stato effettuato.
41 -
42 -> Note:
43 ->
44 -> *MAI* modificare `this.state` direttamente, in quanto chiamare `setState()` successivamente potrebbe sovrascrivere la modifica fatta. Tratta `this.state` come se fosse immutabile.
45 ->
46 -> `setState()` non cambia immediatamente `this.state`, ma crea una transizione di stato in corso. Accedere `this.state` subito dopo aver chiamato questo metodo potrebbe potenzialmente restituire il valore precedente.
47 ->
48 -> Non viene garantita alcuna sincronicità per le chiamate di `setState`, e le chiamate stesse potrebbero essere raggruppate per migliorare le prestazioni.
49 ->
50 -> `setState()` scatena sempre un ri-rendering a meno che la logica di rendering condizionale venga implementata in `shouldComponentUpdate()`. Se oggetti mutabili sono usati e la logica non può essere implementata in `shouldComponentUpdate()`, chiamare `setState()` solo quando il nuovo stato differisce dal precedente eviterà ri-rendering superflui.
51 -
52 -
53 -### replaceState
54 -
55 -```javascript
56 -void replaceState(
57 - object nextState,
58 - [function callback]
59 -)
60 -```
61 -
62 -Come `setState()`, ma elimina ogni chiave preesistente che non si trova in `nextState`.
63 -
64 -> Nota:
65 ->
66 -> Questo metodo non è disponibile il componenti `class` ES6 che estendono `React.Component`. Potrebbe essere eliminato del tutto in una versione futura di React.
67 -
68 -
69 -### forceUpdate
70 -
71 -```javascript
72 -void forceUpdate(
73 - [function callback]
74 -)
75 -```
76 -
77 -In modo predefinito, quando lo stato o le proprietà del tuo componente cambiano, ne verrà effettuato il ri-rendering. Tuttavia, se questi cambiano implicitamente (ad es.: dati profondi all'interno di un oggetto cambiano senza che l'oggetto stesso cambi) o se il tuo metodo `render()` dipende da altri dati, puoi istruire React perché riesegua `render()` chiamando `forceUpdate()`.
78 -
79 -Chiamare `forceUpdate()` causerà la chiamata di `render()` sul componente, saltando l'esecuzione di `shouldComponentUpdate()`. Questo scatenerà i normali metodi del ciclo di vita per i componenti figli, incluso il metodo `shouldComponentUpdate()` di ciascun figlio. React tuttavia aggiornerà il DOM soltanto se il markup effettivamente cambia.
80 -
81 -Normalmente dovresti cercare di evitare l'uso di `forceUpdate()` e leggere soltanto `this.props` e `this.state` all'interno di `render()`. Ciò rende il tuo componente "puro" e la tua applicazione molto più semplice ed efficiente.
82 -
83 -
84 -### isMounted
85 -
86 -```javascript
87 -boolean isMounted()
88 -```
89 -
90 -`isMounted()` restituisce `true` se il rendering del componente è stato effettuato nel DOM, `false` altrimenti. Puoi usare questo metodo come guardia per chiamate asincrone a `setState()` o `forceUpdate()`.
91 -
92 -> Nota:
93 ->
94 -> Questo metodo non è disponibile il componenti `class` ES6 che estendono `React.Component`. Potrebbe essere eliminato del tutto in una versione futura di React.
docs/docs/ref-02-component-api.ko-KR.md deleted
-95
@@ -1,95 +0,0 @@
1 ----
2 -id: component-api-ko-KR
3 -title: 컴포넌트 API
4 -permalink: docs/component-api-ko-KR.html
5 -prev: top-level-api-ko-KR.html
6 -next: component-specs-ko-KR.html
7 ----
8 -
9 -## React.Component
10 -
11 -React 컴포넌트의 인스턴스는 React가 렌더링 시에 내부적으로 만듭니다. 이때 만들어진 인스턴스는 이후의 렌더링에서 다시 사용되고 컴포넌트의 메소드들에서 `this` 변수로 접근할 수 있습니다. React 외부에서 React 컴포넌트의 핸들을 얻는 방법은 `ReactDOM.render`의 리턴값을 저장하는 것이 유일합니다. 다른 컴포넌트 안에서 비슷한 결과를 얻으려면 [refs](/react/docs/more-about-refs-ko-KR.html)를 사용해야 합니다.
12 -
13 -
14 -### setState
15 -
16 -```javascript
17 -void setState(
18 - function|object nextState,
19 - [function callback]
20 -)
21 -```
22 -
23 -nextState를 현재 state에 얕게(shallow) 병합합니다. 이벤트 핸들러와 서버 요청 콜백에서 UI 업데이트를 발생시키기 위해 이 메소드를 주로 사용합니다.
24 -
25 -첫번째 인자는 업데이트를 위한 키를 0개 이상 가진 객체이거나 업데이트를 위한 키들을 포함한 객체를 반환하는 함수(의 state나 props)일 수 있습니다.
26 -
27 -객체를 사용하는 간단한 예제입니다:
28 -
29 -```javascript
30 -setState({mykey: '새로운 값'});
31 -```
32 -
33 -`function(state, props)`처럼 인자를 포함한 함수를 넘겨주는 것도 가능합니다. 어떤 값이든 state와 props의 이전 값을 참고해서 원자적인 업데이트를 큐에 추가(enqueue)하려는 경우 이는 유용합니다. 예를 들어 state의 값을 증가 시키려는 경우 같이 처리 가능합니다:
34 -
35 -```javascript
36 -setState(function(previousState, currentProps) {
37 - return {myInteger: previousState.myInteger + 1};
38 -});
39 -```
40 -
41 -두번째 인자는 선택적이며, `setState`가 한번 완료되고 컴포넌트가 다시 렌더 되었을때 실행되는 콜백 함수입니다.
42 -
43 -> 주의:
44 ->
45 -> *절대로* `this.state`를 직접 변경하지 마세요. 그 뒤에 `setState()`를 호출하면 그동안 변경했던 것이 교체될 수 있습니다. `this.state`는 변경 불가능한 것으로 생각하시는 것이 좋습니다.
46 ->
47 -> `setState()`를 호출해도 `this.state`가 곧바로 변경되지 않고 대기 중인 state transition이 만들어집니다. 이 메소드를 호출한 직후 `this.state`에 접근하면 바뀌기 전의 값을 리턴할 가능성이 있습니다.
48 ->
49 -> `setState`에 대한 호출이 동기적으로 처리된다는 보장이 없으며, 성능 향상을 위해 배치 처리될 수 있습니다.
50 ->
51 -> `setState()`는 `shouldComponentUpdate()`에 조건부 렌더링 로직이 구현되어 있지 않다면 항상 재렌더링을 발생시킵니다. 변경 가능한 객체를 사용하고 있고 조건부 렌더링 로직을 `shouldComponentUpdate()`에 구현할 수 없는 경우라면 새로운 state가 이전 state와 달라지는 경우에만 `setState()`를 호출하여 불필요한 재렌더링을 피할 수 있습니다.
52 -
53 -
54 -### replaceState
55 -
56 -```javascript
57 -void replaceState(
58 - object nextState,
59 - [function callback]
60 -)
61 -```
62 -
63 -`setState()`와 비슷하지만 기존에 존재하는 state 중 nextState에 없는 키는 모두 삭제됩니다.
64 -
65 -> 주의:
66 ->
67 -> 이 메소드는 `React.Component`를 확장한 ES6 `class` 컴포넌트에서는 사용할 수 없습니다. React의 미래 버전에서 이는 완전히 사라지게 될 것입니다.
68 -
69 -
70 -### forceUpdate
71 -
72 -```javascript
73 -void forceUpdate(
74 - [function callback]
75 - )
76 -```
77 -
78 -기본적으로, 컴포넌트의 state나 props가 변경되면, 컴포넌트는 다시 렌더됩니다. 하지만 이런 변경이 묵시적이거나(예를들어 객체의 변경 없이 깊이 있는 데이터만 변경된 경우) `render()` 함수가 다른 값에 의존하는 경우, `forceUpdate()`를 호출해 React에게 `render()`를 다시 실행할 필요가 있다고 알릴 수 있습니다.
79 -
80 -`forceUpdate()`를 호출하면 `shouldComponentUpdate()`를 생략하고 해당 컴포넌트 `render()` 함수가 호출됩니다. 각 자식 컴포넌트에 대해서는 `shouldComponentUpdate()`를 포함해 보통 라이프 사이클 메서드를 호출합니다. React는 마크업이 변경된 경우에만 DOM을 업데이트합니다.
81 -
82 -특별한 경우가 아니면 `forceUpdate()`는 되도록 피하시고 `render()`에서는 `this.props`와 `this.state`에서만 읽어오세요. 그렇게 하는 것이 컴포넌트를 "순수"하게 하고 애플리케이션을 훨씬 단순하고 효율적으로 만들어줍니다.
83 -
84 -
85 -### isMounted
86 -
87 -```javascript
88 -boolean isMounted()
89 -```
90 -
91 -`isMounted()`는 컴포넌트가 DOM에 렌더링되었으면 `true`를, 아니면 `false`를 리턴합니다. 비동기적으로 `setState()`나 `forceUpdate()`를 호출할 때 이 메소드를 사용하여 오류를 방지할 수 있습니다.
92 -
93 -> 주의:
94 ->
95 -> 이 메소드는 `React.Component`를 확장한 ES6 `class` 컴포넌트에서는 사용할 수 없습니다. React의 미래 버전에서 이는 완전히 사라지게 될 것입니다.
docs/docs/ref-02-component-api.md deleted
-94
@@ -1,94 +0,0 @@
1 ----
2 -id: component-api
3 -title: Component API
4 -permalink: docs/component-api.html
5 -prev: top-level-api.html
6 -next: component-specs.html
7 ----
8 -
9 -## React.Component
10 -
11 -Instances of a React Component are created internally in React when rendering. These instances are reused in subsequent renders, and can be accessed in your component methods as `this`. The only way to get a handle to a React Component instance outside of React is by storing the return value of `ReactDOM.render`. Inside other Components, you may use [refs](/react/docs/more-about-refs.html) to achieve the same result.
12 -
13 -
14 -### setState
15 -
16 -```javascript
17 -void setState(
18 - function|object nextState,
19 - [function callback]
20 -)
21 -```
22 -Performs a shallow merge of nextState into current state. This is the primary method you use to trigger UI updates from event handlers and server request callbacks.
23 -
24 -The first argument can be an object (containing zero or more keys to update) or a function (of state and props) that returns an object containing keys to update.
25 -
26 -Here is the simple object usage:
27 -
28 -```javascript
29 -setState({mykey: 'my new value'});
30 -```
31 -
32 -It's also possible to pass a function with the signature `function(state, props)`. This can be useful in some cases when you want to enqueue an atomic update that consults the previous value of state+props before setting any values. For instance, suppose we wanted to increment a value in state:
33 -
34 -```javascript
35 -setState(function(previousState, currentProps) {
36 - return {myInteger: previousState.myInteger + 1};
37 -});
38 -```
39 -
40 -The second (optional) parameter is a callback function that will be executed once `setState` is completed and the component is re-rendered.
41 -
42 -> Notes:
43 ->
44 -> *NEVER* mutate `this.state` directly, as calling `setState()` afterwards may replace the mutation you made. Treat `this.state` as if it were immutable.
45 ->
46 -> `setState()` does not immediately mutate `this.state` but creates a pending state transition. Accessing `this.state` after calling this method can potentially return the existing value.
47 ->
48 -> There is no guarantee of synchronous operation of calls to `setState` and calls may be batched for performance gains.
49 ->
50 -> `setState()` will always trigger a re-render unless conditional rendering logic is implemented in `shouldComponentUpdate()`. If mutable objects are being used and the logic cannot be implemented in `shouldComponentUpdate()`, calling `setState()` only when the new state differs from the previous state will avoid unnecessary re-renders.
51 -
52 -
53 -### replaceState
54 -
55 -```javascript
56 -void replaceState(
57 - object nextState,
58 - [function callback]
59 -)
60 -```
61 -
62 -Like `setState()` but deletes any pre-existing state keys that are not in nextState.
63 -
64 -> Note:
65 ->
66 -> This method is not available on ES6 `class` components that extend `React.Component`. It may be removed entirely in a future version of React.
67 -
68 -
69 -### forceUpdate
70 -
71 -```javascript
72 -void forceUpdate(
73 - [function callback]
74 -)
75 -```
76 -
77 -By default, when your component's state or props change, your component will re-render. However, if these change implicitly (eg: data deep within an object changes without changing the object itself) or if your `render()` method depends on some other data, you can tell React that it needs to re-run `render()` by calling `forceUpdate()`.
78 -
79 -Calling `forceUpdate()` will cause `render()` to be called on the component, skipping `shouldComponentUpdate()`. This will trigger the normal lifecycle methods for child components, including the `shouldComponentUpdate()` method of each child. React will still only update the DOM if the markup changes.
80 -
81 -Normally you should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()`. This makes your component "pure" and your application much simpler and more efficient.
82 -
83 -
84 -### isMounted
85 -
86 -```javascript
87 -boolean isMounted()
88 -```
89 -
90 -`isMounted()` returns `true` if the component is rendered into the DOM, `false` otherwise. You can use this method to guard asynchronous calls to `setState()` or `forceUpdate()`.
91 -
92 -> Note:
93 ->
94 -> This method is not available on ES6 `class` components that extend `React.Component`. It will likely be removed entirely in a future version of React, so you might as well [start migrating away from isMounted() now](/react/blog/2015/12/16/ismounted-antipattern.html).
docs/docs/ref-02-component-api.zh-CN.md deleted
-94
@@ -1,94 +0,0 @@
1 ----
2 -id: component-api-zh-CN
3 -title: 组件 API
4 -permalink: docs/component-api-zh-CN.html
5 -prev: top-level-api-zh-CN.html
6 -next: component-specs-zh-CN.html
7 ----
8 -
9 -## React.Component
10 -
11 -当渲染时,React 组件的实例在 React 内部被创建。这些实例在随后的渲染中被重复使用,并可以在组件方法中通过 `this` 访问。唯一的在 React 之外获取 React 组件实例句柄的方法是保存 `ReactDOM.render` 的返回值。在其它组件内,你可以使用 [refs](/react/docs/more-about-refs-zh-CN.html) 得到相同的结果。
12 -
13 -
14 -### setState
15 -
16 -```javascript
17 -void setState(
18 - function|object nextState,
19 - [function callback]
20 -)
21 -```
22 -执行一个 nextState 到当前 state 的浅合并。这是你从事件处理器和服务器请求回调用来触发 UI 更新的主要手段。
23 -
24 -第一个参数可以是一个对象(包含0或者多个keys来更新)或者一个(state 和 props的)函数,它返回一个包含要更新的keys的对象。
25 -
26 -这里是一个简单的运用:
27 -
28 -```javascript
29 -setState({mykey: 'my new value'});
30 -```
31 -
32 -也可以以 `function(state, props)` 传递一个函数。当你想要把一个在设置任何值之前参考前一次 state+props 的值的原子更新放在队列中 这会有很用。例如,假如我们想在 state 增加一个值:
33 -
34 -```javascript
35 -setState(function(previousState, currentProps) {
36 - return {myInteger: previousState.myInteger + 1};
37 -});
38 -```
39 -
40 -第二个(可选)的参数是一个将会在 `setState` 完成和组件被重绘后执行的回调函数。
41 -
42 -> 注意:
43 ->
44 -> *绝对不要* 直接改变 `this.state`,因为之后调用 `setState()` 可能会替换掉你做的改变。把 `this.state` 当做是不可变的。
45 ->
46 -> `setState()` 不会立刻改变 `this.state`,而是创建一个即将处理的 state 转变。在调用该方法之后访问 `this.state` 可能会返回现有的值。
47 ->
48 -> 对 `setState` 的调用没有任何同步性的保证,并且调用可能会为了性能收益批量执行。
49 ->
50 -> `setState()` 将总是触发一次重绘,除非在 `shouldComponentUpdate()` 中实现了条件渲染逻辑。如果可变对象被使用了,但又不能在 `shouldComponentUpdate()` 中实现这种逻辑,仅在新 state 和之前的 state 存在差异的时候调用 `setState()` 可以避免不必要的重新渲染。
51 -
52 -
53 -### replaceState
54 -
55 -```javascript
56 -void replaceState(
57 - object nextState,
58 - [function callback]
59 -)
60 -```
61 -
62 -类似于 `setState()`,但是删除任何 先前存在但不在 nextState 里的 state 键。
63 -
64 -> 注意:
65 ->
66 -> 这个方法在从 `React.Component` 扩展的 ES6 `class` 组件里不可用。它也许会在未来的 React 版本中被完全移除。
67 -
68 -
69 -### forceUpdate
70 -
71 -```javascript
72 -void forceUpdate(
73 - [function callback]
74 -)
75 -```
76 -
77 -默认情况下,当你的组件的 state 或者 props 改变,你的组件将会重绘。然而,如果它们隐式的改变(例如:在对象深处的数据改变了但没有改变对象本身)或者如果你的 `render()` 方法依赖于其他的数据,你可以用调用 `forceUpdate()` 来告诉 React 它需要重新运行 `render()`。
78 -
79 -调用 `forceUpdate()` 将会导致 `render()` 跳过 `shouldComponentUpdate()` 在组件上被调用,这会为子级触发正常的生命周期方法。包括每个子级的 `shouldComponentUpdate()` 方法。如果标记改变了,React 仍仅只更新 DOM。
80 -
81 -通常你应该试着避免所有对 `forceUpdate()` 的使用并且在 `render()` 里只从 `this.props` 和 `this.state` 读取。这会使你的组件 "纯粹" 并且你的组件会更简单和高效。
82 -
83 -
84 -### isMounted
85 -
86 -```javascript
87 -boolean isMounted()
88 -```
89 -
90 -如果组件渲染到了 DOM 中,`isMounted()` 返回 true,否则返回 `false`。可以使用该方法来控制对 `setState()` 和 `forceUpdate()` 的异步调用。
91 -
92 -> 注意:
93 ->
94 -> 这个方法在从 `React.Component` 扩展的 ES6 `class` 组件里不可用。它也许会在未来的 React 版本中被完全移除,所以你也要移除它 [start migrating away from isMounted() now](/react/blog/2015/12/16/ismounted-antipattern.html)
docs/docs/ref-03-component-specs.it-IT.md deleted
-221
@@ -1,221 +0,0 @@
1 ----
2 -id: component-specs-it-IT
3 -title: Specifica dei Componenti e Ciclo di Vita
4 -permalink: docs/component-specs-it-IT.html
5 -prev: component-api-it-IT.html
6 -next: tags-and-attributes-it-IT.html
7 ----
8 -
9 -## Specifica dei Componenti
10 -
11 -Quando crei una classe di componente invocando `React.createClass()`, devi fornire un oggetto specifica che contiene un metodo `render` che può contenere opzionalmete altri metodi del ciclo di vita descritti di seguito.
12 -
13 -> Nota:
14 ->
15 -> È anche possibile usare pure classi JavaScript come classi di componente. Queste classi possono implementare la maggior parte degli stessi metodi, sebbene vi siano delle differenze. Per maggiori informazioni su queste differenze, leggi la nostra documentazione sulle [classi ES6](/react/docs/reusable-components.html#es6-classes).
16 -
17 -### render
18 -
19 -```javascript
20 -ReactElement render()
21 -```
22 -
23 -Il metodo `render()` è richiesto.
24 -
25 -Quando viene chiamato, dovrebbe esaminare `this.props` e `this.state` e restituire un singolo elemento figlio. Questo elemento figlio può essere sia una rappresentazione virtuale di un componente DOM nativo (come `<div />` o `React.DOM.div()`) o un altro componente composito che hai definito tu stesso.
26 -
27 -Puoi anche restituire `null` o `false` per indicare che desideri che non venga visualizzato nulla. Dietro le quinte, React visualizza un tag `<noscript>` per lavorare con il nostro attuale algoritmo di differenza. Quando si restituisce `null` o `false`, `ReactDOM.findDOMNode(this)` restituirà `null`.
28 -
29 -La funzione `render()` dovrebbe essere *pura*, nel senso che non modifica lo stato del componente, restituisce lo stesso risultato ogni volta che viene invocato, e non legge o scrive il DOM o interagisce in altro modo con il browser (ad es. usando `setTimeout`). Se devi interagire con il browser, effettua le tue operazioni in `componentDidMount()` o negli altri metodi del ciclo di vita. Mantenere `render()` puro rende il rendering lato server più praticabile e rende i componenti più facili da comprendere.
30 -
31 -
32 -### getInitialState
33 -
34 -```javascript
35 -object getInitialState()
36 -```
37 -
38 -Invocato una volta prima che il componente venga montato. Il valore di ritorno sarà usato come il valore iniziale di `this.state`.
39 -
40 -> Nota:
41 ->
42 -> Questo metodo non è disponibile il componenti `class` ES6 che estendono `React.Component`. Per maggiori informazioni, leggi la nostra documentazione sulle [classi ES6](/react/docs/reusable-components.html#es6-classes).
43 -
44 -
45 -### getDefaultProps
46 -
47 -```javascript
48 -object getDefaultProps()
49 -```
50 -
51 -Invocato una volta e conservato quando la classe è creata. I valori nella mappa saranno impostati in `this.props` se tale proprietà non è specificata dal componente genitore (ad es. usando un controllo `in`).
52 -
53 -Questo metodo è invocato prima che un'istanza sia creata e quindi non può dipendere da `this.props`. Inoltre, tieni presente che ogni oggetto complesso restituito da `getDefaultProps()` sarà condiviso tra le diverse istanze, non copiato.
54 -
55 -
56 -### propTypes
57 -
58 -```javascript
59 -object propTypes
60 -```
61 -
62 -L'oggetto `propTypes` ti permette di validare le proprietà passate ai tuoi componenti. Per maggiori informazioni su `propTypes`, leggi [Componenti Riutilizzabili](/react/docs/reusable-components-it-IT.html).
63 -
64 -
65 -### mixins
66 -
67 -```javascript
68 -array mixins
69 -```
70 -
71 -L'array `mixins` ti permette di usare i mixin per condividere il comportamento tra componenti multipli. Per maggiori informazioni sui mixin, leggi [Componenti Riutilizzabili](/react/docs/reusable-components-it-IT.html).
72 -
73 -
74 -### statics
75 -
76 -```javascript
77 -object statics
78 -```
79 -
80 -L'oggetto `statics` ti permette di definire metodi statici che possono essere chiamati sulla classe del componente. Ad esempio:
81 -
82 -```javascript
83 -var MyComponent = React.createClass({
84 - statics: {
85 - customMethod: function(foo) {
86 - return foo === 'bar';
87 - }
88 - },
89 - render: function() {
90 - }
91 -});
92 -
93 -MyComponent.customMethod('bar'); // true
94 -```
95 -
96 -I metodi definiti in questo blocco sono _statici_, ovvero puoi eseguirli prima che un'istanza del componente venga creata, e i metodi non hanno accesso alle proprietà e lo stato dei tuoi componenti. Se desideri confrontare i valori delle proprietà in un metodo statico, devi farle passare dal chiamante al metodo statico tramite un argomento.
97 -
98 -
99 -### displayName
100 -
101 -```javascript
102 -string displayName
103 -```
104 -
105 -La stringa `displayName` viene usata nei messaggi di debug. JSX imposta questo valore automaticamente; vedi [JSX in Profondità](/react/docs/jsx-in-depth-it-IT.html#the-transform).
106 -
107 -
108 -## Metodi del Ciclo di Vita
109 -
110 -Vari metodi vengono eseguiti durante precisi momenti del ciclo di vita di un componente.
111 -
112 -
113 -### Montaggio: componentWillMount
114 -
115 -```javascript
116 -void componentWillMount()
117 -```
118 -
119 -Invocato una volta, sia sul client che sul server, immediatamente prima che il rendering iniziale abbia luogo. Se chiami `setState` all'interno di questo metodo, `render()` vedrà lo stato aggiornato e sarà eseguito solo una volta nonostante il cambiamento di stato.
120 -
121 -
122 -### Montaggio: componentDidMount
123 -
124 -```javascript
125 -void componentDidMount()
126 -```
127 -
128 -Invocato una volta, solo sul client (e non sul server), immediatamente dopo che il rendering iniziale ha avuto luogo. A questo punto del ciclo di vita, il componente ha una rappresentazione DOM che puoi accedere attraverso `ReactDOM.findDOMNode(this)`. Il metodo `componentDidMount()` dei componenti figli è invocato prima di quello dei componenti genitori.
129 -
130 -Se desideri integrare con altri framework JavaScript, impostare dei timer usando `setTimeout` o `setInterval`, oppure inviare richieste AJAX, effettua tali operazioni in questo metodo.
131 -
132 -
133 -### Aggiornamento: componentWillReceiveProps
134 -
135 -```javascript
136 -void componentWillReceiveProps(
137 - object nextProps
138 -)
139 -```
140 -
141 -Invocato quando un componente sta ricevendo nuove proprietà. Questo metodo non viene chiamato durante il rendering iniziale.
142 -
143 -Usa questo metodo come opportunità per reagire a una transizione di proprietà prima che `render()` venga chiamato, aggiornando lo stato usando `this.setState()`. I vecchi valori delle proprietà possono essere letti tramite `this.props`. Chiamare `this.setState()` all'interno di questa funzione non scatenerà un rendering addizionale.
144 -
145 -```javascript
146 -componentWillReceiveProps: function(nextProps) {
147 - this.setState({
148 - likesIncreasing: nextProps.likeCount > this.props.likeCount
149 - });
150 -}
151 -```
152 -
153 -> Nota:
154 ->
155 -> Non esiste un metodo analogo `componentWillReceiveState`. Una imminente transizione delle proprietà potrebbe causare un cambiamento di stato, ma il contrario non è vero. Se devi effettuare delle operazioni in risposta a un cambiamento di stato, usa `componentWillUpdate`.
156 -
157 -
158 -### Aggiornamento: shouldComponentUpdate
159 -
160 -```javascript
161 -boolean shouldComponentUpdate(
162 - object nextProps, object nextState
163 -)
164 -```
165 -
166 -Invocato prima del rendering quando vengono ricevuti nuove proprietà o un nuovo stato. Questo metodo non viene chiamato per il rendering iniziale o quando viene usato `forceUpdate`.
167 -
168 -Usa questo metodo come opportunità per restituire `false` quando si è certi che la transizione alle nuove proprietà e al nuovo stato non richieda un aggiornamento del componente.
169 -
170 -```javascript
171 -shouldComponentUpdate: function(nextProps, nextState) {
172 - return nextProps.id !== this.props.id;
173 -}
174 -```
175 -
176 -Se `shouldComponentUpdate` restituisce false, allora `render()` sarà saltato completamente fino al prossimo cambiamento di stato. Inoltre, `componentWillUpdate` e `componentDidUpdate` non verranno chiamati.
177 -
178 -In modo predefinito, `shouldComponentUpdate` restituisce sempre `true` per evitare bachi subdoli quando `state` viene modificato direttamente, ma se hai l'accortezza di trattare sempre `state` come immutabile e accedere a `props` e `state` in sola lettura in `render()`, allora puoi tranquillamente ridefinire `shouldComponentUpdate` con un'implementazione che confronta i vecchi valori di props e state con quelli nuovi.
179 -
180 -Se le prestazioni diventano un collo di bottiglia, specialmente in presenza di decine o centinaia di componenti, usa `shouldComponentUpdate` per accelerare la tua applicazione.
181 -
182 -
183 -### Aggiornamento: componentWillUpdate
184 -
185 -```javascript
186 -void componentWillUpdate(
187 - object nextProps, object nextState
188 -)
189 -```
190 -
191 -Invocato immediatamente prima del rendering quando nuove proprietà o un nuovo stato vengono ricevuti. Questo metodo non viene chiamato per il rendering iniziale.
192 -
193 -Usa questo metodo come opportunità per effettuare la preparazione prima che si verifichi un aggiornamento.
194 -
195 -> Nota:
196 ->
197 -> *Non puoi* usare `this.setState()` in questo metodo. Se devi aggiornare lo stato in risposta al cambiamento di una proprietà, usa `componentWillReceiveProps`.
198 -
199 -
200 -### Aggiornamento: componentDidUpdate
201 -
202 -```javascript
203 -void componentDidUpdate(
204 - object prevProps, object prevState
205 -)
206 -```
207 -
208 -Invocato immediatamente dopo che gli aggiornamenti del componente sono stati trasmessi al DOM. Questo metodo non viene chiamato per il rendering iniziale.
209 -
210 -Usa questo metodo come opportunità per operare sul DOM quando il componente è stato the component has been updated.
211 -
212 -
213 -### Smontaggio: componentWillUnmount
214 -
215 -```javascript
216 -void componentWillUnmount()
217 -```
218 -
219 -Invocato immediatamente prima che un componente venga smontato dal DOM.
220 -
221 -Effettua la necessaria pulizia in questo metodo, come invalidare i timer o ripulire ciascun elemento DOM creato all'interno di `componentDidMount`.
docs/docs/ref-03-component-specs.ko-KR.md deleted
-222
@@ -1,222 +0,0 @@
1 ----
2 -id: component-specs-ko-KR
3 -title: 컴포넌트 명세와 생명주기
4 -permalink: docs/component-specs-ko-KR.html
5 -prev: component-api-ko-KR.html
6 -next: tags-and-attributes-ko-KR.html
7 ----
8 -
9 -## 컴포넌트 명세
10 -
11 -`React.createClass()`를 호출하여 컴포넌트 클래스를 생성할 때, `render` 메소드를 포함한 명세 객체를 제공해야 합니다. 또한 필요한 경우 여기에서 설명하는 다른 생명주기 메소드를 명세 객체에 추가로 제공할 수 있습니다.
12 -
13 -> 주의:
14 ->
15 -> 그냥 JavaScript 클래스를 컴포넌트 클래스로 사용할 수도 있습니다. 이 클래스는 구현할 수 있는 메소드가 거의 같지만 약간의 차이가 있습니다. 차이에 관한 더 자세한 정보는 [ES6 클래스](/react/docs/reusable-components-ko-KR.html#es6-클래스)를 읽어보세요.
16 -
17 -### render
18 -
19 -```javascript
20 -ReactElement render()
21 -```
22 -
23 -`render()` 메소드는 필수 항목입니다.
24 -
25 -호출되면 `this.props`와 `this.state`를 토대로 하나의 자식 엘리먼트를 리턴합니다. 이 자식 엘리먼트는 네이티브 DOM 컴포넌트의 가상 표현 (`<div />`나 `React.DOM.div()` 등) 또는 직접 정의한 조합(composite) 컴포넌트가 될 수 있습니다.
26 -
27 -아무 것도 렌더링되지 않도록 하려면 `null`이나 `false`를 리턴합니다. React는 지금의 차이 비교 알고리즘이 작동할 수 있도록 내부적으로는 `<noscript>` 태그를 렌더링합니다. `null`이나 `false`를 리턴한 경우, `ReactDOM.findDOMNode(this)`는 `null`을 리턴합니다.
28 -
29 -`render()` 함수는 순수 함수여야 합니다. 즉, 컴포넌트의 상태를 변경하지 않고, 여러번 호출해도 같은 결과를 리턴하며, DOM을 읽고 쓰거나 브라우저와 상호작용(예를 들어 `setTimeout`를 사용)하지 않아야 합니다. 브라우저와 상호작용해야 한다면 `componentDidMount()`나 다른 생명주기 메소드에서 수행해야 합니다. `render()` 함수를 순수 함수로 유지하면 서버 렌더링이 훨씬 쓸만해지고 컴포넌트에 대해 생각하기 쉬워집니다.
30 -
31 -
32 -### getInitialState
33 -
34 -```javascript
35 -object getInitialState()
36 -```
37 -
38 -컴포넌트가 마운트되기 전에 한번 호출됩니다. 리턴값은 `this.state`의 초기값으로 사용됩니다.
39 -
40 -> 주의:
41 ->
42 -> 이 메소드는 `React.Component`를 확장한 ES6 `class` 컴포넌트에서는 사용할 수 없습니다. 관한 더 자세한 정보는 [ES6 클래스](/react/docs/reusable-components-ko-KR.html#es6-클래스)를 읽어보세요.
43 -
44 -
45 -### getDefaultProps
46 -
47 -```javascript
48 -object getDefaultProps()
49 -```
50 -
51 -클래스가 생성될 때 한번 호출되고 캐시됩니다. 부모 컴포넌트에서 prop이 넘어오지 않은 경우 (`in` 연산자로 확인) 매핑의 값이 `this.props`에 설정됩니다.
52 -
53 -이 메소드는 인스턴스가 만들어지기 전에 호출되므로 `this.props`에 의존할 수 없습니다. 그리고 `getDefaultProps()`의 리턴값에 포함된 복잡한 객체는 복사되지 않고 인스턴스 간에 공유됩니다.
54 -
55 -
56 -### propTypes
57 -
58 -```javascript
59 -object propTypes
60 -```
61 -
62 -`propTypes` 객체는 컴포넌트에 넘어오는 props가 올바른지 검사할 수 있게 해줍니다. `propTypes`에 대한 자세한 정보는 [재사용 가능한 컴포넌트](/react/docs/reusable-components-ko-KR.html)를 참고하세요.
63 -
64 -
65 -### mixins
66 -
67 -```javascript
68 -array mixins
69 -```
70 -
71 -`mixins` 배열은 여러 컴포넌트 사이에 동작을 공유하는 믹스인을 사용할 수 있게 해줍니다. 믹스인에 대한 자세한 정보는 [재사용 가능한 컴포넌트](/react/docs/reusable-components-ko-KR.html)를 참고하세요.
72 -
73 -
74 -### statics
75 -
76 -```javascript
77 -object statics
78 -```
79 -
80 -`statics` 객체는 컴포넌트 클래스의 스태틱 메소드를 정의할 수 있게 해줍니다. 에를 들어:
81 -
82 -```javascript
83 -var MyComponent = React.createClass({
84 - statics: {
85 - customMethod: function(foo) {
86 - return foo === 'bar';
87 - }
88 - },
89 - render: function() {
90 - }
91 -});
92 -
93 -MyComponent.customMethod('bar'); // true
94 -```
95 -
96 -이 블럭 안에서 정의된 메소드는 인스턴스를 하나도 만들지 않은 시점에도 호출할 수 있고, 컴포넌트의 props나 state에 접근할 수 없습니다. 스태틱 메소드에서 props의 값을 확인하려면 호출자가 스태틱 메소드에 props를 인자로 넘기도록 해야합니다.
97 -
98 -
99 -### displayName
100 -
101 -```javascript
102 -string displayName
103 -```
104 -
105 -`displayName` 문자열은 디버그 메시지에 사용됩니다. JSX는 이 값을 자동으로 설정합니다. [JSX 깊이 알기](/react/docs/jsx-in-depth-ko-KR.html#변환)를 참고하세요.
106 -
107 -
108 -## 생명주기 메소드
109 -
110 -컴포넌트의 생명주기에서 특정 시점마다 실행되는 메소드들입니다.
111 -
112 -
113 -### 마운트 시: componentWillMount
114 -
115 -```javascript
116 -void componentWillMount()
117 -```
118 -
119 -최초 렌더링이 일어나기 직전에 클라이언트 및 서버에서 한번 호출됩니다. 이 메소드 안에서 `setState`를 호출하면, `render()`에서 업데이트된 state를 확인할 수 있고 state가 변함에도 불구하고 `render()`가 한번만 실행됩니다.
120 -
121 -
122 -### 마운트 시: componentDidMount
123 -
124 -```javascript
125 -void componentDidMount()
126 -```
127 -
128 -최초 렌더링이 일어난 다음 클라이언트에서만 한번 호출됩니다. (서버에서는 호출되지 않습니다.) 이 시점에 자식의 refs들에 접근 할 수 있습니다. (기본 DOM 표현에 접근하는 등). 자식 컴포넌트의 `componentDidMount()` 메소드는 부모 컴포넌트보다 먼저 호출됩니다.
129 -
130 -다른 JavaScript 프레임워크를 연동하거나, `setTimeout`/`setInterval`로 타이머를 설정하고 AJAX 요청을 보내는 등의 작업을 이 메소드에서 합니다.
131 -
132 -
133 -### 업데이트 시: componentWillReceiveProps
134 -
135 -```javascript
136 -void componentWillReceiveProps(
137 - object nextProps
138 -)
139 -```
140 -
141 -컴포넌트가 새로운 props를 받을 때 호출됩니다. 이 메소드는 최초 렌더링 시에는 호출되지 않습니다.
142 -
143 -`render()`가 호출되기 전에 prop의 변화를 감지하여 `this.setState()`를 호출해서 state를 업데이트할 수 있습니다. 이전 props는 `this.props`로 접근할 수 있습니다. 이 함수 안에서 `this.setState()`를 호출해도 추가 렌더링이 발생하지 않습니다.
144 -
145 -```javascript
146 -componentWillReceiveProps: function(nextProps) {
147 - this.setState({
148 - likesIncreasing: nextProps.likeCount > this.props.likeCount
149 - });
150 -}
151 -```
152 -
153 -> 주의:
154 ->
155 -> `componentWillReceiveState`에 해당하는 메소드는 없습니다. prop이 변할 때 state가 바뀔 수는 있지만, 그 역은 불가능합니다. state의 변화에 따라 작업을 실행해야 하면 `componentWillUpdate`를 사용하세요.
156 -
157 -
158 -### 업데이트 시: shouldComponentUpdate
159 -
160 -```javascript
161 -boolean shouldComponentUpdate(
162 - object nextProps, object nextState
163 -)
164 -```
165 -
166 -새로운 props 또는 state를 받아 렌더링을 하기 전에 호출됩니다. 최초 렌더링 시나 `forceUpdate`를 사용하는 경우에는 호출되지 않습니다.
167 -
168 -새로운 props와 state가 컴포넌트 업데이트를 필요로 하지 않는 것이 확실하다면
169 -`false`를 리턴하세요.
170 -
171 -```javascript
172 -shouldComponentUpdate: function(nextProps, nextState) {
173 - return nextProps.id !== this.props.id;
174 -}
175 -```
176 -
177 -`shouldComponentUpdate`가 false를 리턴하면, 다음에 state가 바뀌기 전까지 `render()`가 완전히 호출되지 않고 넘어갑니다. `componentWillUpdate`와 `componentDidUpdate` 또한 호출되지 않습니다.
178 -
179 -기본적으로 `shouldComponentUpdate`는 항상 `true`를 리턴합니다. `state`가 제자리에서(in place) 바뀐 경우에 발생하는 파악하기 힘든 버그를 막기 위함입니다. 하지만 `state`가 항상 변경 불가능하도록 주의하고 `render()`에서 `props`와 `state`를 읽기만 하면 이전 props 및 state와 바뀌는 값을 비교하는 `shouldComponentUpdate`를 직접 구현할 수 있습니다.
180 -
181 -성능에 병목이 있다면, 특히 컴포넌트가 매우 많은 경우 `shouldComponentUpdate`를 사용하여 앱을 빠르게 만들 수 있습니다.
182 -
183 -
184 -### 업데이트 시: componentWillUpdate
185 -
186 -```javascript
187 -void componentWillUpdate(
188 - object nextProps, object nextState
189 -)
190 -```
191 -
192 -새로운 props나 state를 받았을 때 렌더링 직전에 호출됩니다. 최초 렌더링 시에는 호출되지 않습니다.
193 -
194 -업데이트가 일어나기 전에 준비하기 위해 사용할 수 있습니다.
195 -
196 -> 주의:
197 ->
198 -> 이 메소드에서는 `this.setState()`를 호출할 수 없습니다. prop 변화에 반응하여 state를 업데이트해야 할 경우, `componentWillReceiveProps`를 대신 사용하세요.
199 -
200 -
201 -### 업데이트 시: componentDidUpdate
202 -
203 -```javascript
204 -void componentDidUpdate(
205 - object prevProps, object prevState
206 -)
207 -```
208 -
209 -컴포넌트의 업데이트가 DOM에 반영된 직후에 호출됩니다. 최초 렌더링 시에는 호출되지 않습니다.
210 -
211 -컴포넌트가 업데이트된 뒤 DOM을 조작해야 하는 경우 사용할 수 있습니다.
212 -
213 -
214 -### 마운트 해제 시: componentWillUnmount
215 -
216 -```javascript
217 -void componentWillUnmount()
218 -```
219 -
220 -컴포넌트가 DOM에서 마운트 해제 되기 직전에 호출됩니다.
221 -
222 -이 메소드에서 타이머를 무효화하거나 `componentDidMount`에서 만들어진 DOM 엘리먼트를 정리하는 등 필요한 정리 작업을 수행할 수 있습니다.
docs/docs/ref-03-component-specs.md deleted
-223
@@ -1,223 +0,0 @@
1 ----
2 -id: component-specs
3 -title: Component Specs and Lifecycle
4 -permalink: docs/component-specs.html
5 -prev: component-api.html
6 -next: tags-and-attributes.html
7 ----
8 -
9 -## Component Specifications
10 -
11 -When creating a component class by invoking `React.createClass()`, you should provide a specification object that contains a `render` method and can optionally contain other lifecycle methods described here.
12 -
13 -> Note:
14 ->
15 -> It is also possible to use plain JavaScript classes as component classes. These classes can implement most of the same methods, though there are some differences. For more information about these differences, please read our documentation about [ES6 classes](/react/docs/reusable-components.html#es6-classes).
16 -
17 -### render
18 -
19 -```javascript
20 -ReactElement render()
21 -```
22 -
23 -The `render()` method is required.
24 -
25 -When called, it should examine `this.props` and `this.state` and return a single child element. This child element can be either a virtual representation of a native DOM component (such as `<div />` or `React.DOM.div()`) or another composite component that you've defined yourself.
26 -
27 -You can also return `null` or `false` to indicate that you don't want anything rendered. Behind the scenes, React renders a `<noscript>` tag to work with our current diffing algorithm. When returning `null` or `false`, `ReactDOM.findDOMNode(this)` will return `null`.
28 -
29 -The `render()` function should be *pure*, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not read from or write to the DOM or otherwise interact with the browser (e.g., by using `setTimeout`). If you need to interact with the browser, perform your work in `componentDidMount()` or the other lifecycle methods instead. Keeping `render()` pure makes server rendering more practical and makes components easier to think about.
30 -
31 -
32 -### getInitialState
33 -
34 -```javascript
35 -object getInitialState()
36 -```
37 -
38 -Invoked once before the component is mounted. The return value will be used as the initial value of `this.state`.
39 -
40 -> Note:
41 ->
42 -> This method is not available on ES6 `class` components that extend `React.Component`. For more information, please read our documentation about [ES6 classes](/react/docs/reusable-components.html#es6-classes).
43 -
44 -
45 -### getDefaultProps
46 -
47 -```javascript
48 -object getDefaultProps()
49 -```
50 -
51 -Invoked once and cached when the class is created. Values in the mapping will be set on `this.props` if that prop is not specified by the parent component (i.e. using an `in` check).
52 -
53 -This method is invoked before any instances are created and thus cannot rely on `this.props`. In addition, be aware that any complex objects returned by `getDefaultProps()` will be shared across instances, not copied.
54 -
55 -
56 -### propTypes
57 -
58 -```javascript
59 -object propTypes
60 -```
61 -
62 -The `propTypes` object allows you to validate props being passed to your components. For more information about `propTypes`, see [Reusable Components](/react/docs/reusable-components.html).
63 -
64 -
65 -### mixins
66 -
67 -```javascript
68 -array mixins
69 -```
70 -
71 -The `mixins` array allows you to use mixins to share behavior among multiple components. For more information about mixins, see [Reusable Components](/react/docs/reusable-components.html).
72 -
73 -
74 -### statics
75 -
76 -```javascript
77 -object statics
78 -```
79 -
80 -The `statics` object allows you to define static methods that can be called on the component class. For example:
81 -
82 -```javascript
83 -var MyComponent = React.createClass({
84 - statics: {
85 - customMethod: function(foo) {
86 - return foo === 'bar';
87 - }
88 - },
89 - render: function() {
90 - }
91 -});
92 -
93 -MyComponent.customMethod('bar'); // true
94 -```
95 -
96 -Methods defined within this block are _static_, meaning that you can run them before any component instances are created, and the methods do not have access to the props or state of your components. If you want to check the value of props in a static method, have the caller pass in the props as an argument to the static method.
97 -
98 -
99 -### displayName
100 -
101 -```javascript
102 -string displayName
103 -```
104 -
105 -The `displayName` string is used in debugging messages. JSX sets this value automatically; see [JSX in Depth](/react/docs/jsx-in-depth.html#the-transform).
106 -
107 -
108 -## Lifecycle Methods
109 -
110 -Various methods are executed at specific points in a component's lifecycle.
111 -
112 -
113 -### Mounting: componentWillMount
114 -
115 -```javascript
116 -void componentWillMount()
117 -```
118 -
119 -Invoked once, both on the client and server, immediately before the initial rendering occurs. If you call `setState` within this method, `render()` will see the updated state and will be executed only once despite the state change.
120 -
121 -
122 -### Mounting: componentDidMount
123 -
124 -```javascript
125 -void componentDidMount()
126 -```
127 -
128 -Invoked once, only on the client (not on the server), immediately after the initial rendering occurs. At this point in the lifecycle, you can access any refs to your children (e.g., to access the underlying DOM representation). The `componentDidMount()` method of child components is invoked before that of parent components.
129 -
130 -If you want to integrate with other JavaScript frameworks, set timers using `setTimeout` or `setInterval`, or send AJAX requests, perform those operations in this method.
131 -
132 -
133 -### Updating: componentWillReceiveProps
134 -
135 -```javascript
136 -void componentWillReceiveProps(
137 - object nextProps
138 -)
139 -```
140 -
141 -Invoked when a component is receiving new props. This method is not called for the initial render.
142 -
143 -Use this as an opportunity to react to a prop transition before `render()` is called by updating the state using `this.setState()`. The old props can be accessed via `this.props`. Calling `this.setState()` within this function will not trigger an additional render.
144 -
145 -```javascript
146 -componentWillReceiveProps: function(nextProps) {
147 - this.setState({
148 - likesIncreasing: nextProps.likeCount > this.props.likeCount
149 - });
150 -}
151 -```
152 -
153 -> Note:
154 ->
155 -> One common mistake is for code executed during this lifecycle method to assume that props have changed. To understand why this is invalid, read [A implies B does not imply B implies A](/react/blog/2016/01/08/A-implies-B-does-not-imply-B-implies-A.html)
156 ->
157 -> There is no analogous method `componentWillReceiveState`. An incoming prop transition may cause a state change, but the opposite is not true. If you need to perform operations in response to a state change, use `componentWillUpdate`.
158 -
159 -
160 -### Updating: shouldComponentUpdate
161 -
162 -```javascript
163 -boolean shouldComponentUpdate(
164 - object nextProps, object nextState
165 -)
166 -```
167 -
168 -Invoked before rendering when new props or state are being received. This method is not called for the initial render or when `forceUpdate` is used.
169 -
170 -Use this as an opportunity to `return false` when you're certain that the transition to the new props and state will not require a component update.
171 -
172 -```javascript
173 -shouldComponentUpdate: function(nextProps, nextState) {
174 - return nextProps.id !== this.props.id;
175 -}
176 -```
177 -
178 -If `shouldComponentUpdate` returns false, then `render()` will be completely skipped until the next state change. In addition, `componentWillUpdate` and `componentDidUpdate` will not be called.
179 -
180 -By default, `shouldComponentUpdate` always returns `true` to prevent subtle bugs when `state` is mutated in place, but if you are careful to always treat `state` as immutable and to read only from `props` and `state` in `render()` then you can override `shouldComponentUpdate` with an implementation that compares the old props and state to their replacements.
181 -
182 -If performance is a bottleneck, especially with dozens or hundreds of components, use `shouldComponentUpdate` to speed up your app.
183 -
184 -
185 -### Updating: componentWillUpdate
186 -
187 -```javascript
188 -void componentWillUpdate(
189 - object nextProps, object nextState
190 -)
191 -```
192 -
193 -Invoked immediately before rendering when new props or state are being received. This method is not called for the initial render.
194 -
195 -Use this as an opportunity to perform preparation before an update occurs.
196 -
197 -> Note:
198 ->
199 -> You *cannot* use `this.setState()` in this method. If you need to update state in response to a prop change, use `componentWillReceiveProps` instead.
200 -
201 -
202 -### Updating: componentDidUpdate
203 -
204 -```javascript
205 -void componentDidUpdate(
206 - object prevProps, object prevState
207 -)
208 -```
209 -
210 -Invoked immediately after the component's updates are flushed to the DOM. This method is not called for the initial render.
211 -
212 -Use this as an opportunity to operate on the DOM when the component has been updated.
213 -
214 -
215 -### Unmounting: componentWillUnmount
216 -
217 -```javascript
218 -void componentWillUnmount()
219 -```
220 -
221 -Invoked immediately before a component is unmounted from the DOM.
222 -
223 -Perform any necessary cleanup in this method, such as invalidating timers or cleaning up any DOM elements that were created in `componentDidMount`.
docs/docs/ref-03-component-specs.zh-CN.md deleted
-221
@@ -1,221 +0,0 @@
1 ----
2 -id: component-specs-zh-CN
3 -title: 组件的规范和生命周期
4 -permalink: docs/component-specs-zh-CN.html
5 -prev: component-api-zh-CN.html
6 -next: tags-and-attributes-zh-CN.html
7 ----
8 -
9 -## 组件规范(Specifications)
10 -
11 -当调用 `React.createClass()` 创建一个组件类时,你应该提供一个包含有 `render` 方法以及可选的其他生命周期方法的 规范(Specifications)对象.
12 -
13 -> 注意:
14 ->
15 -> 同样可以使用单纯的 JavaScript 类作为组件类. 这些类可以实现大多数相同的方法,虽然有一些不同.更多关于不同的信息,请阅读我们关于[ES6 classes](/react/docs/reusable-components.html#es6-classes)的文档.
16 -
17 -### render
18 -
19 -```javascript
20 -ReactElement render()
21 -```
22 -
23 - `render()` 是必须的
24 -
25 - 当被调用时,它应该检查 `this.props` 和 `this.state` 并返回单个子元素.这个子元素即可以是一个 对原生DOM的虚拟表达(比如 `<div />` 或 `React.DOM.div()`)也可以是其他你自定义的复合组件.
26 -
27 - 你也可以返回 `null` 或 `false` 来指示你不想要任何东西被渲染.幕后,React 渲染一个 `<noscript>` tag 来与我们当前的diffing算法协同工作.当返回 `null` 或 `false` ,`ReactDOM.findDOMNode(this)` 会返回 `null`.
28 -
29 - `render()` 函数应该是纯净的,意味着它不改变组件的状态,它在每次调用时返回相同的结果,并且它不读和写 DOM 或者其他方式与浏览器互动(例如,使用 `setTimeout`).如果你需要与浏览器互动,在 `componentDidMount()` 里执行你的工作,或者其他生命周期方法里.保持 `render()` 纯净使服务器渲染更实用并且让组件更容易被思考.
30 -
31 -
32 - ### getInitialState
33 -
34 - ```javascript
35 -object getInitialState()
36 -```
37 -
38 -当组件被挂载时调用一次.返回值会被用作为 `this.state` 的初始值.
39 -
40 -> 注意:
41 ->
42 -> 这个方法在从 `React.Component` 扩展的 ES6 `class` 组件里不可用。 更多的信息,请阅读我们关于[ES6 classes](/react/docs/reusable-components.html#es6-classes)的文档.
43 -
44 -
45 -### getDefaultProps
46 -
47 -```javascript
48 -object getDefaultProps()
49 -```
50 -
51 -在类被创建时调用一次并被缓存.在这个mapping里的值会被设置给 `this.props` 如果父组件没有指定对应的 prop (例如 使用一个 `in` 检查).
52 -
53 -这个方法在任何实例被创建之前调用,因此不能依赖于 `this.props`.另外,小心,任何被 `getDefaultProps()`返回的复杂对象会被跨实例共享,而不是被拷贝.
54 -
55 -
56 -### propTypes
57 -
58 -```javascript
59 -object propTypes
60 -```
61 -
62 - `propTypes` 对象允许你验证传递到你的组建的 props.更多关于 `propTypes` 的信息,见 [Reusable Components](/react/docs/reusable-components.html).
63 -
64 -
65 -### mixins
66 -
67 -```javascript
68 -array mixins
69 -```
70 -
71 - `mixins` 数组允许你用 mixins 来在多个组件间共享行为.更多关于 mixins 的信息,见 [Reusable Components](/react/docs/reusable-components.html).
72 -
73 -
74 -### statics
75 -
76 -```javascript
77 -object statics
78 -```
79 -
80 -`statics` 对象允许你定义可以在组件类上调用的静态方法.例如:
81 -
82 -```javascript
83 -var MyComponent = React.createClass({
84 - statics: {
85 - customMethod: function(foo) {
86 - return foo === 'bar';
87 - }
88 - },
89 - render: function() {
90 - }
91 -});
92 -
93 -MyComponent.customMethod('bar'); // true
94 -```
95 -
96 -在这个块里定义的方法是 _static_,意味着你可以在任何组件实例被创建前运行他们,并且这些方法没有对你组件的 props 或 state 的访问权.如果你在静态方法里检查props的值,把调用者作为参数传入props给静态函数.
97 -
98 -
99 -### displayName
100 -
101 -```javascript
102 -string displayName
103 -```
104 -
105 -`displayName` 字符串被用在调试信息.JSX 自动设置这个值;见 [JSX in Depth](/react/docs/jsx-in-depth.html#the-transform).
106 -
107 -
108 -## Lifecycle Methods
109 -
110 -多种方法在组件生命周期的特定点上被执行.
111 -
112 -
113 -### Mounting: componentWillMount
114 -
115 -```javascript
116 -void componentWillMount()
117 -```
118 -
119 -被调用一次,即在客户端也在服务端,在最初的渲染发生之前 立即被调用.如果你在这个方法里调用 `setState` , `render()` 将会看到更新的 state 并不论state的变化只执行一次.
120 -
121 -
122 -### Mounting: componentDidMount
123 -
124 -```javascript
125 -void componentDidMount()
126 -```
127 -
128 -被调用一次,只在客户端(不在服务端),在最初的渲染发生之后 立即被调用.在生命周期的这个点上,你可以访问任何对你的子级的refs (比如 访问底层的DOM表达).子组件的 `componentDidMount()` 方法在父组件之前被调用.
129 -
130 -如果你想与其他 JavaScript 框架整合,用 `setTimeout` 或 `setInterval` 设置timers,或者发送 AJAX 请求,执行这些操作在此方法中.
131 -
132 -
133 -### Updating: componentWillReceiveProps
134 -
135 -```javascript
136 -void componentWillReceiveProps(
137 - object nextProps
138 -)
139 -```
140 -
141 -当一个组件收到新的props时被调用.这个方法不会为最初的渲染调用.
142 -
143 -使用它作为响应 prop 转换的时机(在`render()` 被用 `this.setState()` 更新state调用 之前) .旧的 props 可以通过 `this.props` 访问. 在这个函数里调用 `this.setState()` 不会触发任何额外的渲染.
144 -
145 -```javascript
146 -componentWillReceiveProps: function(nextProps) {
147 - this.setState({
148 - likesIncreasing: nextProps.likeCount > this.props.likeCount
149 - });
150 -}
151 -```
152 -
153 -> 注意:
154 ->
155 -> 并没有类似的 `componentWillReceiveState` 方法. 一个即将到来的 prop 转变可能会导致一个 state 变化,但是反之不是. 如果你需要实现一个对 state 变化相应的操作,使用 `componentWillUpdate`.
156 -
157 -
158 -### Updating: shouldComponentUpdate
159 -
160 -```javascript
161 -boolean shouldComponentUpdate(
162 - object nextProps, object nextState
163 -)
164 -```
165 -
166 -当新的props或者state被收到,在渲染前被调用.这个方法不会在最初的渲染或者 `forceUpdate` 时被调用.
167 -
168 -使用此方法作为一个 `return false` 的时机,当你确定新的 props 和 state 的转换不需要组件更新时.
169 -
170 -```javascript
171 -shouldComponentUpdate: function(nextProps, nextState) {
172 - return nextProps.id !== this.props.id;
173 -}
174 -```
175 -
176 -如果 `shouldComponentUpdate` 返回false, `render()` 会在下次state变化前被完全跳过. 另外,`componentWillUpdate` 和 `componentDidUpdate` 将不会被调用.
177 -
178 -默认情况下, `shouldComponentUpdate` 总是返回 `true` 来阻止当 `state` 突变时的细微bug,但是如果你仔细的把 `state` 作为不变量对待并只从 `render()`里的 `props` 和 `state`读,你就可以用一个比较旧的props和state与他们的替换者的实现来重写 `shouldComponentUpdate`.
179 -
180 -如果性能是瓶颈,尤其是随着成百上千的组件,使用 `shouldComponentUpdate` 来加速你的app.
181 -
182 -
183 -### Updating: componentWillUpdate
184 -
185 -```javascript
186 -void componentWillUpdate(
187 - object nextProps, object nextState
188 -)
189 -```
190 -
191 -当新的props或者state被接受时,在渲染前被立即调用.这个方法不会被初始渲染调用.
192 -
193 -使用这个方法作为 在更新发生前执行一些准备 的时机.
194 -
195 -> Note:
196 ->
197 -> 你 *不能* 在这个方法里使用 `this.setState()` .如果你需要响应一个prop变化来更新state,使用 `componentWillReceiveProps` 来替代.
198 -
199 -
200 -### Updating: componentDidUpdate
201 -
202 -```javascript
203 -void componentDidUpdate(
204 - object prevProps, object prevState
205 -)
206 -```
207 -
208 -在组件的更新被刷新到DOM后立即被调用.这个方法不会被初始渲染调用.
209 -
210 -使用这个方法作为 当组件被更新后在DOM上操作 的时机.
211 -
212 -
213 -### Unmounting: componentWillUnmount
214 -
215 -```javascript
216 -void componentWillUnmount()
217 -```
218 -
219 -在组件被从DOM卸载 前 被立即调用.
220 -
221 -在这个方法里执行一些必要的清理操作,比如无效化 timers 或者清理任何被 `componentDidMount` 创建的DOM元素.
docs/docs/ref-04-tags-and-attributes.it-IT.md deleted
-117
@@ -1,117 +0,0 @@
1 ----
2 -id: tags-and-attributes-it-IT
3 -title: Tag e Attributi
4 -permalink: docs/tags-and-attributes-it-IT.html
5 -prev: component-specs-it-IT.html
6 -next: events-it-IT.html
7 ----
8 -
9 -## Tag Supportati
10 -
11 -React tenta di supportare tutti gli elementi comuni. Se hai bisogno di un elemento che non è elencato di seguito, per favore [apri una issue](https://github.com/facebook/react/issues/new).
12 -
13 -### Elementi HTML
14 -
15 -I seguenti elementi HTML sono supportati:
16 -
17 -```
18 -a abbr address area article aside audio b base bdi bdo big blockquote body br
19 -button canvas caption cite code col colgroup data datalist dd del details dfn
20 -dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5
21 -h6 head header hr html i iframe img input ins kbd keygen label legend li link
22 -main map mark menu menuitem meta meter nav noscript object ol optgroup option
23 -output p param picture pre progress q rp rt ruby s samp script section select
24 -small source span strong style sub summary sup table tbody td textarea tfoot th
25 -thead time title tr track u ul var video wbr
26 -```
27 -
28 -### Elementi SVG
29 -
30 -I seguenti elementi SVG sono supportati:
31 -
32 -```
33 -circle clipPath defs ellipse g line linearGradient mask path pattern polygon polyline
34 -radialGradient rect stop svg text tspan
35 -```
36 -
37 -Potresti trovare utile [react-art](https://github.com/facebook/react-art), una libreria di disegno per React che può disegnare su Canvas, SVG oppure VML (per IE8).
38 -
39 -
40 -## Attributi Supportati
41 -
42 -React supporta tutti gli attributi `data-*` e `aria-*`, oltre a ciascun attributo nelle liste seguenti.
43 -
44 -> Nota:
45 ->
46 -> Tutti gli attributi sono camel-cased, e gli attributi `class` e `for` sono resi come `className` e `htmlFor` rispettivamente, per adeguarsi alla specifica delle API del DOM.
47 -
48 -Per una lista di eventi, consulta gli [Eventi Supportati](/react/docs/events.html).
49 -
50 -### Attributi HTML
51 -
52 -Questi attributi standard sono supportati:
53 -
54 -```
55 -accept acceptCharset accessKey action allowFullScreen allowTransparency alt
56 -async autoComplete autoFocus autoPlay capture cellPadding cellSpacing challenge
57 -charSet checked cite classID className colSpan cols content contentEditable
58 -contextMenu controls coords crossOrigin data dateTime default defer dir
59 -disabled download draggable encType form formAction formEncType formMethod
60 -formNoValidate formTarget frameBorder headers height hidden high href hrefLang
61 -htmlFor httpEquiv icon id inputMode integrity is keyParams keyType kind label
62 -lang list loop low manifest marginHeight marginWidth max maxLength media
63 -mediaGroup method min minLength multiple muted name noValidate nonce open
64 -optimum pattern placeholder poster preload profile radioGroup readOnly rel
65 -required reversed role rowSpan rows sandbox scope scoped scrolling seamless
66 -selected shape size sizes span spellCheck src srcDoc srcLang srcSet start step
67 -style summary tabIndex target title type useMap value width wmode wrap
68 -```
69 -
70 -In aggiunta, i seguenti attributi non-standard sono supportati:
71 -
72 -- `autoCapitalize autoCorrect` per Mobile Safari.
73 -- `property` per i meta tag [Open Graph](http://ogp.me/).
74 -- `itemProp itemScope itemType itemRef itemID` per i [microdata HTML5](http://schema.org/docs/gs.html).
75 -- `unselectable` per Internet Explorer.
76 -- `results autoSave` per campi di input del tipo `search` in WebKit/Blink.
77 -
78 -Esiste anche l'attributo specifico di React `dangerouslySetInnerHTML` ([maggiori informazioni](/react/docs/special-non-dom-attributes.html)), usato per inserire direttamente stringhe di HTML in un componente.
79 -
80 -### Attributi SVG
81 -
82 -```
83 -accentHeight accumulate additive alignmentBaseline allowReorder alphabetic
84 -amplitude arabicForm ascent attributeName attributeType autoReverse azimuth
85 -baseFrequency baseProfile baselineShift bbox begin bias by calcMode capHeight
86 -clip clipPath clipPathUnits clipRule colorInterpolation
87 -colorInterpolationFilters colorProfile colorRendering contentScriptType
88 -contentStyleType cursor cx cy d decelerate descent diffuseConstant direction
89 -display divisor dominantBaseline dur dx dy edgeMode elevation enableBackground
90 -end exponent externalResourcesRequired fill fillOpacity fillRule filter
91 -filterRes filterUnits floodColor floodOpacity focusable fontFamily fontSize
92 -fontSizeAdjust fontStretch fontStyle fontVariant fontWeight format from fx fy
93 -g1 g2 glyphName glyphOrientationHorizontal glyphOrientationVertical glyphRef
94 -gradientTransform gradientUnits hanging horizAdvX horizOriginX ideographic
95 -imageRendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLength
96 -kerning keyPoints keySplines keyTimes lengthAdjust letterSpacing lightingColor
97 -limitingConeAngle local markerEnd markerHeight markerMid markerStart
98 -markerUnits markerWidth mask maskContentUnits maskUnits mathematical mode
99 -numOctaves offset opacity operator order orient orientation origin overflow
100 -overlinePosition overlineThickness paintOrder panose1 pathLength
101 -patternContentUnits patternTransform patternUnits pointerEvents points
102 -pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits
103 -r radius refX refY renderingIntent repeatCount repeatDur requiredExtensions
104 -requiredFeatures restart result rotate rx ry scale seed shapeRendering slope
105 -spacing specularConstant specularExponent speed spreadMethod startOffset
106 -stdDeviation stemh stemv stitchTiles stopColor stopOpacity
107 -strikethroughPosition strikethroughThickness string stroke strokeDasharray
108 -strokeDashoffset strokeLinecap strokeLinejoin strokeMiterlimit strokeOpacity
109 -strokeWidth surfaceScale systemLanguage tableValues targetX targetY textAnchor
110 -textDecoration textLength textRendering to transform u1 u2 underlinePosition
111 -underlineThickness unicode unicodeBidi unicodeRange unitsPerEm vAlphabetic
112 -vHanging vIdeographic vMathematical values vectorEffect version vertAdvY
113 -vertOriginX vertOriginY viewBox viewTarget visibility widths wordSpacing
114 -writingMode x x1 x2 xChannelSelector xHeight xlinkActuate xlinkArcrole
115 -xlinkHref xlinkRole xlinkShow xlinkTitle xlinkType xmlBase xmlLang xmlSpace
116 -y y1 y2 yChannelSelector z zoomAndPan
117 -```
docs/docs/ref-04-tags-and-attributes.ko-KR.md deleted
-117
@@ -1,117 +0,0 @@
1 ----
2 -id: tags-and-attributes-ko-KR
3 -title: 태그와 어트리뷰트
4 -permalink: docs/tags-and-attributes-ko-KR.html
5 -prev: component-specs-ko-KR.html
6 -next: events-ko-KR.html
7 ----
8 -
9 -## 지원되는 태그
10 -
11 -React는 모든 공통 엘리먼트를 지원하려 합니다. 필요한 엘리먼트가 목록에 없다면, [이슈로 등록](https://github.com/facebook/react/issues/new)해 주세요.
12 -
13 -### HTML 엘리먼트
14 -
15 -다음의 HTML 엘리먼트가 지원됩니다.
16 -
17 -```
18 -a abbr address area article aside audio b base bdi bdo big blockquote body br
19 -button canvas caption cite code col colgroup data datalist dd del details dfn
20 -dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5
21 -h6 head header hr html i iframe img input ins kbd keygen label legend li link
22 -main map mark menu menuitem meta meter nav noscript object ol optgroup option
23 -output p param picture pre progress q rp rt ruby s samp script section select
24 -small source span strong style sub summary sup table tbody td textarea tfoot th
25 -thead time title tr track u ul var video wbr
26 -```
27 -
28 -### SVG 엘리먼트
29 -
30 -다음의 SVG 엘리먼트가 지원됩니다.
31 -
32 -```
33 -circle clipPath defs ellipse g line linearGradient mask path pattern polygon polyline
34 -radialGradient rect stop svg text tspan
35 -```
36 -
37 -아마 Canvas, SVG, VML(IE8 전용)에 렌더할 때 쓰는 React의 드로잉 라이브러리인 [react-art](https://github.com/facebook/react-art)도 흥미 있으실 수 있습니다.
38 -
39 -
40 -## 지원되는 어트리뷰트
41 -
42 -React는 모든 `data-*`, `aria-*` 어트리뷰트와 밑에 있는 모든 어트리뷰트를 지원합니다.
43 -
44 -> 주의:
45 ->
46 -> 모든 어트리뷰트는 카멜케이스이고, `class` `for` 어트리뷰트는 각각 DOM API의 사양에 맞춰서 `className` `htmlFor` 가 됩니다.
47 -
48 -이벤트의 목록을 보시려면 [지원되는 이벤트](/react/docs/events-ko-KR.html)를 확인하세요.
49 -
50 -### HTML 어트리뷰트
51 -
52 -이런 표준 어트리뷰트가 지원됩니다.
53 -
54 -```
55 -accept acceptCharset accessKey action allowFullScreen allowTransparency alt
56 -async autoComplete autoFocus autoPlay capture cellPadding cellSpacing challenge
57 -charSet checked cite classID className colSpan cols content contentEditable
58 -contextMenu controls coords crossOrigin data dateTime default defer dir
59 -disabled download draggable encType form formAction formEncType formMethod
60 -formNoValidate formTarget frameBorder headers height hidden high href hrefLang
61 -htmlFor httpEquiv icon id inputMode integrity is keyParams keyType kind label
62 -lang list loop low manifest marginHeight marginWidth max maxLength media
63 -mediaGroup method min minLength multiple muted name noValidate nonce open
64 -optimum pattern placeholder poster preload profile radioGroup readOnly rel
65 -required reversed role rowSpan rows sandbox scope scoped scrolling seamless
66 -selected shape size sizes span spellCheck src srcDoc srcLang srcSet start step
67 -style summary tabIndex target title type useMap value width wmode wrap
68 -```
69 -
70 -덧붙여, 이런 비표준 어트리뷰트도 지원됩니다.
71 -
72 -- 모바일 사파리를 위한 `autoCapitalize autoCorrect`.
73 -- [오픈 그래프](http://ogp.me/) 메타 태그를 위한 `property`.
74 -- [HTML5 마이크로데이터](http://schema.org/docs/gs.html)를 위한 `itemProp itemScope itemType itemRef itemID`.
75 -- 인터넷 익스플로어를 위한 `unselectable`.
76 -- WebKit/Blink의 `search` 타입 input 필드를 위한 `results autoSave`
77 -
78 -컴포넌트에 직접 HTML 문자열을 넣을 때 사용하는, React 전용 어트리뷰트 `dangerouslySetInnerHTML`([자세한 정보는 여기](/react/docs/special-non-dom-attributes-ko-KR.html))도 있습니다.
79 -
80 -### SVG 어트리뷰트
81 -
82 -```
83 -accentHeight accumulate additive alignmentBaseline allowReorder alphabetic
84 -amplitude arabicForm ascent attributeName attributeType autoReverse azimuth
85 -baseFrequency baseProfile baselineShift bbox begin bias by calcMode capHeight
86 -clip clipPath clipPathUnits clipRule colorInterpolation
87 -colorInterpolationFilters colorProfile colorRendering contentScriptType
88 -contentStyleType cursor cx cy d decelerate descent diffuseConstant direction
89 -display divisor dominantBaseline dur dx dy edgeMode elevation enableBackground
90 -end exponent externalResourcesRequired fill fillOpacity fillRule filter
91 -filterRes filterUnits floodColor floodOpacity focusable fontFamily fontSize
92 -fontSizeAdjust fontStretch fontStyle fontVariant fontWeight format from fx fy
93 -g1 g2 glyphName glyphOrientationHorizontal glyphOrientationVertical glyphRef
94 -gradientTransform gradientUnits hanging horizAdvX horizOriginX ideographic
95 -imageRendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLength
96 -kerning keyPoints keySplines keyTimes lengthAdjust letterSpacing lightingColor
97 -limitingConeAngle local markerEnd markerHeight markerMid markerStart
98 -markerUnits markerWidth mask maskContentUnits maskUnits mathematical mode
99 -numOctaves offset opacity operator order orient orientation origin overflow
100 -overlinePosition overlineThickness paintOrder panose1 pathLength
101 -patternContentUnits patternTransform patternUnits pointerEvents points
102 -pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits
103 -r radius refX refY renderingIntent repeatCount repeatDur requiredExtensions
104 -requiredFeatures restart result rotate rx ry scale seed shapeRendering slope
105 -spacing specularConstant specularExponent speed spreadMethod startOffset
106 -stdDeviation stemh stemv stitchTiles stopColor stopOpacity
107 -strikethroughPosition strikethroughThickness string stroke strokeDasharray
108 -strokeDashoffset strokeLinecap strokeLinejoin strokeMiterlimit strokeOpacity
109 -strokeWidth surfaceScale systemLanguage tableValues targetX targetY textAnchor
110 -textDecoration textLength textRendering to transform u1 u2 underlinePosition
111 -underlineThickness unicode unicodeBidi unicodeRange unitsPerEm vAlphabetic
112 -vHanging vIdeographic vMathematical values vectorEffect version vertAdvY
113 -vertOriginX vertOriginY viewBox viewTarget visibility widths wordSpacing
114 -writingMode x x1 x2 xChannelSelector xHeight xlinkActuate xlinkArcrole
115 -xlinkHref xlinkRole xlinkShow xlinkTitle xlinkType xmlBase xmlLang xmlSpace
116 -y y1 y2 yChannelSelector z zoomAndPan
117 -```
docs/docs/ref-04-tags-and-attributes.md deleted
-131
@@ -1,131 +0,0 @@
1 ----
2 -id: tags-and-attributes
3 -title: Tags and Attributes
4 -permalink: docs/tags-and-attributes.html
5 -prev: component-specs.html
6 -next: events.html
7 ----
8 -
9 -## Supported Elements
10 -
11 -React attempts to support all common elements in both HTML and SVG. Any lower case tag in JSX will be rendered to an element with that tag. SVG elements must be contained within an `<svg>` element to work properly.
12 -
13 -### Using `React.DOM` Factory methods
14 -
15 -If you aren't using JSX and are using the `React.DOM.*` API to create elements, then you are slightly more limited and there is list of supported elements that will be available on that API.
16 -
17 -#### HTML Elements
18 -
19 -The following HTML elements are supported in `React.DOM.*`:
20 -
21 -```
22 -a abbr address area article aside audio b base bdi bdo big blockquote body br
23 -button canvas caption cite code col colgroup data datalist dd del details dfn
24 -dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5
25 -h6 head header hgroup hr html i iframe img input ins kbd keygen label legend li
26 -link main map mark menu menuitem meta meter nav noscript object ol optgroup
27 -option output p param picture pre progress q rp rt ruby s samp script section
28 -select small source span strong style sub summary sup table tbody td textarea
29 -tfoot th thead time title tr track u ul var video wbr
30 -```
31 -
32 -#### SVG elements
33 -
34 -The following SVG elements are supported in `React.DOM.*`:
35 -
36 -```
37 -circle clipPath defs ellipse g image line linearGradient mask path pattern
38 -polygon polyline radialGradient rect stop svg text tspan
39 -```
40 -
41 -You may also be interested in [react-art](https://github.com/facebook/react-art), a cross-browser drawing library for React.
42 -
43 -
44 -## Supported Attributes
45 -
46 -React supports all `data-*` and `aria-*` attributes as well as every attribute in the following lists.
47 -
48 -> Note:
49 ->
50 -> All attributes are camel-cased and the attributes `class` and `for` are `className` and `htmlFor`, respectively, to match the DOM API specification.
51 -
52 -For a list of events, see [Supported Events](/react/docs/events.html).
53 -
54 -### HTML Attributes
55 -
56 -These standard attributes are supported:
57 -
58 -```
59 -accept acceptCharset accessKey action allowFullScreen allowTransparency alt
60 -async autoComplete autoFocus autoPlay capture cellPadding cellSpacing challenge
61 -charSet checked cite classID className colSpan cols content contentEditable
62 -contextMenu controls coords crossOrigin data dateTime default defer dir
63 -disabled download draggable encType form formAction formEncType formMethod
64 -formNoValidate formTarget frameBorder headers height hidden high href hrefLang
65 -htmlFor httpEquiv icon id inputMode integrity is keyParams keyType kind label
66 -lang list loop low manifest marginHeight marginWidth max maxLength media
67 -mediaGroup method min minLength multiple muted name noValidate nonce open
68 -optimum pattern placeholder poster preload profile radioGroup readOnly rel
69 -required reversed role rowSpan rows sandbox scope scoped scrolling seamless
70 -selected shape size sizes span spellCheck src srcDoc srcLang srcSet start step
71 -style summary tabIndex target title type useMap value width wmode wrap
72 -```
73 -
74 -These RDFa attributes are supported (several RDFa attributes overlap with standard HTML attributes and thus are excluded from this list):
75 -
76 -```
77 -about datatype inlist prefix property resource typeof vocab
78 -```
79 -
80 -In addition, the following non-standard attributes are supported:
81 -
82 -- `autoCapitalize autoCorrect` for Mobile Safari.
83 -- `color` for `<link rel="mask-icon" />` in Safari.
84 -- `itemProp itemScope itemType itemRef itemID` for [HTML5 microdata](http://schema.org/docs/gs.html).
85 -- `security` for older versions of Internet Explorer.
86 -- `unselectable` for Internet Explorer.
87 -- `results autoSave` for WebKit/Blink input fields of type `search`.
88 -
89 -There is also 2 React-specific attributes:
90 -- `dangerouslySetInnerHTML` ([more here](/react/docs/special-non-dom-attributes.html)), used for directly inserting HTML strings into a component.
91 -- `suppressContentEditableWarning`, used to suppress the warning when using `contentEditable` and `children`.
92 -
93 -### SVG Attributes
94 -
95 -```
96 -accentHeight accumulate additive alignmentBaseline allowReorder alphabetic
97 -amplitude arabicForm ascent attributeName attributeType autoReverse azimuth
98 -baseFrequency baseProfile baselineShift bbox begin bias by calcMode capHeight
99 -clip clipPath clipPathUnits clipRule colorInterpolation
100 -colorInterpolationFilters colorProfile colorRendering contentScriptType
101 -contentStyleType cursor cx cy d decelerate descent diffuseConstant direction
102 -display divisor dominantBaseline dur dx dy edgeMode elevation enableBackground
103 -end exponent externalResourcesRequired fill fillOpacity fillRule filter
104 -filterRes filterUnits floodColor floodOpacity focusable fontFamily fontSize
105 -fontSizeAdjust fontStretch fontStyle fontVariant fontWeight format from fx fy
106 -g1 g2 glyphName glyphOrientationHorizontal glyphOrientationVertical glyphRef
107 -gradientTransform gradientUnits hanging horizAdvX horizOriginX ideographic
108 -imageRendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLength
109 -kerning keyPoints keySplines keyTimes lengthAdjust letterSpacing lightingColor
110 -limitingConeAngle local markerEnd markerHeight markerMid markerStart
111 -markerUnits markerWidth mask maskContentUnits maskUnits mathematical mode
112 -numOctaves offset opacity operator order orient orientation origin overflow
113 -overlinePosition overlineThickness paintOrder panose1 pathLength
114 -patternContentUnits patternTransform patternUnits pointerEvents points
115 -pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits
116 -r radius refX refY renderingIntent repeatCount repeatDur requiredExtensions
117 -requiredFeatures restart result rotate rx ry scale seed shapeRendering slope
118 -spacing specularConstant specularExponent speed spreadMethod startOffset
119 -stdDeviation stemh stemv stitchTiles stopColor stopOpacity
120 -strikethroughPosition strikethroughThickness string stroke strokeDasharray
121 -strokeDashoffset strokeLinecap strokeLinejoin strokeMiterlimit strokeOpacity
122 -strokeWidth surfaceScale systemLanguage tableValues targetX targetY textAnchor
123 -textDecoration textLength textRendering to transform u1 u2 underlinePosition
124 -underlineThickness unicode unicodeBidi unicodeRange unitsPerEm vAlphabetic
125 -vHanging vIdeographic vMathematical values vectorEffect version vertAdvY
126 -vertOriginX vertOriginY viewBox viewTarget visibility widths wordSpacing
127 -writingMode x x1 x2 xChannelSelector xHeight xlinkActuate xlinkArcrole
128 -xlinkHref xlinkRole xlinkShow xlinkTitle xlinkType xmlBase xmlLang xmlSpace
129 -y y1 y2 yChannelSelector z zoomAndPan
130 -
131 -```
docs/docs/ref-04-tags-and-attributes.zh-CN.md deleted
-124
@@ -1,124 +0,0 @@
1 ----
2 -id: tags-and-attributes-zh-CN
3 -title: Tags和属性
4 -permalink: docs/tags-and-attributes-zh-CN.html
5 -prev: component-specs-zh-CN.html
6 -next: events-zh-CN.html
7 ----
8 -
9 -## 支持的Tags
10 -
11 -React试着支持所有常见的元素.如果你需要一个没有列在这里的元素,请 [file an issue](https://github.com/facebook/react/issues/new).
12 -
13 -### HTML 元素
14 -
15 -下面的HTML是被支持的:
16 -
17 -```
18 -a abbr address area article aside audio b base bdi bdo big blockquote body br
19 -button canvas caption cite code col colgroup data datalist dd del details dfn
20 -dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5
21 -h6 head header hgroup hr html i iframe img input ins kbd keygen label legend li
22 -link main map mark menu menuitem meta meter nav noscript object ol optgroup
23 -option output p param picture pre progress q rp rt ruby s samp script section
24 -select small source span strong style sub summary sup table tbody td textarea
25 -tfoot th thead time title tr track u ul var video wbr
26 -```
27 -
28 -### SVG 元素
29 -
30 -下面的 SVG 元素是被支持的:
31 -
32 -```
33 -circle clipPath defs ellipse g image line linearGradient mask path pattern
34 -polygon polyline radialGradient rect stop svg text tspan
35 -```
36 -
37 -你也许对 [react-art](https://github.com/facebook/react-art)有兴趣,一个让React绘制Canvas, SVG, 或者 VML (for IE8) 的绘制库.
38 -
39 -
40 -## 支持的属性
41 -
42 -React支持所有的 `data-*` 和 `aria-*` 以及下列的属性.
43 -
44 -> 注意:
45 ->
46 -> 所有的属性都是 camel-cased ,`class` 和 `for` 分别是 `className` 和 `htmlFor`,来符合DOM API 规范.
47 -
48 -关于事件的列表,见 [Supported Events](/react/docs/events.html).
49 -
50 -### HTML 属性
51 -
52 -下面的标准属性是被支持的:
53 -
54 -```
55 -accept acceptCharset accessKey action allowFullScreen allowTransparency alt
56 -async autoComplete autoFocus autoPlay capture cellPadding cellSpacing challenge
57 -charSet checked cite classID className colSpan cols content contentEditable
58 -contextMenu controls coords crossOrigin data dateTime default defer dir
59 -disabled download draggable encType form formAction formEncType formMethod
60 -formNoValidate formTarget frameBorder headers height hidden high href hrefLang
61 -htmlFor httpEquiv icon id inputMode integrity is keyParams keyType kind label
62 -lang list loop low manifest marginHeight marginWidth max maxLength media
63 -mediaGroup method min minLength multiple muted name noValidate nonce open
64 -optimum pattern placeholder poster preload profile radioGroup readOnly rel
65 -required reversed role rowSpan rows sandbox scope scoped scrolling seamless
66 -selected shape size sizes span spellCheck src srcDoc srcLang srcSet start step
67 -style summary tabIndex target title type useMap value width wmode wrap
68 -```
69 -
70 -这些RDFa属性是被支持的 (许多RDFa属性和标准的HTML属性重叠,因此被从这个列表里去除):
71 -
72 -```
73 -about datatype inlist prefix property resource typeof vocab
74 -```
75 -
76 -另外,支持下面的非标准属性:
77 -
78 -- `autoCapitalize autoCorrect` for Mobile Safari.
79 -- `color` for `<link rel="mask-icon" />` in Safari.
80 -- `itemProp itemScope itemType itemRef itemID` for [HTML5 microdata](http://schema.org/docs/gs.html).
81 -- `security` 老的IE浏览器.
82 -- `unselectable` IE浏览器.
83 -- `results autoSave` for WebKit/Blink input fields of type `search`.
84 -
85 -同样有React规范的属性 `dangerouslySetInnerHTML` ([more here](/react/docs/special-non-dom-attributes.html)),用于直接插入HTML字符串到组件里.
86 -
87 -### SVG 属性
88 -
89 -```
90 -accentHeight accumulate additive alignmentBaseline allowReorder alphabetic
91 -amplitude arabicForm ascent attributeName attributeType autoReverse azimuth
92 -baseFrequency baseProfile baselineShift bbox begin bias by calcMode capHeight
93 -clip clipPath clipPathUnits clipRule colorInterpolation
94 -colorInterpolationFilters colorProfile colorRendering contentScriptType
95 -contentStyleType cursor cx cy d decelerate descent diffuseConstant direction
96 -display divisor dominantBaseline dur dx dy edgeMode elevation enableBackground
97 -end exponent externalResourcesRequired fill fillOpacity fillRule filter
98 -filterRes filterUnits floodColor floodOpacity focusable fontFamily fontSize
99 -fontSizeAdjust fontStretch fontStyle fontVariant fontWeight format from fx fy
100 -g1 g2 glyphName glyphOrientationHorizontal glyphOrientationVertical glyphRef
101 -gradientTransform gradientUnits hanging horizAdvX horizOriginX ideographic
102 -imageRendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLength
103 -kerning keyPoints keySplines keyTimes lengthAdjust letterSpacing lightingColor
104 -limitingConeAngle local markerEnd markerHeight markerMid markerStart
105 -markerUnits markerWidth mask maskContentUnits maskUnits mathematical mode
106 -numOctaves offset opacity operator order orient orientation origin overflow
107 -overlinePosition overlineThickness paintOrder panose1 pathLength
108 -patternContentUnits patternTransform patternUnits pointerEvents points
109 -pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits
110 -r radius refX refY renderingIntent repeatCount repeatDur requiredExtensions
111 -requiredFeatures restart result rotate rx ry scale seed shapeRendering slope
112 -spacing specularConstant specularExponent speed spreadMethod startOffset
113 -stdDeviation stemh stemv stitchTiles stopColor stopOpacity
114 -strikethroughPosition strikethroughThickness string stroke strokeDasharray
115 -strokeDashoffset strokeLinecap strokeLinejoin strokeMiterlimit strokeOpacity
116 -strokeWidth surfaceScale systemLanguage tableValues targetX targetY textAnchor
117 -textDecoration textLength textRendering to transform u1 u2 underlinePosition
118 -underlineThickness unicode unicodeBidi unicodeRange unitsPerEm vAlphabetic
119 -vHanging vIdeographic vMathematical values vectorEffect version vertAdvY
120 -vertOriginX vertOriginY viewBox viewTarget visibility widths wordSpacing
121 -writingMode x x1 x2 xChannelSelector xHeight xlinkActuate xlinkArcrole
122 -xlinkHref xlinkRole xlinkShow xlinkTitle xlinkType xmlBase xmlLang xmlSpace
123 -y y1 y2 yChannelSelector z zoomAndPan
124 -```
docs/docs/ref-05-events.it-IT.md deleted
-262
@@ -1,262 +0,0 @@
1 ----
2 -id: events-it-IT
3 -title: Sistema di Eventi
4 -permalink: docs/events-it-IT.html
5 -prev: tags-and-attributes-it-IT.html
6 -next: dom-differences-it-IT.html
7 ----
8 -
9 -## SyntheticEvent
10 -
11 -Ai tuoi gestori di eventi saranno passate istanze di `SyntheticEvent`, un involucro cross-browser attorno all'evento nativo del browser. Possiede la stessa interfaccia dell'evento nativo del browser, incluso `stopPropagation()` e `preventDefault()`, con l'eccezione che gli eventi funzionano in modo identico su tutti i browser.
12 -
13 -Se ti trovi nella situazione di avere bisogno dell'evento sottostante del browser per qualunque ragione, usa semplicemente l'attributo `nativeEvent` per ottenerlo. Ogni oggetto `SyntheticEvent` ha i seguenti attributi:
14 -
15 -```javascript
16 -boolean bubbles
17 -boolean cancelable
18 -DOMEventTarget currentTarget
19 -boolean defaultPrevented
20 -number eventPhase
21 -boolean isTrusted
22 -DOMEvent nativeEvent
23 -void preventDefault()
24 -boolean isDefaultPrevented()
25 -void stopPropagation()
26 -boolean isPropagationStopped()
27 -DOMEventTarget target
28 -number timeStamp
29 -string type
30 -```
31 -
32 -> Nota:
33 ->
34 -> A partire dalla v0.14, restituire `false` da un gestore di eventi non fermerà più la propagazione dell'evento. Invece, `e.stopPropagation()` o `e.preventDefault()` devono essere invocati manualmente, in maniera appropriata.
35 -
36 -## Riutilizzo degli eventi
37 -
38 -Gli oggetti `SyntheticEvent` sono gestiti come un pool. Ciò significa che ciascun oggetto `SyntheticEvent` sarà riutilizzato e tutte le sue proprietà annullate dopo che la callback dell'evento è stata invocata.
39 -Ciò avviene per ragioni di performance.
40 -Per questo motivo non potrai accedere all'evento in maniera asincrona.
41 -
42 -```javascript
43 -function onClick(event) {
44 - console.log(event); // => oggetto annullato.
45 - console.log(event.type); // => "click"
46 - var eventType = event.type; // => "click"
47 -
48 - setTimeout(function() {
49 - console.log(event.type); // => null
50 - console.log(eventType); // => "click"
51 - }, 0);
52 -
53 - this.setState({clickEvent: event}); // Non funzionerà. this.state.clickEvent conterrà soltanto valori null.
54 - this.setState({eventType: event.type}); // Puoi sempre esportare le singole proprietà dell'evento.
55 -}
56 -```
57 -
58 -> Nota:
59 ->
60 -> Se vuoi accedere alle proprietà dell'evento in maniera asincrona, devi invocare `event.persist()` sull'evento, che rimuoverà l'evento sintetico dal pool e permetterà ai riferimenti all'evento di essere mantenuti nel codice dell'utente.
61 -
62 -## Eventi Supportati
63 -
64 -React normalizza gli eventi in modo che abbiano proprietà consistenti su browser differenti.
65 -
66 -I gestori di eventi seguenti sono scatenati da un evento nella fase di propagazione. Per registrare un gestore di eventi per la fase di cattura, aggiungi il suffisso `Capture` al nome dell'evento; ad esempio, anziché usare `onClick`, useresti `onClickCapture` per gestire l'evento click nella fase di cattura.
67 -
68 -
69 -### Eventi della Clipboard
70 -
71 -Nomi degli eventi:
72 -
73 -```
74 -onCopy onCut onPaste
75 -```
76 -
77 -Proprietà:
78 -
79 -```javascript
80 -DOMDataTransfer clipboardData
81 -```
82 -
83 -
84 -### Eventi di Composizione
85 -
86 -Nomi degli eventi:
87 -
88 -```
89 -onCompositionEnd onCompositionStart onCompositionUpdate
90 -```
91 -
92 -Proprietà:
93 -
94 -```javascript
95 -string data
96 -
97 -```
98 -
99 -
100 -### Eventi di Tastiera
101 -
102 -Nomi degli eventi:
103 -
104 -```
105 -onKeyDown onKeyPress onKeyUp
106 -```
107 -
108 -Proprietà:
109 -
110 -```javascript
111 -boolean altKey
112 -number charCode
113 -boolean ctrlKey
114 -boolean getModifierState(key)
115 -string key
116 -number keyCode
117 -string locale
118 -number location
119 -boolean metaKey
120 -boolean repeat
121 -boolean shiftKey
122 -number which
123 -```
124 -
125 -
126 -### Eventi del Focus
127 -
128 -Nomi degli eventi:
129 -
130 -```
131 -onFocus onBlur
132 -```
133 -
134 -Proprietà:
135 -
136 -```javascript
137 -DOMEventTarget relatedTarget
138 -```
139 -
140 -
141 -### Eventi dei Moduli
142 -
143 -Nomi degli eventi:
144 -
145 -```
146 -onChange onInput onSubmit
147 -```
148 -
149 -Per maggiori informazioni sull'evento onChange, leggi [Moduli](/react/docs/forms.html).
150 -
151 -
152 -### Eventi del Mouse
153 -
154 -Nomi degli eventi:
155 -
156 -```
157 -onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
158 -onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
159 -onMouseMove onMouseOut onMouseOver onMouseUp
160 -```
161 -
162 -Gli eventi `onMouseEnter` e `onMouseLeave` vengono propagati dal componente che viene abbandonato a quello in cui viene effettuato l'ingresso anziché seguire la propagazione ordinaria, e non posseggono una fase di cattura.
163 -
164 -Proprietà:
165 -
166 -```javascript
167 -boolean altKey
168 -number button
169 -number buttons
170 -number clientX
171 -number clientY
172 -boolean ctrlKey
173 -boolean getModifierState(key)
174 -boolean metaKey
175 -number pageX
176 -number pageY
177 -DOMEventTarget relatedTarget
178 -number screenX
179 -number screenY
180 -boolean shiftKey
181 -```
182 -
183 -
184 -### Eventi di Selezione
185 -
186 -Nomi degli eventi:
187 -
188 -```
189 -onSelect
190 -```
191 -
192 -
193 -### Eventi del Tocco
194 -
195 -Nomi degli eventi:
196 -
197 -```
198 -onTouchCancel onTouchEnd onTouchMove onTouchStart
199 -```
200 -
201 -Proprietà:
202 -
203 -```javascript
204 -boolean altKey
205 -DOMTouchList changedTouches
206 -boolean ctrlKey
207 -boolean getModifierState(key)
208 -boolean metaKey
209 -boolean shiftKey
210 -DOMTouchList targetTouches
211 -DOMTouchList touches
212 -```
213 -
214 -
215 -### Eventi UI
216 -
217 -Nomi degli eventi:
218 -
219 -```
220 -onScroll
221 -```
222 -
223 -Proprietà:
224 -
225 -```javascript
226 -number detail
227 -DOMAbstractView view
228 -```
229 -
230 -
231 -### Eventi della Rotellina
232 -
233 -Nomi degli eventi:
234 -
235 -```
236 -onWheel
237 -```
238 -
239 -Proprietà:
240 -
241 -```javascript
242 -number deltaMode
243 -number deltaX
244 -number deltaY
245 -number deltaZ
246 -```
247 -
248 -### Eventi dei Media
249 -
250 -Nomi degli eventi:
251 -
252 -```
253 -onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend onTimeUpdate onVolumeChange onWaiting
254 -```
255 -
256 -### Eventi delle Immagini
257 -
258 -Nomi degli eventi:
259 -
260 -```
261 -onLoad onError
262 -```
docs/docs/ref-05-events.ko-KR.md deleted
-263
@@ -1,263 +0,0 @@
1 ----
2 -id: events-ko-KR
3 -title: 이벤트 시스템
4 -permalink: docs/events-ko-KR.html
5 -prev: tags-and-attributes-ko-KR.html
6 -next: dom-differences-ko-KR.html
7 ----
8 -
9 -## 통합적인(Synthetic) 이벤트
10 -
11 -이벤트 핸들러는 브라우저의 네이티브 이벤트의 크로스 브라우저 래퍼(wrapper)인`SyntheticEvent`의 인스턴스에 전달됩니다. 모든 브라우저에서 동작한다는 점을 제외하면, `SyntheticEvent`는 `stopPropagation()`나 `preventDefault()`를 포함해, 브라우저의 네이티브 이벤트와 같은 인터페이스를 가지고 있습니다.
12 -
13 -어떤 이유로 기본 브라우저 이벤트가 필요하다면, 그냥 `nativeEvent`를 사용해 할 수 있습니다. 모든 `SyntheticEvent` 객체는 이런 어트리뷰트를 가집니다.
14 -
15 -```javascript
16 -boolean bubbles
17 -boolean cancelable
18 -DOMEventTarget currentTarget
19 -boolean defaultPrevented
20 -number eventPhase
21 -boolean isTrusted
22 -DOMEvent nativeEvent
23 -void preventDefault()
24 -boolean isDefaultPrevented()
25 -void stopPropagation()
26 -boolean isPropagationStopped()
27 -DOMEventTarget target
28 -number timeStamp
29 -string type
30 -```
31 -
32 -> 주의:
33 ->
34 -> v0.14 시점에서, 이벤트 핸들러에서 `false` 를 리턴하는 것은 더 이상 이벤트의 전달(propagation)을 멈추지 않습니다. 대신, `e.stopPropagation()`나 `e.preventDefault()`로 적절히 수동으로 트리거해야 합니다.
35 -
36 -## 이벤트 풀링
37 -
38 -`SyntheticEvent`는 풀링됩니다. 이는 `SyntheticEvent` 객체가 재사용될 것이며 이벤트 콜백이 호출된 후 모든 프로퍼티가 null 값을 갖게 된다는 것을 뜻합니다.
39 -이는 성능을 위한 동작입니다.
40 -이 때문에, 비동기 방식으로는 이벤트에 접근할 수 없습니다.
41 -
42 -```javascript
43 -function onClick(event) {
44 - console.log(event); // => null이 된 객체.
45 - console.log(event.type); // => "click"
46 - var eventType = event.type; // => "click"
47 -
48 - setTimeout(function() {
49 - console.log(event.type); // => null
50 - console.log(eventType); // => "click"
51 - }, 0);
52 -
53 - this.setState({clickEvent: event}); // 작동하지 않습니다. this.state.clickEvent 는 null값들만을 갖고 있습니다.
54 - this.setState({eventType: event.type}); // 여전히 이벤트 프로퍼티를 내보낼 수 있습니다.
55 -}
56 -```
57 -
58 -> 주의:
59 ->
60 -> 만약 비동기 방식으로 이벤트 프로퍼티에 접근하길 원한다면, 이벤트의 `event.persist()`를 호출해야 합니다, 이는 풀로부터 통합적인 이벤트를 제거하고 이벤트에 대한 참조는 사용자의 코드에 의해 유지 될 수 있도록 합니다.
61 -
62 -## 지원되는 이벤트
63 -
64 -React는 다른 브라우저에서 일관된 특성을 가지도록 이벤트를 일반화합니다.
65 -
66 -밑에 있는 이벤트 핸들러들은 일으키는(bubbling) 단계에서 이벤트를 트리거합니다. 이벤트 핸들러를 캡처 단계로 등록하려면, 이벤트 이름에 `Capture`를 붙이면 됩니다. 예를 들어, 캡처 단계의 클릭 이벤트를 다루려면 `onClick`를 사용하는 대신에 `onClickCapture`를 사용해야 합니다.
67 -
68 -
69 -### 클립보드 이벤트
70 -
71 -이벤트 이름:
72 -
73 -```
74 -onCopy onCut onPaste
75 -```
76 -
77 -프로퍼티:
78 -
79 -```javascript
80 -DOMDataTransfer clipboardData
81 -```
82 -
83 -
84 -### Composition Events
85 -
86 -이벤트 이름:
87 -
88 -```
89 -onCompositionEnd onCompositionStart onCompositionUpdate
90 -```
91 -
92 -프로퍼티:
93 -
94 -```javascript
95 -string data
96 -
97 -```
98 -
99 -
100 -### 키보드 이벤트
101 -
102 -이벤트 이름:
103 -
104 -```
105 -onKeyDown onKeyPress onKeyUp
106 -```
107 -
108 -프로퍼티:
109 -
110 -```javascript
111 -boolean altKey
112 -number charCode
113 -boolean ctrlKey
114 -boolean getModifierState(key)
115 -string key
116 -number keyCode
117 -string locale
118 -number location
119 -boolean metaKey
120 -boolean repeat
121 -boolean shiftKey
122 -number which
123 -```
124 -
125 -
126 -### 포커스 이벤트
127 -
128 -이벤트 이름:
129 -
130 -```
131 -onFocus onBlur
132 -```
133 -
134 -프로퍼티:
135 -
136 -```javascript
137 -DOMEventTarget relatedTarget
138 -```
139 -
140 -이 포커스 이벤트는 폼 엘리먼트뿐만 아니라 모든 React DOM 엘리먼트에서 작동합니다.
141 -
142 -### 폼 이벤트
143 -
144 -이벤트 이름:
145 -
146 -```
147 -onChange onInput onSubmit
148 -```
149 -
150 -onChange 이벤트에 대한 더 자세한 정보는 [폼](/react/docs/forms-ko-KR.html)에서 확인하세요.
151 -
152 -
153 -### 마우스 이벤트
154 -
155 -이벤트 이름:
156 -
157 -```
158 -onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
159 -onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
160 -onMouseMove onMouseOut onMouseOver onMouseUp
161 -```
162 -
163 -`onMouseEnter`와 `onMouseLeave` 이벤트는 평범하게 일어나는(bubbling) 대신 입력된 엘리먼트에 남겨지도록 엘리먼트에서 전달되고 캡쳐 단계가 없습니다.
164 -
165 -프로퍼티:
166 -
167 -```javascript
168 -boolean altKey
169 -number button
170 -number buttons
171 -number clientX
172 -number clientY
173 -boolean ctrlKey
174 -boolean getModifierState(key)
175 -boolean metaKey
176 -number pageX
177 -number pageY
178 -DOMEventTarget relatedTarget
179 -number screenX
180 -number screenY
181 -boolean shiftKey
182 -```
183 -
184 -
185 -### 셀렉션 이벤트
186 -
187 -이벤트 이름:
188 -
189 -```
190 -onSelect
191 -```
192 -
193 -
194 -### 터치 이벤트
195 -
196 -이벤트 이름:
197 -
198 -```
199 -onTouchCancel onTouchEnd onTouchMove onTouchStart
200 -```
201 -
202 -프로퍼티:
203 -
204 -```javascript
205 -boolean altKey
206 -DOMTouchList changedTouches
207 -boolean ctrlKey
208 -boolean getModifierState(key)
209 -boolean metaKey
210 -boolean shiftKey
211 -DOMTouchList targetTouches
212 -DOMTouchList touches
213 -```
214 -
215 -
216 -### UI 이벤트
217 -
218 -이벤트 이름:
219 -
220 -```
221 -onScroll
222 -```
223 -
224 -프로퍼티:
225 -
226 -```javascript
227 -number detail
228 -DOMAbstractView view
229 -```
230 -
231 -
232 -### 휠 이벤트
233 -
234 -이벤트 이름:
235 -
236 -```
237 -onWheel
238 -```
239 -
240 -프로퍼티:
241 -
242 -```javascript
243 -number deltaMode
244 -number deltaX
245 -number deltaY
246 -number deltaZ
247 -```
248 -
249 -### 미디어 이벤트
250 -
251 -이벤트 이름:
252 -
253 -```
254 -onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend onTimeUpdate onVolumeChange onWaiting
255 -```
256 -
257 -### 이미지 이벤트
258 -
259 -이벤트 이름:
260 -
261 -```
262 -onLoad onError
263 -```
docs/docs/ref-05-events.zh-CN.md deleted
-300
@@ -1,300 +0,0 @@
1 ----
2 -id: events-zh-CN
3 -title: 事件系统
4 -permalink: docs/events-zh-CN.html
5 -prev: tags-and-attributes-zh-CN.html
6 -next: dom-differences-zh-CN.html
7 ----
8 -
9 -## 合成事件
10 -
11 -事件处理程序通过 `合成事件`(`SyntheticEvent`)的实例传递,`SyntheticEvent` 是浏览器原生事件跨浏览器的封装。`SyntheticEvent` 和浏览器原生事件一样有 `stopPropagation()`、`preventDefault()` 接口,而且这些接口夸浏览器兼容。
12 -
13 -如果出于某些原因想使用浏览器原生事件,可以使用 `nativeEvent` 属性获取。每个和成事件(`SyntheticEvent`)对象都有以下属性:
14 -
15 -```javascript
16 -boolean bubbles
17 -boolean cancelable
18 -DOMEventTarget currentTarget
19 -boolean defaultPrevented
20 -number eventPhase
21 -boolean isTrusted
22 -DOMEvent nativeEvent
23 -void preventDefault()
24 -boolean isDefaultPrevented()
25 -void stopPropagation()
26 -boolean isPropagationStopped()
27 -DOMEventTarget target
28 -number timeStamp
29 -string type
30 -```
31 -
32 -> 注意:
33 ->
34 -> React v0.14 中,事件处理程序返回 `false` 不再停止事件传播,取而代之,应该根据需要手动触发 `e.stopPropagation()` 或 `e.preventDefault()`。
35 -
36 -## 事件池
37 -
38 -`SyntheticEvent` 是池化的. 这意味着 `SyntheticEvent` 对象将会被重用并且所有的属性都会在事件回调被调用后被 nullified.
39 -这是因为性能的原因.
40 -因此,你不能异步的访问事件.
41 -
42 -```javascript
43 -function onClick(event) {
44 - console.log(event); // => nullified object.
45 - console.log(event.type); // => "click"
46 - var eventType = event.type; // => "click"
47 -
48 - setTimeout(function() {
49 - console.log(event.type); // => null
50 - console.log(eventType); // => "click"
51 - }, 0);
52 -
53 - this.setState({clickEvent: event}); // Won't work. this.state.clickEvent will only contain null values.
54 - this.setState({eventType: event.type}); // You can still export event properties.
55 -}
56 -```
57 -
58 -> 注意:
59 ->
60 -> 如果你想异步访问事件属性,你应该在事件上调用 `event.persist()` ,这会从池中移除合成事件并允许对事件的引用被用会保留.
61 -
62 -## 支持的事件
63 -
64 -React 将事件统一化,使事件在不同浏览器上有一致的属性.
65 -
66 -下面的事件处理程序在事件冒泡阶段被触发。如果要注册事件捕获处理程序,应该使用 `Capture` 事件,例如使用 `onClickCapture` 处理点击事件的捕获阶段,而不是 `onClick`。
67 -
68 -
69 -### 剪贴板事件
70 -
71 -事件名称:
72 -
73 -```
74 -onCopy onCut onPaste
75 -```
76 -
77 -属性:
78 -
79 -```javascript
80 -DOMDataTransfer clipboardData
81 -```
82 -
83 -
84 -### Composition 事件
85 -
86 -事件名称:
87 -
88 -```
89 -onCompositionEnd onCompositionStart onCompositionUpdate
90 -```
91 -
92 -属性:
93 -
94 -```javascript
95 -string data
96 -
97 -```
98 -
99 -
100 -### 键盘事件
101 -
102 -事件名称:
103 -
104 -```
105 -onKeyDown onKeyPress onKeyUp
106 -```
107 -
108 -属性:
109 -
110 -```javascript
111 -boolean altKey
112 -number charCode
113 -boolean ctrlKey
114 -boolean getModifierState(key)
115 -string key
116 -number keyCode
117 -string locale
118 -number location
119 -boolean metaKey
120 -boolean repeat
121 -boolean shiftKey
122 -number which
123 -```
124 -
125 -
126 -### 焦点事件
127 -
128 -事件名称
129 -
130 -```
131 -onFocus onBlur
132 -```
133 -
134 -属性:
135 -
136 -```javascript
137 -DOMEventTarget relatedTarget
138 -```
139 -
140 -焦点事件在所有的React DOM上工作,不仅仅是表单元素.
141 -
142 -
143 -### 表单事件
144 -
145 -事件名称:
146 -
147 -```
148 -onChange onInput onSubmit
149 -```
150 -
151 -关于 `onChange` 事件的更多信息,参见 [表单组件](/react/docs/forms-zh-CN.html)。
152 -
153 -
154 -### 鼠标事件
155 -
156 -事件名称:
157 -
158 -```
159 -onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
160 -onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
161 -onMouseMove onMouseOut onMouseOver onMouseUp
162 -```
163 -
164 -`onMouseEnter` 和 `onMouseLeave` 事件从离开的元素传播到进入的元素,代替冒泡排序并且没有捕获阶段.
165 -
166 -属性:
167 -
168 -```javascript
169 -boolean altKey
170 -number button
171 -number buttons
172 -number clientX
173 -number clientY
174 -boolean ctrlKey
175 -boolean getModifierState(key)
176 -boolean metaKey
177 -number pageX
178 -number pageY
179 -DOMEventTarget relatedTarget
180 -number screenX
181 -number screenY
182 -boolean shiftKey
183 -```
184 -
185 -
186 -### Selection Events
187 -
188 -事件名称:
189 -
190 -```
191 -onSelect
192 -```
193 -
194 -
195 -### 触控事件
196 -
197 -事件名称:
198 -
199 -```
200 -onTouchCancel onTouchEnd onTouchMove onTouchStart
201 -```
202 -
203 -属性:
204 -
205 -```javascript
206 -boolean altKey
207 -DOMTouchList changedTouches
208 -boolean ctrlKey
209 -boolean getModifierState(key)
210 -boolean metaKey
211 -boolean shiftKey
212 -DOMTouchList targetTouches
213 -DOMTouchList touches
214 -```
215 -
216 -
217 -### 用户界面事件
218 -
219 -事件名称:
220 -
221 -```
222 -onScroll
223 -```
224 -
225 -属性:
226 -
227 -```javascript
228 -number detail
229 -DOMAbstractView view
230 -```
231 -
232 -
233 -### 滚轮事件
234 -
235 -事件名称:
236 -
237 -```
238 -onWheel
239 -```
240 -
241 -属性:
242 -
243 -```javascript
244 -number deltaMode
245 -number deltaX
246 -number deltaY
247 -number deltaZ
248 -```
249 -
250 -
251 -### 媒体事件
252 -
253 -事件名称:
254 -
255 -```
256 -onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend onTimeUpdate onVolumeChange onWaiting
257 -```
258 -
259 -
260 -### 图片事件
261 -
262 -事件名称:
263 -
264 -```
265 -onLoad onError
266 -```
267 -
268 -
269 -### 动画事件
270 -
271 -事件名称:
272 -
273 -```
274 -onAnimationStart onAnimationEnd onAnimationIteration
275 -```
276 -
277 -属性:
278 -
279 -```javascript
280 -string animationName
281 -string pseudoElement
282 -float elapsedTime
283 -```
284 -
285 -
286 -### Transition Events
287 -
288 -事件名称:
289 -
290 -```
291 -onTransitionEnd
292 -```
293 -
294 -属性:
295 -
296 -```javascript
297 -string propertyName
298 -string pseudoElement
299 -float elapsedTime
300 -```
docs/docs/ref-06-dom-differences.it-IT.md deleted
-15
@@ -1,15 +0,0 @@
1 ----
2 -id: dom-differences-it-IT
3 -title: Differenze del DOM
4 -permalink: docs/dom-differences-it-IT.html
5 -prev: events-it-IT.html
6 -next: special-non-dom-attributes-it-IT.html
7 ----
8 -
9 -React ha implementato eventi indipendenti dal browser e un sistema DOM per ragioni di prestazioni e compatibilità cross-browser. Abbiamo colto l'occasione di dare una ripulita ad alcuni aspetti trascurati nelle implementazioni del DOM nei browser.
10 -
11 -* Tutte le proprietà e attributi del DOM (incluso i gestori di eventi) dovrebbero essere camelCased per essere consistenti con lo stile standard JavaScript. Abbiamo intenzionalmente deviato dalla specifica perché la specifica stessa è inconsistente. **Tuttavia**, gli attributi `data-*` e `aria-*` [sono conformi alle specifiche](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#data-*) e dovrebbero essere soltanto in minuscolo.
12 -* L'attributo `style` accetta un oggetto JavaScript con proprietà camelCased anziché una stringa CSS. Questo è consistente con la proprietà DOM `style` di JavaScript, è più efficiente, e previene falle nella sicurezza XSS.
13 -* Tutti gli oggetti evento sono conformi con la specifica W3C, e tutti gli eventi (incluso il submit) si propagano correttamente secondo la specifica W3C. Consulta il [Sistema degli Eventi](/react/docs/events.html) per maggiori dettagli.
14 -* L'evento `onChange` si comporta come ti aspetteresti: questo evento è emesso ogni qualvolta il valore di un campo di un modulo cambia anziché, in maniera inconsistente, quando il campo perde il focus. Abbiamo intenzionalmente deviato dal comportamento corrente dei browser perché `onChange` è un nome incorretto per questo comportamento e React dipende dall'emissione di questo evento in tempo reale in risposta all'input dell'utente. Leggi [Moduli](/react/docs/forms.html) per maggiori dettagli.
15 -* Attributi dei campi di modulo come `value` e `checked`, oppure `textarea`. [Maggiori dettagli](/react/docs/forms.html).
docs/docs/ref-06-dom-differences.ko-KR.md deleted
-17
@@ -1,17 +0,0 @@
1 ----
2 -id: dom-differences-ko-KR
3 -title: DOM과의 차이점
4 -permalink: docs/dom-differences-ko-KR.html
5 -prev: events-ko-KR.html
6 -next: special-non-dom-attributes-ko-KR.html
7 ----
8 -
9 -React는 성능과 크로스 브라우저 호환성을 이유로 브라우저에 독립적인 이벤트와 DOM 시스템으로 구현되었습니다. 브라우저 DOM 구현의 일관성없는 부분들을 정리할 기회를 가졌습니다.
10 -
11 -* 모든 DOM 프로퍼티와 어트리뷰트는 (이벤트 핸들러를 포함해) 표준 JavaScript 스타일과 일치하도록 카멜케이스를 사용해야 합니다. **하지만**, `data-*` 와 `aria-*` 어트리뷰트는 [사양을 준수해](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#data-*) 소문자만 사용해야 합니다.
12 -* `style` 어트리뷰트는 CSS 문자열 대신에 카멜케이스로 된 프로퍼티를 가지는 JavaScript 객체를 받습니다. 이는 DOM `style` JavaScript 프로퍼티와 일치하면서도 좀 더 효율적이며, XSS 보안 취약점을 예방할 수 있습니다.
13 -* 모든 이벤트 객체는 W3C 사양을 준수하고, 모든 이벤트(submit을 포함해)는 W3C 사양에 따라 일으킵(bubble)니다. 좀 더 자세한 정보는 [이벤트 시스템](/react/docs/events-ko-KR.html)을 보세요.
14 -* `onChange` 이벤트는 기대대로 동작합니다. 이 이벤트는 일관성없이 blur시점에서 발생하지 않고 폼 필드가 변경될 때만 발생합니다.[^1] 우리는 의도적으로 기존 브라우저 동작을 차단했습니다. `onChange`는 이름과 실제 동작이 다르고, React는 실시간으로 사용자 입력에 반응할 때 이 이벤트에 의존하기 때문입니다. 더 자세한 정보는 [폼](/react/docs/forms-ko-KR.html)을 보세요.
15 -* `value`와 `checked` 폼 input 어트리뷰트, `textarea`. [자세히 보기](/react/docs/forms-ko-KR.html).
16 -
17 -[^1]: **역주**: 일관성 없다는 표현에 대해 부연 설명하자면, 네이티브의 onChange는 변경뿐만 아니라 blur에서도 반응합니다.
docs/docs/ref-06-dom-differences.md deleted
-16
@@ -1,16 +0,0 @@
1 ----
2 -id: dom-differences
3 -title: DOM Differences
4 -permalink: docs/dom-differences.html
5 -prev: events.html
6 -next: special-non-dom-attributes.html
7 ----
8 -
9 -React has implemented a browser-independent events and DOM system for performance and cross-browser compatibility reasons. We took the opportunity to clean up a few rough edges in browser DOM implementations.
10 -
11 -* All DOM properties and attributes (including event handlers) should be camelCased to be consistent with standard JavaScript style. We intentionally break with the spec here since the spec is inconsistent. **However**, `data-*` and `aria-*` attributes [conform to the specs](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#data-*) and should be lower-cased only.
12 -* The `style` attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM `style` JavaScript property, is more efficient, and prevents XSS security holes.
13 -* Since `class` and `for` are reserved words in JavaScript, the JSX elements for built-in [DOM nodes](http://javascript.info/tutorial/dom-nodes) should use the attribute names `className` and `htmlFor` respectively, (eg. `<div className="foo" />` ). Custom elements should use `class` and `for` directly (eg. `<my-tag class="foo" />` ).
14 -* All event objects conform to the W3C spec, and all events (including submit) bubble correctly per the W3C spec. See [Event System](/react/docs/events.html) for more details.
15 -* The `onChange` event behaves as you would expect it to: whenever a form field is changed this event is fired rather than inconsistently on blur. We intentionally break from existing browser behavior because `onChange` is a misnomer for its behavior and React relies on this event to react to user input in real time. See [Forms](/react/docs/forms.html) for more details.
16 -* Form input attributes such as `value` and `checked`, as well as `textarea`. [More here](/react/docs/forms.html).
docs/docs/ref-06-dom-differences.zh-CN.md deleted
-16
@@ -1,16 +0,0 @@
1 ----
2 -id: dom-differences-zh-CN
3 -title: DOM 的不同之处
4 -permalink: docs/dom-differences-zh-CN.html
5 -prev: events-zh-CN.html
6 -next: special-non-dom-attributes-zh-CN.html
7 ----
8 -
9 -React 实现了一个浏览器无关的 事件和DOM 系统,原因是为了性能和跨浏览器的兼容性.我们利用这个机会来清理了一些浏览器DOM实现的一些粗糙边缘.
10 -
11 -* 所有的 DOM properties 和 attributes (包括事件处理器) 都应该 camelCased 来保持和标准的 JavaScript 风格一致.我们在这里故意打破了这个规范是因为规范是不一致的. **然而**,`data-*` 和 `aria-*` attributes [conform to the specs](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#data-*) 应该只 lower-cased.
12 -* `style` attribute 接受 camelCased properties 的JavaScript对象 而不是一个CSS字符串. 这保持了和 DOM `style` JavaScript property 的一致,更有效率,而且阻止了XSS安全漏洞.
13 -* 因为 `class` 和 `for` 是 JavaScript的保留字,内建[DOM nodes](http://javascript.info/tutorial/dom-nodes)的JSX元素 应该分别使用 attribute名`className` 和 `htmlFor` ,(比如 `<div className="foo" />`).自定义元素应该直接使用 `class` 和 `for` (例如. `<my-tag class="foo" />` ).
14 -* 所有事件对象遵循 W3C 规范,所有事件(包括提交)正确按W3C规范冒泡.详见[Event System](/react/docs/events.html).
15 -* `onChange` 事件表现的像你期望的那样:不论何时一个表单域改变了这个事件就会激发,而不是模糊的不一致.我们故意打破了已有浏览器的行为,因为 `onChange` 对于他的行为来说用词不当,并且React依赖于这个事件来实时响应用户的输入.详见[Forms](/react/docs/forms.html).
16 -* 表单 输入attributes 类似 `value` 和 `checked`,就像`textarea`一样[More here](/react/docs/forms.html).
docs/docs/ref-07-special-non-dom-attributes.it-IT.md deleted
-13
@@ -1,13 +0,0 @@
1 ----
2 -id: special-non-dom-attributes-it-IT
3 -title: Attributi Speciali Non-DOM
4 -permalink: docs/special-non-dom-attributes-it-IT.html
5 -prev: dom-differences-it-IT.html
6 -next: reconciliation-it-IT.html
7 ----
8 -
9 -Oltre alle [Differenze del DOM](/react/docs/dom-differences.html), React offre alcuni attributi che semplicemente non esistono nel DOM.
10 -
11 -- `key`: un identificatore univoco opzionale. Quando il tuo componente viene riordinato durante i passaggi di `render`, potrebbe essere distrutto e ricreato in base all'algoritmo di calcolo delle differenze. Assegnargli una chiave che persiste assicura che il componente venga preservato. Scopri maggiori dettagli [qui](/react/docs/multiple-components.html#dynamic-children).
12 -- `ref`: leggi [qui](/react/docs/more-about-refs.html).
13 -- `dangerouslySetInnerHTML`: Offre l'abilità di inserire HTML grezzo, principalmente per cooperare con librerie di manipolazione di stringhe DOM. Scopri maggiori dettagli [qui](/react/tips/dangerously-set-inner-html.html).
docs/docs/ref-07-special-non-dom-attributes.ko-KR.md deleted
-13
@@ -1,13 +0,0 @@
1 ----
2 -id: special-non-dom-attributes-ko-KR
3 -title: DOM이 아닌 특별한 어트리뷰트
4 -permalink: docs/special-non-dom-attributes-ko-KR.html
5 -prev: dom-differences-ko-KR.html
6 -next: reconciliation-ko-KR.html
7 ----
8 -
9 -[DOM 차이점](/react/docs/dom-differences-ko-KR.html)처럼, React는 DOM에는 존재하지 않는 몇몇 어트리뷰트도 제공합니다.
10 -
11 -- `key`: 선택적인 고유 식별자. 컴포넌트가 `render` 과정에서 섞일 때, diff 알고리즘에 의해 파괴되고, 다시 생성될 수 있습니다. 컴포넌트에 영속적인(persists) 키를 할당하면 컴포넌트가 확실히 유지되게 할 수 있습니다. 더 자세한 것은 [여기](/react/docs/multiple-components-ko-KR.html#동적-자식)에서 보세요.
12 -- `ref`: [여기](/react/docs/more-about-refs-ko-KR.html)를 보세요.
13 -- `dangerouslySetInnerHTML`: 생(raw) HTML을 넣을 수 있게 합니다. 주로 DOM 문자열 관리 라이브러리와의 협력하기 위해 사용합니다. 더 자세한 것은 [여기](/react/tips/dangerously-set-inner-html.html)를 보세요.
docs/docs/ref-07-special-non-dom-attributes.md deleted
-13
@@ -1,13 +0,0 @@
1 ----
2 -id: special-non-dom-attributes
3 -title: Special Non-DOM Attributes
4 -permalink: docs/special-non-dom-attributes.html
5 -prev: dom-differences.html
6 -next: reconciliation.html
7 ----
8 -
9 -Beside [DOM differences](/react/docs/dom-differences.html), React offers some attributes that simply don't exist in DOM.
10 -
11 -- `key`: an optional, unique identifier. When your component shuffles around during `render` passes, it might be destroyed and recreated due to the diff algorithm. Assigning it a key that persists makes sure the component stays. See more [here](/react/docs/multiple-components.html#dynamic-children).
12 -- `ref`: see [here](/react/docs/more-about-refs.html).
13 -- `dangerouslySetInnerHTML`: Provides the ability to insert raw HTML, mainly for cooperating with DOM string manipulation libraries. See more [here](/react/tips/dangerously-set-inner-html.html).
docs/docs/ref-07-special-non-dom-attributes.zh-CN.md deleted
-13
@@ -1,13 +0,0 @@
1 ----
2 -id: special-non-dom-attributes-zh-CN
3 -title: 特殊的 Non-DOM Attributes
4 -permalink: docs/special-non-dom-attributes-zh-CN.html
5 -prev: dom-differences-zh-CN.html
6 -next: reconciliation-zh-CN.html
7 ----
8 -
9 -和 [DOM 的不同之处](/react/docs/dom-differences-zh-CN.html)相比, React 提供了一些不存在于DOM的 attributes .
10 -
11 -- `key`: 一个可选的.独特的标识.当你的组件穿梭于 `render` 的pass,它也许会因为diff算法被摧毁和重建.赋予它一个持久的key保证这个component可达.详见 [这里](/react/docs/multiple-components.html#dynamic-children).
12 -- `ref`: 见 [这里](/react/docs/more-about-refs.html).
13 -- `dangerouslySetInnerHTML`: 提供了直接插入raw HTML的能力,主要是为了与操纵DOM字符串的库协作.详见 [这里](/react/tips/dangerously-set-inner-html.html).
docs/docs/ref-08-reconciliation.it-IT.md deleted
-132
@@ -1,132 +0,0 @@
1 ----
2 -id: reconciliation-it-IT
3 -title: Riconciliazione
4 -permalink: docs/reconciliation-it-IT.html
5 -prev: special-non-dom-attributes-it-IT.html
6 -next: webcomponents.html
7 ----
8 -
9 -La decisione chiave del design di React è fare in modo che l'API sembri ripetere il rendering dell'intera applicazione per ciascun aggiornamento. Ciò rende la scrittura delle applicazione molto più semplice, ma è anche una sfida incredibile per renderlo trattabile. Questo articolo spiega come siamo riusciti a trasformare, tramite potenti euristiche, un problema O(n<sup>3</sup>) in uno O(n).
10 -
11 -
12 -## Motivazione
13 -
14 -Generare il minimo numero di operazioni necessarie a trasformare un albero in un altro è un problema complesso e ben noto. Gli [algoritmi dello stato dell'arte](http://grfia.dlsi.ua.es/ml/algorithms/references/editsurvey_bille.pdf) hanno una complessità dell'ordine di O(n<sup>3</sup>) dove n è il numero di nodi dell'albero.
15 -
16 -Ciò significa che visualizzare 1000 nodi richiederebbe un numero di confronti dell'ordine del miliardo. Ciò è decisamente troppo costoso per il nostro caso d'uso. Per mettere questo numero in prospettiva, le CPU oggi giorno eseguono approssimativamente 3 miliardi di istruzioni al secondo. Quindi anche con l'implementazione più efficiente, non saremmo in grado di calcolare la differenza in meno di un secondo.
17 -
18 -Dal momento che un algoritmo ottimo non è trattabile, implementiamo un algoritmo O(n) non ottimale usando euristiche basate su due assunzioni:
19 -
20 -1. Due componenti della stessa classe genereranno alberi simili e due componenti di classi diverse genereranno alberi diversi.
21 -2. È possibile fornire una chiave unica per gli elementi che sia stabile durante rendering differenti.
22 -
23 -In pratica, queste assunzioni sono eccezionalmente veloci per quasi tutti i casi d'uso pratici.
24 -
25 -
26 -## Differenza a coppie
27 -
28 -Per effettuare la differenza di due alberi, dobbiamo prima essere capaci di effettuare la differenza tra due nodi. Esistono tre diversi casi da considerare.
29 -
30 -
31 -### Tipi di Nodo Differenti
32 -
33 -Se il tipo di nodo è differente, React li tratterà come due sottoalberi diversi, getterà via il primo e costruirà e inserirà il secondo.
34 -
35 -```xml
36 -renderA: <div />
37 -renderB: <span />
38 -=> [removeNode <div />], [insertNode <span />]
39 -```
40 -
41 -La stessa logica è usata per i componenti personalizzati. Se non sono dello stesso tipo, React non proverà neppure a confrontare ciò che visualizzano. Rimuoverà soltanto il primo dal DOM e inserirà il secondo.
42 -
43 -```xml
44 -renderA: <Header />
45 -renderB: <Content />
46 -=> [removeNode <Header />], [insertNode <Content />]
47 -```
48 -
49 -Possedere questa conoscenza di alto livello è un aspetto molto importante del perché l'algoritmo di differenza di React è sia veloce che preciso. Ciò fornisce una buona euristica per potare rapidamente gran parte dell'albero e concentrarsi su parti che hanno una buona probabilità di essere simili.
50 -
51 -È molto improbabile che un elemento `<Header>` generi un DOM che somigli a quello generato da un elemento `<Content>`. Anziché perdere tempo provando a confrontare queste due strutture, React semplicemente ricostruisce l'albero da zero.
52 -
53 -Come corollario, se c'è un elemento `<Header>` nella stessa posizione in due rendering consecutivi, ti puoi aspettare di trovare una struttura molto simile che vale la pena di esplorare.
54 -
55 -
56 -### Nodi DOM
57 -
58 -Quando vengono confrontati nodi DOM, guardiamo gli attributi di entrambi e decidiamo quali di essi sono cambiati in un tempo lineare.
59 -
60 -```xml
61 -renderA: <div id="before" />
62 -renderB: <div id="after" />
63 -=> [replaceAttribute id "after"]
64 -```
65 -
66 -Anziché trattare lo stile come una stringa opaca, viene rappresentato come un oggetto chiave-valore. Ciò ci permette di aggiornare solo le proprietà che sono cambiate.
67 -
68 -```xml
69 -renderA: <div style={{'{{'}}color: 'red'}} />
70 -renderB: <div style={{'{{'}}fontWeight: 'bold'}} />
71 -=> [removeStyle color], [addStyle font-weight 'bold']
72 -```
73 -
74 -Dopo che gli attributi sono stati aggiornati, effettuiamo un confronto ricorsivo su ciascuno dei nodi figli.
75 -
76 -
77 -### Componenti Personalizzati
78 -
79 -We decided that the two custom components are the same. Since components are stateful, we cannot just use the new component and call it a day. React takes all the attributes from the new component and calls `component[Will/Did]ReceiveProps()` on the previous one.
80 -
81 -The previous component is now operational. Its `render()` method is called and the diff algorithm restarts with the new result and the previous result.
82 -
83 -
84 -## List-wise diff
85 -
86 -### Problematic Case
87 -
88 -In order to do children reconciliation, React adopts a very naive approach. It goes over both lists of children at the same time and generates a mutation whenever there's a difference.
89 -
90 -For example if you add an element at the end:
91 -
92 -```xml
93 -renderA: <div><span>first</span></div>
94 -renderB: <div><span>first</span><span>second</span></div>
95 -=> [insertNode <span>second</span>]
96 -```
97 -
98 -Inserting an element at the beginning is problematic. React is going to see that both nodes are spans and therefore run into a mutation mode.
99 -
100 -```xml
101 -renderA: <div><span>first</span></div>
102 -renderB: <div><span>second</span><span>first</span></div>
103 -=> [replaceAttribute textContent 'second'], [insertNode <span>first</span>]
104 -```
105 -
106 -There are many algorithms that attempt to find the minimum sets of operations to transform a list of elements. [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) can find the minimum using single element insertion, deletion and substitution in O(n<sup>2</sup>). Even if we were to use Levenshtein, this doesn't find when a node has moved into another position and algorithms to do that have much worse complexity.
107 -
108 -### Keys
109 -
110 -In order to solve this seemingly intractable issue, an optional attribute has been introduced. You can provide for each child a key that is going to be used to do the matching. If you specify a key, React is now able to find insertion, deletion, substitution and moves in O(n) using a hash table.
111 -
112 -
113 -```xml
114 -renderA: <div><span key="first">first</span></div>
115 -renderB: <div><span key="second">second</span><span key="first">first</span></div>
116 -=> [insertNode <span>second</span>]
117 -```
118 -
119 -In practice, finding a key is not really hard. Most of the time, the element you are going to display already has a unique id. When that's not the case, you can add a new ID property to your model or hash some parts of the content to generate a key. Remember that the key only has to be unique among its siblings, not globally unique.
120 -
121 -
122 -## Trade-offs
123 -
124 -It is important to remember that the reconciliation algorithm is an implementation detail. React could re-render the whole app on every action; the end result would be the same. We are regularly refining the heuristics in order to make common use cases faster.
125 -
126 -In the current implementation, you can express the fact that a sub-tree has been moved amongst its siblings, but you cannot tell that it has moved somewhere else. The algorithm will re-render that full sub-tree.
127 -
128 -Because we rely on two heuristics, if the assumptions behind them are not met, performance will suffer.
129 -
130 -1. The algorithm will not try to match sub-trees of different components classes. If you see yourself alternating between two components classes with very similar output, you may want to make it the same class. In practice, we haven't found this to be an issue.
131 -
132 -2. If you don't provide stable keys (by using Math.random() for example), all the sub-trees are going to be re-rendered every single time. By giving the users the choice to choose the key, they have the ability to shoot themselves in the foot.
docs/docs/ref-08-reconciliation.ko-KR.md deleted
-132
@@ -1,132 +0,0 @@
1 ----
2 -id: reconciliation-ko-KR
3 -title: 비교조정(Reconciliation)
4 -permalink: docs/reconciliation-ko-KR.html
5 -prev: special-non-dom-attributes-ko-KR.html
6 -next: webcomponents.html
7 ----
8 -
9 -React의 주요 설계 철학은 업데이트할 때마다 전체 앱을 다시 렌더하는 것처럼 보이게 API를 만드는 것입니다. 이렇게 하면 애플리케이션 작성이 훨씬 쉬워지지만 한편으로는 어려운 도전 과제이기도 합니다. 이 글에서는 강력한 휴리스틱으로 어떻게 O(n<sup>3</sup>) 복잡도의 문제를 O(n)짜리로 바꿀 수 있었는지 설명합니다.
10 -
11 -
12 -## 동기
13 -
14 -최소한의 연산으로 어떤 트리를 다른 트리로 바꾸는 것은 복잡하고 많이 연구된 문제입니다. n을 트리에 있는 노드 수라고 할 때 [최신 알고리즘](http://grfia.dlsi.ua.es/ml/algorithms/references/editsurvey_bille.pdf)은 O(n<sup>3</sup>) 복잡도를 가집니다.
15 -
16 -다시 말해 1000개의 노드를 표시하려면 10억 번 수준의 비교를 해야 한다는 뜻입니다. 이는 우리가 필요한 용도로는 너무 비쌉니다. 이 수치를 좀 더 알기 쉽게 설명하면, 요즘 CPU는 1초에 대략 30억 번의 연산을 하므로 가장 빠른 구현으로도 1초 안에 이러한 비교는 계산해낼 수 없다는 것입니다.
17 -
18 -최적의 알고리즘을 사용할 수 없기 때문에, 완전하진 않지만 다음의 두 가지 가정에 기반한 휴리스틱을 사용한 O(n) 알고리즘으로 구현했습니다.
19 -
20 -1. 같은 클래스의 두 컴포넌트는 비슷한 트리를 생성하고, 서로 다른 클래스를 가진 두 컴포넌트는 서로 다른 트리를 생성할 것이다.
21 -2. 각 렌더 과정들 사이에 유지되는 엘리먼트에 고유한 키를 제공할 수 있다.
22 -
23 -실제로 이러한 가정은 거의 모든 실용적인 상황에서 굉장히 빠릅니다.
24 -
25 -
26 -## 일대일 비교
27 -
28 -트리 비교를 하기 위해서는 먼저 두 노드를 비교할 수 있어야 합니다. 세 가지 경우를 다룹니다.
29 -
30 -
31 -### 서로 다른 노드 타입
32 -
33 -두 노드의 타입이 서로 다르다면, React는 이를 두 개의 서로 다른 서브트리로 간주해 처음 것을 버리고 두번째 것을 만들어 삽입합니다.
34 -
35 -```xml
36 -renderA: <div />
37 -renderB: <span />
38 -=> [removeNode <div />], [insertNode <span />]
39 -```
40 -
41 -동일한 로직이 커스텀 컴포넌트에 대해서도 적용됩니다. 타입이 다르다면 React는 그 컴포넌트들이 무엇을 렌더하는지 조차도 비교하지 않습니다. 그저 처음 것을 DOM에서 제거하고 두번째 것을 삽입합니다.
42 -
43 -```xml
44 -renderA: <Header />
45 -renderB: <Content />
46 -=> [removeNode <Header />], [insertNode <Content />]
47 -```
48 -
49 -이러한 고수준의 사실을 알 수 있다는 것이 React의 비교 알고리즘이 빠르면서 정확할 수 있는 비결입니다. 트리의 커다란 부분을 일찌감치 탐색 대상에서 제외하고 비슷할 가능성이 높은 부분에 집중할 수 있는 좋은 휴리스틱을 제공합니다.
50 -
51 -`<Header>` 엘리먼트가 생성하는 DOM이 `<Content>`가 생성하는 것과 비슷하게 생길 확률은 매우 낮습니다. 이 두 구조를 비교하는데 시간을 낭비하지 않고 React는 그냥 트리를 처음부터 새로 만듭니다.
52 -
53 -한편 두 번의 연속적인 렌더에서 같은 위치에 `<Header>` 엘리먼트가 있다면 비슷한 구조일 것이므로 탐색할만 합니다.
54 -
55 -
56 -### DOM 노드
57 -
58 -두 DOM 노드를 비교할 때는 어트리뷰트를 보고 무엇이 바뀌었는지 선형 시간 안에 결정할 수 있습니다.
59 -
60 -```xml
61 -renderA: <div id="before" />
62 -renderB: <div id="after" />
63 -=> [replaceAttribute id "after"]
64 -```
65 -
66 -스타일을 불명확한 문자열로 다루지 않고 키-값 객체를 사용합니다. 이는 변경된 프로퍼티만 업데이트 하도록 해줍니다.
67 -
68 -```xml
69 -renderA: <div style={{'{{'}}color: 'red'}} />
70 -renderB: <div style={{'{{'}}fontWeight: 'bold'}} />
71 -=> [removeStyle color], [addStyle font-weight 'bold']
72 -```
73 -
74 -어트리뷰트가 업데이트된 다음에는, 모든 자식도 재귀적으로 업데이트합니다.
75 -
76 -
77 -### 커스텀 컴포넌트
78 -
79 -우리는 두 커스텀 컴포넌트를 같은 것으로 취급하기로 했습니다. 컴포넌트는 상태를 가지기 때문에 새 컴포넌트를 그냥 사용할 수는 없습니다. React는 새 컴포넌트의 모든 어트리뷰트를 취해 이전 컴포넌트의 `component[Will/Did]ReceiveProps()`를 호출해 줍니다.
80 -
81 -이제 이전 컴포넌트가 작동합니다. 거기 있는 `render()` 메소드가 호출되고 비교 알고리즘이 다시 새로운 결과와 이전 결과를 비교합니다.
82 -
83 -
84 -## 목록끼리 비교
85 -
86 -### 문제가 되는 경우
87 -
88 -React는 매우 단순한 방식으로 자식 비교조정(children reconciliation)을 합니다. 자식 목록을 동시에 서로 비교하다가 차이를 발견하면 변경 사항을 적용합니다.
89 -
90 -예를 들어 맨 끝에 엘리먼트를 추가한 경우에는:
91 -
92 -```xml
93 -renderA: <div><span>first</span></div>
94 -renderB: <div><span>first</span><span>second</span></div>
95 -=> [insertNode <span>second</span>]
96 -```
97 -
98 -맨 앞에 엘리먼트를 삽입하는 경우가 문제입니다. React는 두 노드가 모두 span인지 확인하고 변경 모드로 작동합니다.
99 -
100 -```xml
101 -renderA: <div><span>first</span></div>
102 -renderB: <div><span>second</span><span>first</span></div>
103 -=> [replaceAttribute textContent 'second'], [insertNode <span>first</span>]
104 -```
105 -
106 -원소의 목록을 변환하기 위한 최소 연산 집합을 찾는 알고리즘이 여럿 있습니다. [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance)를 사용하면 O(n<sup>2</sup>) 복잡도로 원소 한 개의 삽입, 삭제, 교체를 위해 필요한 최솟값을 찾을 수 있습니다. Levenshtein 알고리즘을 사용해도 노드가 다른 위치로 이동한 경우는 알아낼 수 없고, 그것을 알아내는 알고리즘은 더욱 높은 복잡도를 가집니다.
107 -
108 -### 키(keys)
109 -
110 -해결할 수 없어보이는 이 문제를 풀기 위해 선택적인 어트리뷰트를 도입했습니다. 각 자식에 키(key)를 할당해 이를 비교하는 데에 사용합니다. 키를 명시하면 React가 해시 테이블을 사용하여 삽입, 삭제, 교체 및 이동을 O(n) 복잡도로 찾아낼 수 있습니다.
111 -
112 -
113 -```xml
114 -renderA: <div><span key="first">first</span></div>
115 -renderB: <div><span key="second">second</span><span key="first">first</span></div>
116 -=> [insertNode <span>second</span>]
117 -```
118 -
119 -실제 상황에서 키를 찾는 것은 별로 어렵지 않습니다. 대부분의 경우, 표시하려는 엘리먼트는 이미 고유한 식별자를 가지고 있습니다. 그렇지 않은 경우에도 모델에 새로운 ID 프로퍼티를 추가하거나 내용의 일부분을 해시하여 키를 생성할 수 있습니다. 키는 형제 노드 사이에서만 고유하면 됩니다. 전역적으로 고유할 필요는 없습니다.
120 -
121 -
122 -## 트레이드오프
123 -
124 -비교조정 알고리즘이 구현 세부사항이라는 것을 기억하는 것은 중요합니다. React가 전체 앱을 모든 동작마다 새로 렌더해도 결과는 같을 것입니다. 일반적인 사용 패턴을 빠르게 만들 수 있도록 저희는 계속 휴리스틱을 다듬고 있습니다.
125 -
126 -현재 구현에서 서브트리가 형제 노드 사이에서 이동하는 경우는 표현할 수 있지만, 그 외의 곳으로 이동했는지는 알 수 없습니다. 알고리즘에 따라 전체 서브트리가 다시 렌더됩니다.
127 -
128 -두 가지 휴리스틱에 의존하기 때문에 그에 대한 가정이 만족되지 않으면 성능이 좋지 않을 것입니다.
129 -
130 -1. 서로 다른 컴포넌트 클래스의 서브트리는 비교하려고 시도하지 않습니다. 만약 매우 비슷한 출력 결과의 두 컴포넌트를 왔다갔다 하는 경우 같은 클래스로 만들 수 있습니다. 실제 상황에서는 큰 문제가 없습니다.
131 -
132 -2. 안정적인 키를 붙이지 않을 경우 (예를 들어 Math.random()을 사용한다거나) 모든 서브트리가 매번 다시 렌더될 것입니다. 사용자에게 키를 선택하도록 하는 대신 실수할 수 있는 여지가 있습니다.
docs/docs/ref-08-reconciliation.md deleted
-133
@@ -1,133 +0,0 @@
1 ----
2 -id: reconciliation
3 -title: Reconciliation
4 -permalink: docs/reconciliation.html
5 -prev: special-non-dom-attributes.html
6 -next: webcomponents.html
7 ----
8 -
9 -React's key design decision is to make the API seem like it re-renders the whole app on every update. This makes writing applications a lot easier but is also an incredible challenge to make it tractable. This article explains how with powerful heuristics we managed to turn a O(n<sup>3</sup>) problem into a O(n) one.
10 -
11 -
12 -## Motivation
13 -
14 -Generating the minimum number of operations to transform one tree into another is a complex and well-studied problem. The [state of the art algorithms](http://grfia.dlsi.ua.es/ml/algorithms/references/editsurvey_bille.pdf) have a complexity in the order of O(n<sup>3</sup>) where n is the number of nodes in the tree.
15 -
16 -This means that displaying 1000 nodes would require in the order of one billion comparisons. This is far too expensive for our use case. To put this number in perspective, CPUs nowadays execute roughly 3 billion instructions per second. So even with the most performant implementation, we wouldn't be able to compute that diff in less than a second.
17 -
18 -Since an optimal algorithm is not tractable, we implement a non-optimal O(n) algorithm using heuristics based on two assumptions:
19 -
20 -1. Two components of the same class will generate similar trees and two components of different classes will generate different trees.
21 -2. It is possible to provide a unique key for elements that is stable across different renders.
22 -
23 -In practice, these assumptions are ridiculously fast for almost all practical use cases.
24 -
25 -
26 -## Pair-wise diff
27 -
28 -In order to do a tree diff, we first need to be able to diff two nodes. There are three different cases being handled.
29 -
30 -
31 -### Different Node Types
32 -
33 -If the node type is different, React is going to treat them as two different sub-trees, throw away the first one and build/insert the second one.
34 -
35 -```xml
36 -renderA: <div />
37 -renderB: <span />
38 -=> [removeNode <div />], [insertNode <span />]
39 -```
40 -
41 -The same logic is used for custom components. If they are not of the same type, React is not going to even try at matching what they render. It is just going to remove the first one from the DOM and insert the second one.
42 -
43 -```xml
44 -renderA: <Header />
45 -renderB: <Content />
46 -=> [removeNode <Header />], [insertNode <Content />]
47 -```
48 -
49 -Having this high level knowledge is a very important aspect of why React's diff algorithm is both fast and precise. It provides a good heuristic to quickly prune big parts of the tree and focus on parts likely to be similar.
50 -
51 -It is very unlikely that a `<Header>` element is going to generate a DOM that is going to look like what a `<Content>` would generate. Instead of spending time trying to match those two structures, React just re-builds the tree from scratch.
52 -
53 -As a corollary, if there is a `<Header>` element at the same position in two consecutive renders, you would expect to see a very similar structure and it is worth exploring it.
54 -
55 -
56 -### DOM Nodes
57 -
58 -When comparing two DOM nodes, we look at the attributes of both and can decide which of them changed in linear time.
59 -
60 -```xml
61 -renderA: <div id="before" />
62 -renderB: <div id="after" />
63 -=> [replaceAttribute id "after"]
64 -```
65 -
66 -Instead of treating style as an opaque string, a key-value object is used instead. This lets us update only the properties that changed.
67 -
68 -```xml
69 -renderA: <div style={{'{{'}}color: 'red'}} />
70 -renderB: <div style={{'{{'}}fontWeight: 'bold'}} />
71 -=> [removeStyle color], [addStyle font-weight 'bold']
72 -```
73 -
74 -After the attributes have been updated, we recurse on all the children.
75 -
76 -
77 -### Custom Components
78 -
79 -We decided that the two custom components are the same. Since components are stateful, we cannot just use the new component and call it a day. React takes all the attributes from the new component and calls `componentWillReceiveProps()` and `componentWillUpdate()` on the previous one.
80 -
81 -The previous component is now operational. Its `render()` method is called and the diff algorithm restarts with the new result and the previous result.
82 -
83 -
84 -## List-wise diff
85 -
86 -### Problematic Case
87 -
88 -In order to do children reconciliation, React adopts a very naive approach. It goes over both lists of children at the same time and generates a mutation whenever there's a difference.
89 -
90 -For example if you add an element at the end:
91 -
92 -```xml
93 -renderA: <div><span>first</span></div>
94 -renderB: <div><span>first</span><span>second</span></div>
95 -=> [insertNode <span>second</span>]
96 -```
97 -
98 -Inserting an element at the beginning is problematic. React is going to see that both nodes are spans and therefore run into a mutation mode.
99 -
100 -```xml
101 -renderA: <div><span>first</span></div>
102 -renderB: <div><span>second</span><span>first</span></div>
103 -=> [replaceAttribute textContent 'second'], [insertNode <span>first</span>]
104 -```
105 -
106 -There are many algorithms that attempt to find the minimum sets of operations to transform a list of elements. [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) can find the minimum using single element insertion, deletion and substitution in O(n<sup>2</sup>). Even if we were to use Levenshtein, this doesn't find when a node has moved into another position and algorithms to do that have much worse complexity.
107 -
108 -### Keys
109 -
110 -In order to solve this seemingly intractable issue, an optional attribute has been introduced. You can provide for each child a key that is going to be used to do the matching. If you specify a key, React is now able to find insertion, deletion, substitution and moves in O(n) using a hash table.
111 -
112 -
113 -```xml
114 -renderA: <div><span key="first">first</span></div>
115 -renderB: <div><span key="second">second</span><span key="first">first</span></div>
116 -=> [insertNode <span>second</span>]
117 -```
118 -
119 -In practice, finding a key is not really hard. Most of the time, the element you are going to display already has a unique id. When that's not the case, you can add a new ID property to your model or hash some parts of the content to generate a key. Remember that the key only has to be unique among its siblings, not globally unique.
120 -
121 -
122 -## Trade-offs
123 -
124 -It is important to remember that the reconciliation algorithm is an implementation detail. React could re-render the whole app on every action; the end result would be the same. We are regularly refining the heuristics in order to make common use cases faster.
125 -
126 -In the current implementation, you can express the fact that a sub-tree has been moved amongst its siblings, but you cannot tell that it has moved somewhere else. The algorithm will re-render that full sub-tree.
127 -
128 -Because we rely on two heuristics, if the assumptions behind them are not met, performance will suffer.
129 -
130 -1. The algorithm will not try to match sub-trees of different components classes. If you see yourself alternating between two components classes with very similar output, you may want to make it the same class. In practice, we haven't found this to be an issue.
131 -
132 -2. Keys should be stable, predictable, and unique. Unstable keys (like those produced by Math.random()) will cause many nodes to be unnecessarily re-created, which can cause performance degradation and lost state in child components.
133 -
docs/docs/ref-09-webcomponents.md deleted
-56
@@ -1,56 +0,0 @@
1 ----
2 -id: webcomponents
3 -title: Web Components
4 -permalink: docs/webcomponents.html
5 -prev: reconciliation.html
6 -next: glossary.html
7 ----
8 -
9 -Trying to compare and contrast React with WebComponents inevitably results in specious conclusions, because the two libraries are built to solve different problems. WebComponents provide strong encapsulation for reusable components, while React provides a declarative library that keeps the DOM in sync with your data. The two goals are complementary; engineers can mix-and-match the technologies. As a developer, you are free to use React in your WebComponents, or to use WebComponents in React, or both.
10 -
11 -## Using Web Components in React
12 -
13 -```javascript
14 -class HelloMessage extends React.Component{
15 - render() {
16 - return <div>Hello <x-search>{this.props.name}</x-search>!</div>;
17 - }
18 -}
19 -```
20 -
21 -> Note:
22 ->
23 -> The programming models of the two component systems (web components vs. react components) differ in that
24 -> web components often expose an imperative API (for instance, a `video` web component might expose `play()`
25 -> and `pause()` functions). To the extent that web components are declarative functions of their attributes,
26 -> they should work, but to access the imperative APIs of a web component, you will need to attach a ref to the
27 -> component and interact with the DOM node directly. If you are using third-party web components, the
28 -> recommended solution is to write a React component that behaves as a wrapper for your web component.
29 ->
30 -> At this time, events emitted by a web component may not properly propagate through a React render tree.
31 -> You will need to manually attach event handlers to handle these events within your React components.
32 -
33 -
34 -## Using React in your Web Components
35 -
36 -
37 -```javascript
38 -var proto = Object.create(HTMLElement.prototype, {
39 - attachedCallback: {
40 - value: function() {
41 - var mountPoint = document.createElement('span');
42 - this.createShadowRoot().appendChild(mountPoint);
43 -
44 - var name = this.getAttribute('name');
45 - var url = 'https://www.google.com/search?q=' + encodeURIComponent(name);
46 - ReactDOM.render(<a href={url}>{name}</a>, mountPoint);
47 - }
48 - }
49 -});
50 -document.registerElement('x-search', {prototype: proto});
51 -```
52 -
53 -## Complete Example
54 -
55 -Check out the `webcomponents` example in the [starter kit](/react/downloads.html) for a complete example.
56 -
docs/docs/ref-09-webcomponents.zh-CN.md deleted
-56
@@ -1,56 +0,0 @@
1 ----
2 -id: webcomponents-zh-CN
3 -title: Web Components
4 -permalink: docs/webcomponents-zh-CN.html
5 -prev: reconciliation-zh-CN.html
6 -next: glossary-zh-CN.html
7 ----
8 -
9 -因为React和Web组件是用来解决不同问题的, 试图比较两者将不可避免地导致似是而非的结论, 。Web组件为可复用组件提供了强大的封装, 而React则提供了一个使DOM与你的数据同步的声明式库。两者的目标是互补的;工程师可以混合使用这些技术。作为一个开发者,你可以在你的Web组件中使用React,或者在React中使用Web组件,或者两者一起使用。
10 -
11 -## 在React中使用Web组件
12 -
13 -```javascript
14 -class HelloMessage extends React.Component{
15 - render() {
16 - return <div>Hello <x-search>{this.props.name}</x-search>!</div>;
17 - }
18 -}
19 -```
20 -
21 -> 注意:
22 ->
23 -> 两个组件系统的程序模型 (web 组件 与 react 组件) 区别在
24 -> web组件通常暴露一个命令式的API (比如 一个 `video` web 组件可能暴露 `play()`
25 -> 与 `pause()` 函数)。 因为web 组件是它们属性的声明式函数,
26 -> 他们应该可以执行, 但是如果要访问命令式API的一个web组件, 你将需要在组件上附加一个引用
27 -> 并与DOM节点直接交互。如果你在使用第三方web组件,
28 -> 我们推荐你写一个React组件作为你的web组件的封装。
29 ->
30 -> 当前,一个由web组件触发的事件可能不能准确地在React渲染树中传递。
31 -> 你将需要手动附加event handlers来在你的react组件中处理这些事件。
32 -
33 -
34 -## 在Web 组件中使用React
35 -
36 -
37 -```javascript
38 -var proto = Object.create(HTMLElement.prototype, {
39 - attachedCallback: {
40 - value: function() {
41 - var mountPoint = document.createElement('span');
42 - this.createShadowRoot().appendChild(mountPoint);
43 -
44 - var name = this.getAttribute('name');
45 - var url = 'https://www.google.com/search?q=' + encodeURIComponent(name);
46 - ReactDOM.render(<a href={url}>{name}</a>, mountPoint);
47 - }
48 - }
49 -});
50 -document.registerElement('x-search', {prototype: proto});
51 -```
52 -
53 -## 完整样例
54 -
55 -若要查看完整样例,请参照[starter kit](/react/downloads.html)中的`webcomponents`例子。
56 -
docs/docs/ref-10-glossary.it-IT.md deleted
-192
@@ -1,192 +0,0 @@
1 ----
2 -id: glossary-it-IT
3 -title: Terminologia del DOM (Virtuale)
4 -permalink: docs/glossary-it-IT.html
5 -prev: webcomponents.html
6 ----
7 -
8 -Nella terminologia di React, esistono cinque tipi base che è importante distinguere:
9 -
10 -- [ReactElement / ReactElement Factory](#react-elements)
11 -- [ReactNode](#react-nodes)
12 -- [ReactComponent / ReactComponent Class](#react-components)
13 -
14 -## Elementi React
15 -
16 -Il tipo primario in React è il `ReactElement`. Possiede quattro proprietà: `type`, `props`, `key` e `ref`. Non possiede alcun metodo e non espone nulla sul prototype.
17 -
18 -Puoi creare uno di questi oggetti attraverso `React.createElement`.
19 -
20 -```javascript
21 -var root = React.createElement('div');
22 -```
23 -
24 -Per effettuare il rendering di un nuovo albero nel DOM, crei dei `ReactElement` ande li passi a `ReactDOM.render` assieme a un `Element` DOM regolare (`HTMLElement` o `SVGElement`). I `ReactElement` non vanno confusi con gli `Element` del DOM. Un `ReactElement` è una rappresentazione leggera, priva di stato, immutabile e virtuale di un `Element` del DOM. È un DOM virtuale.
25 -
26 -```javascript
27 -ReactDOM.render(root, document.getElementById('example'));
28 -```
29 -
30 -Per aggiungere proprietà ad un elemento DOM, passa un oggetto di proprietà come secondo argomento, e i figli come terzo argomento.
31 -
32 -```javascript
33 -var child = React.createElement('li', null, 'Contenuto di Testo');
34 -var root = React.createElement('ul', { className: 'my-list' }, child);
35 -ReactDOM.render(root, document.getElementById('example'));
36 -```
37 -
38 -Se usi React JSX, allora questi `ReactElement` verranno creati per te. Questa espressione è equivalente:
39 -
40 -```javascript
41 -var root = <ul className="my-list">
42 - <li>Contenuto di Testo</li>
43 - </ul>;
44 -ReactDOM.render(root, document.getElementById('example'));
45 -```
46 -
47 -### Le Factory
48 -
49 -Una factory di `ReactElement` è semplicemente una funzione che genera un `ReactElement` con una particolare proprietà `type`. React ha uno helper integrato per permetterti di creare factory. La sua implementazione è semplicemente:
50 -
51 -```javascript
52 -function createFactory(type) {
53 - return React.createElement.bind(null, type);
54 -}
55 -```
56 -
57 -Ti permette di creare una conveniente scorciatoia anziché scrivere ogni volta `React.createElement('div')`.
58 -
59 -```javascript
60 -var div = React.createFactory('div');
61 -var root = div({ className: 'my-div' });
62 -ReactDOM.render(root, document.getElementById('example'));
63 -```
64 -
65 -React possiede già factory integrate per tag HTML comuni:
66 -
67 -```javascript
68 -var root = React.DOM.ul({ className: 'my-list' },
69 - React.DOM.li(null, 'Contenuto di Testo')
70 - );
71 -```
72 -
73 -Se stai usando JSX non hai bisogno di factory. JSX fornisce già una conveniente scorciatoia per creare `ReactElement`.
74 -
75 -
76 -## Nodi React
77 -
78 -Un `ReactNode` può essere uno tra:
79 -
80 -- `ReactElement`
81 -- `string` (ovvero `ReactText`)
82 -- `number` (ovvero `ReactText`)
83 -- Array di `ReactNode` (ovvero `ReactFragment`)
84 -
85 -Questi sono usati come proprietà di altri `ReactElement` per rappresentare i figli. Effettivamente creano un albero di `ReactElement`.
86 -
87 -
88 -## Componenti React
89 -
90 -Puoi usare React usando soltanto `ReactElement`, ma per avvantaggiarti seriamente di React vorrai usare i `ReactComponent` per creare incapsulamento con uno stato incluso.
91 -
92 -Una classe `ReactComponent` è semplicemente una classe JavaScript (o una "funzione costruttore").
93 -
94 -```javascript
95 -var MyComponent = React.createClass({
96 - render: function() {
97 - ...
98 - }
99 -});
100 -```
101 -
102 -Quando questo costruttore è invocato, ci si aspetta che restituisca un oggetto con almeno un metodo `render`. Questo oggetto è chiamato `ReactComponent`.
103 -
104 -```javascript
105 -var component = new MyComponent(props); // non farlo mai!
106 -```
107 -
108 -Per scopi diversi dai test, *non chiamerai mai* questo costruttore direttamente. React lo chiamerà per te.
109 -
110 -Invece, passa una classe `ReactComponent` a `createElement` per ottenere un `ReactElement`.
111 -
112 -```javascript
113 -var element = React.createElement(MyComponent);
114 -```
115 -
116 -OPPURE usando JSX:
117 -
118 -```javascript
119 -var element = <MyComponent />;
120 -```
121 -
122 -Quando `element` viene passato a `ReactDOM.render`, React chiamerà il costruttore al tuo posto e creerà un`ReactComponent`, che verrà restituito.
123 -
124 -```javascript
125 -var component = ReactDOM.render(element, document.getElementById('example'));
126 -```
127 -
128 -Se chiami ripetutamente `ReactDOM.render` con lo stesso tipo di `ReactElement` e lo stesso `Element` DOM come contenitore, ti restituirà sempre la stessa istanza. Questa istanza è dotata di stato.
129 -
130 -```javascript
131 -var componentA = ReactDOM.render(<MyComponent />, document.getElementById('example'));
132 -var componentB = ReactDOM.render(<MyComponent />, document.getElementById('example'));
133 -componentA === componentB; // true
134 -```
135 -
136 -Questo è il motivo per cui non dovresti mai costruire la tua istanza. Invece, `ReactElement` è un `ReactComponent` virtuale prima che venga costruito. Un vecchio `ReactElement` e uno nuovo possono essere confrontati per vedere se una nuova istanza di `ReactComponent` è stata creata o quella esistente è stata riutilizzata.
137 -
138 -Ci si aspetta che il metodo `render` di un `ReactComponent` restituisca un altro `ReactElement`. Ciò permette a questi componenti di essere composti. In ultima analisi, il rendering si risolve in un `ReactElement` con un tag `string` che viene istanziato come un `Element` DOM e viene inserito nel documento.
139 -
140 -
141 -## Definizioni Formali dei Tipi
142 -
143 -### Punto di Entrata
144 -
145 -```
146 -ReactDOM.render = (ReactElement, HTMLElement | SVGElement) => ReactComponent;
147 -```
148 -
149 -### Nodi ed Elementi
150 -
151 -```
152 -type ReactNode = ReactElement | ReactFragment | ReactText;
153 -
154 -type ReactElement = ReactComponentElement | ReactDOMElement;
155 -
156 -type ReactDOMElement = {
157 - type : string,
158 - props : {
159 - children : ReactNodeList,
160 - className : string,
161 - etc.
162 - },
163 - key : string | boolean | number | null,
164 - ref : string | null
165 -};
166 -
167 -type ReactComponentElement<TProps> = {
168 - type : ReactClass<TProps>,
169 - props : TProps,
170 - key : string | boolean | number | null,
171 - ref : string | null
172 -};
173 -
174 -type ReactFragment = Array<ReactNode | ReactEmpty>;
175 -
176 -type ReactNodeList = ReactNode | ReactEmpty;
177 -
178 -type ReactText = string | number;
179 -
180 -type ReactEmpty = null | undefined | boolean;
181 -```
182 -
183 -### Classi e Componenti
184 -
185 -```
186 -type ReactClass<TProps> = (TProps) => ReactComponent<TProps>;
187 -
188 -type ReactComponent<TProps> = {
189 - props : TProps,
190 - render : () => ReactElement
191 -};
192 -```
docs/docs/ref-10-glossary.ko-KR.md deleted
-193
@@ -1,193 +0,0 @@
1 ----
2 -id: glossary-ko-KR
3 -title: React (가상) DOM 용어
4 -permalink: docs/glossary-ko-KR.html
5 -prev: webcomponents-ko-KR.html
6 ----
7 -
8 -다음은 React에서 사용되는 용어들로, 이 다섯 가지의 타입을 구별하는 것은 중요합니다.
9 -
10 -- [ReactElement / ReactElement 팩토리](#react-엘리먼트)
11 -- [ReactNode](#react-노드)
12 -- [ReactComponent / ReactComponent 클래스](#react-컴포넌트)
13 -
14 -## React 엘리먼트
15 -
16 -`ReactElement`는 React의 주요 타입입니다. `type`, `props`, `key`, `ref`의 네 가지 프로퍼티를 가집니다. 메소드는 가지지 않으며 프로토타입에는 아무 것도 들어있지 않습니다.
17 -
18 -이러한 객체는 `React.createElement`를 통해 만들 수 있습니다.
19 -
20 -```javascript
21 -var root = React.createElement('div');
22 -```
23 -
24 -DOM에 새로운 트리를 렌더링하기 위해서는 `ReactElement`를 만들고 일반적인 DOM `Element` (`HTMLElement` 또는 `SVGElement`)와 함께 `ReactDOM.render`에 넘깁니다. `ReactElement`를 DOM `Element`와 혼동해서는 안됩니다. `ReactElement`는 가볍고, 상태를 갖지 않으며, 변경 불가능한, DOM `Element`의 가상 표현입니다. 즉 가상 DOM입니다.
25 -
26 -```javascript
27 -ReactDOM.render(root, document.getElementById('example'));
28 -```
29 -
30 -DOM 엘리먼트에 프로퍼티를 추가하려면 두번째 인자로 프로퍼티 객체를, 세번째 인자로 자식을 넘깁니다.
31 -
32 -```javascript
33 -var child = React.createElement('li', null, 'Text Content');
34 -var root = React.createElement('ul', { className: 'my-list' }, child);
35 -ReactDOM.render(root, document.getElementById('example'));
36 -```
37 -
38 -React JSX를 사용하면 `ReactElement`가 알아서 만들어집니다. 따라서 다음 코드는 앞의 코드와 같습니다:
39 -
40 -```javascript
41 -var root = <ul className="my-list">
42 - <li>Text Content</li>
43 - </ul>;
44 -ReactDOM.render(root, document.getElementById('example'));
45 -```
46 -
47 -### 팩토리
48 -
49 -`ReactElement` 팩토리는 그저 특정한 `type` 프로퍼티를 가지는 `ReactElement`를 만들어주는 함수입니다. React에는 팩토리를 만드는 헬퍼가 내장되어 있습니다. 그 함수는 사실상 다음과 같습니다:
50 -
51 -```javascript
52 -function createFactory(type) {
53 - return React.createElement.bind(null, type);
54 -}
55 -```
56 -
57 -이를 이용하면 편리한 단축 함수를 만들 수 있어 항상 `React.createElement('div')`를 입력하지 않아도 됩니다.
58 -
59 -```javascript
60 -var div = React.createFactory('div');
61 -var root = div({ className: 'my-div' });
62 -ReactDOM.render(root, document.getElementById('example'));
63 -```
64 -
65 -React에는 이미 보통의 HTML 태그를 위한 팩토리가 내장되어 있습니다:
66 -
67 -```javascript
68 -var root = React.DOM.ul({ className: 'my-list' },
69 - React.DOM.li(null, 'Text Content')
70 - );
71 -```
72 -
73 -JSX를 사용하면 팩토리가 필요하지 않습니다. 이미 JSX가 `ReactElement`를 만드는 편리한 단축 문법을 제공합니다.
74 -
75 -
76 -## React 노드
77 -
78 -`ReactNode`는 다음 중 하나가 될 수 있습니다:
79 -
80 -- `ReactElement`
81 -- `string` (`ReactText`로 부르기도 함)
82 -- `number` (`ReactText`로 부르기도 함)
83 -- `ReactNode`의 배열 (`ReactFragment`로 부르기도 함)
84 -
85 -이들은 자식을 표현하기 위해 다른 `ReactElement`의 프로퍼티에 사용됩니다. 사실상 이들이 `ReactElement`의 트리를 형성합니다.
86 -
87 -
88 -## React 컴포넌트
89 -
90 -`ReactElement`만 가지고도 React를 사용할 수는 있지만, React의 장점을 제대로 활용하려면 `ReactComponent`를 사용하여 상태를 가진 캡슐화된 객체를 만들기를 원할 것입니다.
91 -
92 -`ReactComponent` 클래스는 그냥 JavaScript 클래스 (또는 "생성자 함수")입니다.
93 -
94 -```javascript
95 -var MyComponent = React.createClass({
96 - render: function() {
97 - ...
98 - }
99 -});
100 -```
101 -
102 -이 생성자가 호출될 때 최소한 `render` 메소드를 가진 객체를 리턴해야 합니다. 이 리턴된 객체를 `ReactComponent`라고 부릅니다.
103 -
104 -```javascript
105 -var component = new MyComponent(props); // 절대 하지 마세요.
106 -```
107 -
108 -테스트 목적이 아니라면 *절대* 이 생성자를 직접 호출하지 마십시오. React가 알아서 호출해줍니다.
109 -
110 -대신 `ReactComponent` 클래스를 `createElement`에 넘겨 `ReactElement`를 받을 수 있습니다.
111 -
112 -```javascript
113 -var element = React.createElement(MyComponent);
114 -```
115 -
116 -또는 JSX를 사용하면:
117 -
118 -```javascript
119 -var element = <MyComponent />;
120 -```
121 -
122 -이것이 `ReactDOM.render`에 넘겨지면 React가 알아서 생성자를 호출하여 `ReactComponent`를 만들고 리턴합니다.
123 -
124 -```javascript
125 -var component = ReactDOM.render(element, document.getElementById('example'));
126 -```
127 -
128 -같은 타입의 `ReactElement`와 같은 컨테이너 DOM `Element`를 가지고 `ReactDOM.render`를 계속 호출하면 항상 같은 인스턴스를 리턴합니다. 이 인스턴스는 상태를 가집니다.
129 -
130 -```javascript
131 -var componentA = ReactDOM.render(<MyComponent />, document.getElementById('example'));
132 -var componentB = ReactDOM.render(<MyComponent />, document.getElementById('example'));
133 -componentA === componentB; // true
134 -```
135 -
136 -그렇기 때문에 직접 인스턴스를 만들어서는 안됩니다. `ReactComponent`가 생성되기 전에 `ReactElement`가 대신 가상의 `ReactComponent` 역할을 합니다. 이전 `ReactElement`와 새 `ReactElement`를 비교하여 새로운 `ReactComponent`를 만들지, 아니면 기존 것을 재사용할지 결정합니다.
137 -
138 -`ReactComponent`의 `render` 메소드는 또다른 `ReactElement`를 리턴해야 합니다. 이렇게 해서 컴포넌트들이 조합됩니다. 결과적으로 렌더링 과정은 다음과 같습니다. `string` 타입의 태그를 가진 `ReactElement`를 통해 DOM `Element` 인스턴스가 생성되며 문서에 삽입됩니다.
139 -
140 -
141 -## 형식 타입 정의
142 -
143 -### 진입점
144 -
145 -```
146 -ReactDOM.render = (ReactElement, HTMLElement | SVGElement) => ReactComponent;
147 -```
148 -
149 -### 노드와 엘리먼트
150 -
151 -```
152 -type ReactNode = ReactElement | ReactFragment | ReactText;
153 -
154 -type ReactElement = ReactComponentElement | ReactDOMElement;
155 -
156 -type ReactDOMElement = {
157 - type : string,
158 - props : {
159 - children : ReactNodeList,
160 - className : string,
161 - etc.
162 - },
163 - key : string | boolean | number | null,
164 - ref : string | null
165 -};
166 -
167 -type ReactComponentElement<TProps> = {
168 - type : ReactClass<TProps>,
169 - props : TProps,
170 - key : string | boolean | number | null,
171 - ref : string | null
172 -};
173 -
174 -type ReactFragment = Array<ReactNode | ReactEmpty>;
175 -
176 -type ReactNodeList = ReactNode | ReactEmpty;
177 -
178 -type ReactText = string | number;
179 -
180 -type ReactEmpty = null | undefined | boolean;
181 -```
182 -
183 -### 클래스와 컴포넌트
184 -
185 -```
186 -type ReactClass<TProps> = (TProps) => ReactComponent<TProps>;
187 -
188 -type ReactComponent<TProps> = {
189 - props : TProps,
190 - render : () => ReactElement
191 -};
192 -```
193 -
docs/docs/ref-10-glossary.md deleted
-196
@@ -1,196 +0,0 @@
1 ----
2 -id: glossary
3 -title: React (Virtual) DOM Terminology
4 -permalink: docs/glossary.html
5 -prev: webcomponents.html
6 ----
7 -
8 -In React's terminology, there are five core types that are important to distinguish:
9 -
10 -- [ReactElement / ReactElement Factory](#react-elements)
11 -- [ReactNode](#react-nodes)
12 -- [ReactComponent / ReactComponent Class](#react-components)
13 -
14 -## React Elements
15 -
16 -The primary type in React is the `ReactElement`. It has four properties: `type`, `props`, `key` and `ref`. It has no methods and nothing on the prototype.
17 -
18 -You can create one of these objects through `React.createElement`.
19 -
20 -```javascript
21 -var root = React.createElement('div');
22 -```
23 -
24 -To render a new tree into the DOM, you create `ReactElement`s and pass them to `ReactDOM.render` along with a regular DOM `Element` (`HTMLElement` or `SVGElement`). `ReactElement`s are not to be confused with DOM `Element`s. A `ReactElement` is a light, stateless, immutable, virtual representation of a DOM `Element`. It is a virtual DOM.
25 -
26 -```javascript
27 -ReactDOM.render(root, document.getElementById('example'));
28 -```
29 -
30 -To add properties to a DOM element, pass a properties object as the second argument and children to the third argument.
31 -
32 -```javascript
33 -var child = React.createElement('li', null, 'Text Content');
34 -var root = React.createElement('ul', { className: 'my-list' }, child);
35 -ReactDOM.render(root, document.getElementById('example'));
36 -```
37 -
38 -If you use React JSX, then these `ReactElement`s are created for you. So this is equivalent:
39 -
40 -```javascript
41 -var root = <ul className="my-list">
42 - <li>Text Content</li>
43 - </ul>;
44 -ReactDOM.render(root, document.getElementById('example'));
45 -```
46 -
47 -### Factories
48 -
49 -A `ReactElement`-factory is simply a function that generates a `ReactElement` with a particular `type` property. React has a built-in helper for you to create factories. It's effectively just:
50 -
51 -```javascript
52 -function createFactory(type) {
53 - return React.createElement.bind(null, type);
54 -}
55 -```
56 -
57 -It allows you to create a convenient short-hand instead of typing out `React.createElement('div')` all the time.
58 -
59 -```javascript
60 -var div = React.createFactory('div');
61 -var root = div({ className: 'my-div' });
62 -ReactDOM.render(root, document.getElementById('example'));
63 -```
64 -
65 -React already has built-in factories for common HTML tags:
66 -
67 -```javascript
68 -var root = React.DOM.ul({ className: 'my-list' },
69 - React.DOM.li(null, 'Text Content')
70 - );
71 -```
72 -
73 -If you are using JSX you have no need for factories. JSX already provides a convenient short-hand for creating `ReactElement`s.
74 -
75 -
76 -## React Nodes
77 -
78 -A `ReactNode` can be either:
79 -
80 -- `ReactElement`
81 -- `string` (aka `ReactText`)
82 -- `number` (aka `ReactText`)
83 -- Array of `ReactNode`s (aka `ReactFragment`)
84 -
85 -These are used as properties of other `ReactElement`s to represent children. Effectively they create a tree of `ReactElement`s.
86 -
87 -
88 -## React Components
89 -
90 -You can use React using only `ReactElement`s but to really take advantage of React, you'll want to use `ReactComponent`s to create encapsulations with embedded state.
91 -
92 -A `ReactComponent` Class is simply just a JavaScript class (or "constructor function").
93 -
94 -```javascript
95 -var MyComponent = React.createClass({
96 - render: function() {
97 - ...
98 - }
99 -});
100 -```
101 -
102 -When this constructor is invoked it is expected to return an object with at least a `render` method on it. This object is referred to as a `ReactComponent`.
103 -
104 -```javascript
105 -var component = new MyComponent(props); // never do this
106 -```
107 -
108 -Other than for testing, you would normally *never* call this constructor yourself. React calls it for you.
109 -
110 -Instead, you pass the `ReactComponent` Class to `createElement` you get a `ReactElement`.
111 -
112 -```javascript
113 -var element = React.createElement(MyComponent);
114 -```
115 -
116 -OR using JSX:
117 -
118 -```javascript
119 -var element = <MyComponent />;
120 -```
121 -
122 -When this is passed to `ReactDOM.render`, React will call the constructor for you and create a `ReactComponent`, which is returned.
123 -
124 -```javascript
125 -var component = ReactDOM.render(element, document.getElementById('example'));
126 -```
127 -
128 -If you keep calling `ReactDOM.render` with the same type of `ReactElement` and the same container DOM `Element` it always returns the same instance. This instance is stateful.
129 -
130 -```javascript
131 -var componentA = ReactDOM.render(<MyComponent />, document.getElementById('example'));
132 -var componentB = ReactDOM.render(<MyComponent />, document.getElementById('example'));
133 -componentA === componentB; // true
134 -```
135 -
136 -This is why you shouldn't construct your own instance. Instead, `ReactElement` is a virtual `ReactComponent` before it gets constructed. An old and new `ReactElement` can be compared to see if a new `ReactComponent` instance should be created or if the existing one should be reused.
137 -
138 -The `render` method of a `ReactComponent` is expected to return another `ReactElement`. This allows these components to be composed. Ultimately the render resolves into `ReactElement` with a `string` tag which instantiates a DOM `Element` instance and inserts it into the document.
139 -
140 -React 0.14 introduced [stateless functional components](/react/blog/2015/10/07/react-v0.14.html#stateless-functional-components) as an alternative way of defining components. Instead of being a class, it is a simple function that accepts props and is expected to return a `ReactElement`.
141 -
142 -## Formal Type Definitions
143 -
144 -### Entry Point
145 -
146 -```
147 -ReactDOM.render = (ReactElement, HTMLElement | SVGElement) => ReactComponent;
148 -```
149 -
150 -### Nodes and Elements
151 -
152 -```
153 -type ReactNode = ReactElement | ReactFragment | ReactText;
154 -
155 -type ReactElement = ReactComponentElement | ReactDOMElement;
156 -
157 -type ReactDOMElement = {
158 - type : string,
159 - props : {
160 - children : ReactNodeList,
161 - className : string,
162 - etc.
163 - },
164 - key : string | boolean | number | null,
165 - ref : string | null
166 -};
167 -
168 -type ReactComponentElement<TProps> = {
169 - type : ReactClass<TProps> | ReactFunctionalComponent<TProps>,
170 - props : TProps,
171 - key : string | boolean | number | null,
172 - ref : string | null
173 -};
174 -
175 -type ReactFragment = Array<ReactNode | ReactEmpty>;
176 -
177 -type ReactNodeList = ReactNode | ReactEmpty;
178 -
179 -type ReactText = string | number;
180 -
181 -type ReactEmpty = null | undefined | boolean;
182 -```
183 -
184 -### Classes and Components
185 -
186 -```
187 -type ReactClass<TProps> = (TProps) => ReactComponent<TProps>;
188 -
189 -type ReactComponent<TProps> = {
190 - props : TProps,
191 - render : () => ReactElement
192 -};
193 -
194 -type ReactFunctionalComponent<TProps> = (TProps) => ReactElement;
195 -```
196 -
docs/docs/ref-10-glossary.zh-CN.md deleted
-193
@@ -1,193 +0,0 @@
1 ----
2 -id: glossary-zh-CN
3 -title: React (虚拟) DOM 术语
4 -permalink: docs/glossary-zh-CN.html
5 -prev: webcomponents-zh-CN.html
6 ----
7 -
8 -在 React 的术语中,有五个要重点区分的核心类型:
9 -
10 -- [ReactElement / ReactElement Factory](#react-elementsreact-元素)
11 -- [ReactNode](#react-nodes)
12 -- [ReactComponent / ReactComponent Class](#react-components)
13 -
14 -## React Elements(React 元素)
15 -
16 -React里的首要类型是 `ReactElement`.它有四个 properties:`type`, `props`, `key` 和 `ref`.它没有方法,在 prototype 上什么也没有.
17 -
18 -你可以通过 `React.createElement` 来创建这些对象.
19 -
20 -```javascript
21 -var root = React.createElement('div');
22 -```
23 -
24 -要渲染一个新的树到DOM上,你创建 `ReactElement`s 并传递他们到 `ReactDOM.render` 伴随着一个标准的 DOM `Element` (`HTMLElement` 或 `SVGElement`).`ReactElement`s 不要与 DOM `Element`s 混淆.`ReactElement` 是一个轻的,有状态的,不可变的,虚拟的DOM `Element` 的表达.它是一个虚拟 DOM.
25 -
26 -```javascript
27 -ReactDOM.render(root, document.getElementById('example'));
28 -```
29 -
30 -要给一个DOM元素添加 properties,传递一个properties 对象作为第二个参数,第三个参数传递子级.
31 -
32 -```javascript
33 -var child = React.createElement('li', null, 'Text Content');
34 -var root = React.createElement('ul', { className: 'my-list' }, child);
35 -ReactDOM.render(root, document.getElementById('example'));
36 -```
37 -
38 -如果你使用 React JSX,这些`ReactElement`s 已经为你创建了.所以 这是等价的:
39 -
40 -```javascript
41 -var root = <ul className="my-list">
42 - <li>Text Content</li>
43 - </ul>;
44 -ReactDOM.render(root, document.getElementById('example'));
45 -```
46 -
47 -### Factories(工厂)
48 -
49 -`ReactElement`-工厂 是一个产生特定 `type` property的 `ReactElement` 的函数.React有一个为你内建的辅助工具来创建工厂.它想这样起作用:
50 -
51 -```javascript
52 -function createFactory(type) {
53 - return React.createElement.bind(null, type);
54 -}
55 -```
56 -
57 -它允许你创建一个方便的速记 来代替每次输入 `React.createElement('div')` .
58 -
59 -```javascript
60 -var div = React.createFactory('div');
61 -var root = div({ className: 'my-div' });
62 -ReactDOM.render(root, document.getElementById('example'));
63 -```
64 -
65 -React 已经具备用于常用 HTML tags的内建工厂
66 -
67 -```javascript
68 -var root = React.DOM.ul({ className: 'my-list' },
69 - React.DOM.li(null, 'Text Content')
70 - );
71 -```
72 -
73 -如果你使用JSX 你没有必要使用工厂.JSX已经为创建 `ReactElement`s 提供了一个 方便的速记.
74 -
75 -
76 -## React Nodes
77 -
78 -一个 `ReactNode` 可以是:
79 -
80 -- `ReactElement`
81 -- `string` (aka `ReactText`)
82 -- `number` (aka `ReactText`)
83 -- Array of `ReactNode`s (aka `ReactFragment`)
84 -
85 -他们被用作其他`ReactElement`s的properties来表示子级.事实上他们创建了一个 `ReactElement`s 的树.
86 -
87 -
88 -## React Components
89 -
90 -你可以使用 React只使用`ReactElement`s 但是要真正利用React,你将要使用 `ReactComponent`s 来创建内嵌 state 的封装.
91 -
92 -一个 `ReactComponent` 类就是一个 JavaScript 类 (或者 "constructor function").
93 -
94 -```javascript
95 -var MyComponent = React.createClass({
96 - render: function() {
97 - ...
98 - }
99 -});
100 -```
101 -
102 -当这个构造函数被调用,期望返回一个至少有一个 `render` 方法的对象.这个对象被称为一个 `ReactComponent`.
103 -
104 -```javascript
105 -var component = new MyComponent(props); // never do this
106 -```
107 -
108 -与测试不同,你可能通常 *绝不会* 亲自调用这个构造函数.React 为你调用它.
109 -
110 -作为替代,你传递 `ReactComponent` 类到 `createElement`,你得到一个 `ReactElement`.
111 -
112 -```javascript
113 -var element = React.createElement(MyComponent);
114 -```
115 -
116 -或者用 JSX:
117 -
118 -```javascript
119 -var element = <MyComponent />;
120 -```
121 -
122 -当这个被传给 `ReactDOM.render`,React 会为你调用构造函数并创建一个 `ReactComponent`,返回给你.
123 -
124 -```javascript
125 -var component = ReactDOM.render(element, document.getElementById('example'));
126 -```
127 -
128 -如果你保持用相同类型的 `ReactElement` 和相同的DOM `Element`容器调用 `ReactDOM.render` ,它总是会返回相同的实例.这个实例是状态化的.
129 -
130 -```javascript
131 -var componentA = ReactDOM.render(<MyComponent />, document.getElementById('example'));
132 -var componentB = ReactDOM.render(<MyComponent />, document.getElementById('example'));
133 -componentA === componentB; // true
134 -```
135 -
136 -这就是为什么你不应该构造你自己的实例.作为替代,`ReactElement` 在它被构造以前 是一个虚拟的 `ReactComponent`.一个老的和新的`ReactElement` 可以被比较来判断 一个新的 `ReactComponent` 实例是否需要被创建或者已经存在的是否应该被重用.
137 -
138 - `ReactComponent` 的 `render` 方法被期望返回另一个 `ReactElement`.这允许这些组件被结构化.最后,渲染分解为 带着一个 `string` tag的`ReactElement`,它实例化一个 DOM `Element` 实例并把它插入document里.
139 -
140 -
141 -## Formal Type Definitions
142 -
143 -### Entry Point
144 -
145 -```
146 -ReactDOM.render = (ReactElement, HTMLElement | SVGElement) => ReactComponent;
147 -```
148 -
149 -### Nodes and Elements
150 -
151 -```
152 -type ReactNode = ReactElement | ReactFragment | ReactText;
153 -
154 -type ReactElement = ReactComponentElement | ReactDOMElement;
155 -
156 -type ReactDOMElement = {
157 - type : string,
158 - props : {
159 - children : ReactNodeList,
160 - className : string,
161 - etc.
162 - },
163 - key : string | boolean | number | null,
164 - ref : string | null
165 -};
166 -
167 -type ReactComponentElement<TProps> = {
168 - type : ReactClass<TProps>,
169 - props : TProps,
170 - key : string | boolean | number | null,
171 - ref : string | null
172 -};
173 -
174 -type ReactFragment = Array<ReactNode | ReactEmpty>;
175 -
176 -type ReactNodeList = ReactNode | ReactEmpty;
177 -
178 -type ReactText = string | number;
179 -
180 -type ReactEmpty = null | undefined | boolean;
181 -```
182 -
183 -### Classes and Components
184 -
185 -```
186 -type ReactClass<TProps> = (TProps) => ReactComponent<TProps>;
187 -
188 -type ReactComponent<TProps> = {
189 - props : TProps,
190 - render : () => ReactElement
191 -};
192 -```
193 -
docs/docs/reference-dom-elements.md new
+172
@@ -0,0 +1,172 @@
1 +---
2 +id: dom-elements
3 +title: DOM Elements
4 +layout: docs
5 +category: Reference
6 +permalink: docs/dom-elements.html
7 +redirect_from: "/docs/tags-and-attributes.html"
8 +redirect_from: "/docs/dom-differences.html"
9 +redirect_from: "/docs/special-non-dom-attributes.html"
10 +redirect_from: "/tips/inline-styles.html"
11 +redirect_from: "/tips/style-props-value-px.html"
12 +redirect_from: "/tips/dangerously-set-inner-html.html"
13 +---
14 +
15 +React implements a browser-independent DOM system for performance and cross-browser compatibility. We took the opportunity to clean up a few rough edges in browser DOM implementations.
16 +
17 +In React, all DOM properties and attributes (including event handlers) should be camelCased. For example, the HTML attribute `tabindex` corresponds to the attribute `tabIndex` in React. The exception is `aria-*` and `data-*` attributes, which should be lowercased.
18 +
19 +## Differences In Attributes
20 +
21 +There are a number of attributes that work differently between React and HTML:
22 +
23 +### checked
24 +
25 +The `checked` attribute is supported by `<input>` components of type `checkbox` or `radio`. You can use it to set whether the component is checked. This is useful for building controlled components. `defaultChecked` is the uncontrolled equivalent, which sets whether the component is checked when it is first mounted.
26 +
27 +### className
28 +
29 +To specify a CSS class, use the `className` attribute. This applies to all regular DOM and SVG elements like `<div>`, `<a>`, and others.
30 +
31 +If you use React with Web Components (which is uncommon), use the `class` attribute instead.
32 +
33 +### dangerouslySetInnerHTML
34 +
35 +`dangerouslySetInnerHTML` is React's replacement for using `innerHTML` in the browser DOM. In general, setting HTML from code is risky because it's easy to inadvertently expose your users to a [cross-site scripting (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting) attack. So, you can set HTML directly from React, but you have to type out `dangerouslySetInnerHTML` and pass an object with a `__html` key, to remind yourself that it's dangerous. For example:
36 +
37 +```js
38 +function createMarkup() {
39 + return {__html: 'First &middot; Second'};
40 +}
41 +
42 +function MyComponent() {
43 + return <div dangerouslySetInnerHTML={createMarkup()} />;
44 +}
45 +```
46 +
47 +### htmlFor
48 +
49 +Since `for` is a reserved word in JavaScript, React elements use `htmlFor` instead.
50 +
51 +### onChange
52 +
53 +The `onChange` event behaves as you would expect it to: whenever a form field is changed, this event is fired. We intentionally do not use the existing browser behavior because `onChange` is a misnomer for its behavior and React relies on this event to handle user input in real time.
54 +
55 +### selected
56 +
57 +The `selected` attribute is supported by `<option>` components. You can use it to set whether the component is selected. This is useful for building controlled components.
58 +
59 +### style
60 +
61 +The `style` attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM `style` JavaScript property, is more efficient, and prevents XSS security holes. For example:
62 +
63 +```js
64 +const divStyle = {
65 + color: 'blue',
66 + backgroundImage: 'url(' + imgUrl + ')',
67 +};
68 +
69 +function HelloWorldComponent() {
70 + return <div style={divStyle}>Hello World!</div>;
71 +}
72 +```
73 +
74 +Note that styles are not autoprefixed. To support older browsers, you need to supply corresponding style properties:
75 +
76 +```js
77 +const divStyle = {
78 + WebkitTransition: 'all', // note the capital 'W' here
79 + msTransition: 'all' // 'ms' is the only lowercase vendor prefix
80 +};
81 +
82 +function ComponentWithTransition() {
83 + return <div style={divStyle}>This should work cross-browser</div>;
84 +}
85 +```
86 +
87 +Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes from JS (e.g. `node.style.backgroundImage`). Vendor prefixes [other than `ms`](http://www.andismith.com/blog/2012/02/modernizr-prefixed/) should begin with a capital letter. This is why `WebkitTransition` has an uppercase "W".
88 +
89 +### suppressContentEditableWarning
90 +
91 +Normally, there is a warning when an element with children is also marked as `contentEditable`, because it won't work. This attribute suppresses that warning. Don't use this unless you are building a library like [Draft.js](https://facebook.github.io/draft-js/) that manages `contentEditable` manually.
92 +
93 +### value
94 +
95 +The `value` attribute is supported by `<input>` and `<textarea>` components. You can use it to set the value of the component. This is useful for building controlled components. `defaultValue` is the uncontrolled equivalent, which sets the value of the component when it is first mounted.
96 +
97 +## All Supported HTML Attributes
98 +
99 +React supports all `data-*` and `aria-*` attributes as well as these attributes:
100 +
101 +```
102 +accept acceptCharset accessKey action allowFullScreen allowTransparency alt
103 +async autoComplete autoFocus autoPlay capture cellPadding cellSpacing challenge
104 +charSet checked cite classID className colSpan cols content contentEditable
105 +contextMenu controls coords crossOrigin data dateTime default defer dir
106 +disabled download draggable encType form formAction formEncType formMethod
107 +formNoValidate formTarget frameBorder headers height hidden high href hrefLang
108 +htmlFor httpEquiv icon id inputMode integrity is keyParams keyType kind label
109 +lang list loop low manifest marginHeight marginWidth max maxLength media
110 +mediaGroup method min minLength multiple muted name noValidate nonce open
111 +optimum pattern placeholder poster preload profile radioGroup readOnly rel
112 +required reversed role rowSpan rows sandbox scope scoped scrolling seamless
113 +selected shape size sizes span spellCheck src srcDoc srcLang srcSet start step
114 +style summary tabIndex target title type useMap value width wmode wrap
115 +```
116 +
117 +These RDFa attributes are supported (several RDFa attributes overlap with standard HTML attributes and thus are excluded from this list):
118 +
119 +```
120 +about datatype inlist prefix property resource typeof vocab
121 +```
122 +
123 +In addition, the following non-standard attributes are supported:
124 +
125 +- `autoCapitalize autoCorrect` for Mobile Safari.
126 +- `color` for `<link rel="mask-icon" />` in Safari.
127 +- `itemProp itemScope itemType itemRef itemID` for [HTML5 microdata](http://schema.org/docs/gs.html).
128 +- `security` for older versions of Internet Explorer.
129 +- `unselectable` for Internet Explorer.
130 +- `results autoSave` for WebKit/Blink input fields of type `search`.
131 +
132 +## All Supported SVG Attributes
133 +
134 +React supports these SVG attributes:
135 +
136 +```
137 +accentHeight accumulate additive alignmentBaseline allowReorder alphabetic
138 +amplitude arabicForm ascent attributeName attributeType autoReverse azimuth
139 +baseFrequency baseProfile baselineShift bbox begin bias by calcMode capHeight
140 +clip clipPath clipPathUnits clipRule colorInterpolation
141 +colorInterpolationFilters colorProfile colorRendering contentScriptType
142 +contentStyleType cursor cx cy d decelerate descent diffuseConstant direction
143 +display divisor dominantBaseline dur dx dy edgeMode elevation enableBackground
144 +end exponent externalResourcesRequired fill fillOpacity fillRule filter
145 +filterRes filterUnits floodColor floodOpacity focusable fontFamily fontSize
146 +fontSizeAdjust fontStretch fontStyle fontVariant fontWeight format from fx fy
147 +g1 g2 glyphName glyphOrientationHorizontal glyphOrientationVertical glyphRef
148 +gradientTransform gradientUnits hanging horizAdvX horizOriginX ideographic
149 +imageRendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLength
150 +kerning keyPoints keySplines keyTimes lengthAdjust letterSpacing lightingColor
151 +limitingConeAngle local markerEnd markerHeight markerMid markerStart
152 +markerUnits markerWidth mask maskContentUnits maskUnits mathematical mode
153 +numOctaves offset opacity operator order orient orientation origin overflow
154 +overlinePosition overlineThickness paintOrder panose1 pathLength
155 +patternContentUnits patternTransform patternUnits pointerEvents points
156 +pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits
157 +r radius refX refY renderingIntent repeatCount repeatDur requiredExtensions
158 +requiredFeatures restart result rotate rx ry scale seed shapeRendering slope
159 +spacing specularConstant specularExponent speed spreadMethod startOffset
160 +stdDeviation stemh stemv stitchTiles stopColor stopOpacity
161 +strikethroughPosition strikethroughThickness string stroke strokeDasharray
162 +strokeDashoffset strokeLinecap strokeLinejoin strokeMiterlimit strokeOpacity
163 +strokeWidth surfaceScale systemLanguage tableValues targetX targetY textAnchor
164 +textDecoration textLength textRendering to transform u1 u2 underlinePosition
165 +underlineThickness unicode unicodeBidi unicodeRange unitsPerEm vAlphabetic
166 +vHanging vIdeographic vMathematical values vectorEffect version vertAdvY
167 +vertOriginX vertOriginY viewBox viewTarget visibility widths wordSpacing
168 +writingMode x x1 x2 xChannelSelector xHeight xlinkActuate xlinkArcrole
169 +xlinkHref xlinkRole xlinkShow xlinkTitle xlinkType xmlBase xmlLang xmlSpace
170 +y y1 y2 yChannelSelector z zoomAndPan
171 +
172 +```
docs/docs/reference-events.md renamed
+41 -7
@@ -1,12 +1,14 @@
1 ---
2 id: events
3 -title: Event System
3 +title: SyntheticEvent
4 permalink: docs/events.html
5 -prev: tags-and-attributes.html
6 -next: dom-differences.html
5 +layout: docs
6 +category: Reference
7 ---
8
9 -## SyntheticEvent
9 +This reference guide documents the `SyntheticEvent` wrapper that forms part of React's Event System. See the [Handling Events](/react/docs/handling-events.html) guide to learn more.
10 +
11 +## Overview
12
13 Your event handlers will be passed instances of `SyntheticEvent`, a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event, including `stopPropagation()` and `preventDefault()`, except the events work identically across all browsers.
14
@@ -33,7 +35,7 @@ string type
35 >
36 > As of v0.14, returning `false` from an event handler will no longer stop event propagation. Instead, `e.stopPropagation()` or `e.preventDefault()` should be triggered manually, as appropriate.
37
36 -## Event pooling
38 +### Event pooling
39
40 The `SyntheticEvent` is pooled. This means that the `SyntheticEvent` object will be reused and all properties will be nullified after the event callback has been invoked.
41 This is for performance reasons.
@@ -68,6 +70,24 @@ React normalizes events so that they have consistent properties across different
70
71 The event handlers below are triggered by an event in the bubbling phase. To register an event handler for the capture phase, append `Capture` to the event name; for example, instead of using `onClick`, you would use `onClickCapture` to handle the click event in the capture phase.
72
73 +- [Clipboard Events](#clipboard-events)
74 +- [Composition Events](#composition-events)
75 +- [Keyboard Events](#keyboard-events)
76 +- [Focus Events](#focus-events)
77 +- [Form Events](#form-events)
78 +- [Mouse Events](#mouse-events)
79 +- [Selection Events](#selection-events)
80 +- [Touch Events](#touch-events)
81 +- [UI Events](#ui-events)
82 +- [Wheel Events](#wheel-events)
83 +- [Media Events](#media-events)
84 +- [Image Events](#image-events)
85 +- [Animation Events](#animation-events)
86 +- [Transition Events](#transition-events)
87 +
88 +* * *
89 +
90 +## Reference
91
92 ### Clipboard Events
93
@@ -83,6 +103,7 @@ Properties:
103 DOMDataTransfer clipboardData
104 ```
105
106 +* * *
107
108 ### Composition Events
109
@@ -99,6 +120,7 @@ string data
120
121 ```
122
123 +* * *
124
125 ### Keyboard Events
126
@@ -125,6 +147,7 @@ boolean shiftKey
147 number which
148 ```
149
150 +* * *
151
152 ### Focus Events
153
@@ -134,14 +157,15 @@ Event names:
157 onFocus onBlur
158 ```
159
160 +These focus events work on all elements in the React DOM, not just form elements.
161 +
162 Properties:
163
164 ```javascript
165 DOMEventTarget relatedTarget
166 ```
167
143 -These focus events work on all elements in the React DOM, not just form elements.
144 -
168 +* * *
169
170 ### Form Events
171
@@ -153,6 +177,7 @@ onChange onInput onSubmit
177
178 For more information about the onChange event, see [Forms](/react/docs/forms.html).
179
180 +* * *
181
182 ### Mouse Events
183
@@ -185,6 +210,7 @@ number screenY
210 boolean shiftKey
211 ```
212
213 +* * *
214
215 ### Selection Events
216
@@ -194,6 +220,7 @@ Event names:
220 onSelect
221 ```
222
223 +* * *
224
225 ### Touch Events
226
@@ -216,6 +243,7 @@ DOMTouchList targetTouches
243 DOMTouchList touches
244 ```
245
246 +* * *
247
248 ### UI Events
249
@@ -232,6 +260,7 @@ number detail
260 DOMAbstractView view
261 ```
262
263 +* * *
264
265 ### Wheel Events
266
@@ -250,6 +279,7 @@ number deltaY
279 number deltaZ
280 ```
281
282 +* * *
283
284 ### Media Events
285
@@ -262,6 +292,7 @@ onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend
292 onTimeUpdate onVolumeChange onWaiting
293 ```
294
295 +* * *
296
297 ### Image Events
298
@@ -271,6 +302,7 @@ Event names:
302 onLoad onError
303 ```
304
305 +* * *
306
307 ### Animation Events
308
@@ -288,6 +320,7 @@ string pseudoElement
320 float elapsedTime
321 ```
322
323 +* * *
324
325 ### Transition Events
326
@@ -304,3 +337,4 @@ string propertyName
337 string pseudoElement
338 float elapsedTime
339 ```
340 +
docs/docs/reference-pure-render-mixin.md renamed
+7 -3
@@ -1,12 +1,16 @@
1 ---
2 id: pure-render-mixin
3 title: PureRenderMixin
4 +layout: docs
5 +category: Reference
6 permalink: docs/pure-render-mixin.html
5 -prev: update.html
6 -next: perf.html
7 ---
8
9 -If your React component's render function is "pure" (in other words, it renders the same result given the same props and state), you can use this mixin for a performance boost in some cases.
9 +> Note
10 +
11 +> The `PureRenderMixin` mixin predates `React.PureComponent`. This reference doc is provided for legacy purposes, and you should consider using [`React.PureComponent`](/react/docs/component-api.html#react.purecomponent) instead.
12 +
13 +If your React component's render function renders the same result given the same props and state, you can use this mixin for a performance boost in some cases.
14
15 Example:
16
docs/docs/reference-react-component.md new
+351
@@ -0,0 +1,351 @@
1 +---
2 +id: react-component
3 +title: React.Component
4 +layout: docs
5 +category: Reference
6 +permalink: docs/react-component.html
7 +redirect_from: "/docs/component-api.html"
8 +redirect_from: "/docs/component-specs.html"
9 +redirect_from: "/tips/componentWillReceiveProps-not-triggered-after-mounting.html"
10 +redirect_from: "/tips/dom-event-listeners.html"
11 +redirect_from: "/tips/initial-ajax.html"
12 +redirect_from: "/tips/use-react-with-other-libraries.html"
13 +---
14 +
15 +[Components](/react/docs/components-and-props.html) let you split the UI into independent, reusable pieces, and think about each piece in isolation. `React.Component` is provided by [`React`](/react/docs/react-api.html).
16 +
17 +## Overview
18 +
19 +`React.Component` is an abstract base class, so it rarely makes sense to refer to `React.Component` directly. Instead, you will typically subclass it, and define at least a [`render()`](#render) method.
20 +
21 +Normally you would define a React component as a plain [JavaScript class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes):
22 +
23 +```javascript
24 +class Greeting extends React.Component {
25 + render() {
26 + return <h1>Hello, {this.props.name}</h1>;
27 + }
28 +}
29 +```
30 +
31 +If you don't use ES6 yet, you may use the [`React.createClass`](/react/docs/react-api.html#createclass) helper instead. Take a look at [Using React without ES6](/react/docs/react-without-es6.html) to learn more.
32 +
33 +### The Component Lifecycle
34 +
35 +Each component has several "lifecycle methods" that you can override to run code at particular times in the process. Methods prefixed with **`will`** are called right before something happens, and methods prefixed with **`did`** are called right after something happens.
36 +
37 +#### Mounting
38 +
39 +These methods are called when an instance of a component is being created and inserted into the DOM:
40 +
41 +- [`constructor()`](#constructor)
42 +- [`componentWillMount()`](#componentwillmount)
43 +- [`render()`](#render)
44 +- [`componentDidMount()`](#componentdidmount)
45 +
46 +#### Updating
47 +
48 +An update can be caused by changes to props or state. These methods are called when a component is being re-rendered:
49 +
50 +- [`componentWillReceiveProps()`](#componentwillreceiveprops)
51 +- [`shouldComponentUpdate()`](#shouldcomponentupdate)
52 +- [`componentWillUpdate()`](#componentwillupdate)
53 +- [`render()`](#render)
54 +- [`componentDidUpdate()`](#componentdidupdate)
55 +
56 +#### Unmounting
57 +
58 +This method is called when a component is being removed from the DOM:
59 +
60 +- [`componentWillUnmount()`](#componentwillunmount)
61 +
62 +### Other APIs
63 +
64 +Each component also provides some other APIs:
65 +
66 + - [`setState()`](#setstate)
67 + - [`forceUpdate()`](#forceupdate)
68 +
69 +### Class Properties
70 +
71 + - [`defaultProps`](#defaultprops)
72 + - [`displayName`](#displayName)
73 + - [`propTypes`](#proptypes)
74 +
75 +### Instance Properties
76 +
77 + - [`props`](#props)
78 + - [`state`](#state)
79 +
80 +* * *
81 +
82 +## Reference
83 +
84 +### `render()`
85 +
86 +```javascript
87 +render()
88 +```
89 +
90 +The `render()` method is required.
91 +
92 +When called, it should examine `this.props` and `this.state` and return a single React element. This element can be either a representation of a native DOM component, such as `<div />`, or another composite component that you've defined yourself.
93 +
94 +You can also return `null` or `false` to indicate that you don't want anything rendered. When returning `null` or `false`, `ReactDOM.findDOMNode(this)` will return `null`.
95 +
96 +The `render()` function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not directly interact with the browser. If you need to interact with the browser, perform your work in `componentDidMount()` or the other lifecycle methods instead. Keeping `render()` pure makes components easier to think about.
97 +
98 +> Note
99 +>
100 +> `render()` will not be invoked if [`shouldComponentUpdate()`](#shouldcomponentupdate) returns false.
101 +
102 +* * *
103 +
104 +### `constructor()`
105 +
106 +```javascript
107 +constructor(props)
108 +```
109 +
110 +The constructor for a React component is called before it is mounted. When implementing the constructor for a `React.Component` subclass, you should call `super(props)` before any other statement. Otherwise, `this.props` will be undefined in the constructor, which can lead to bugs.
111 +
112 +The constructor is the right place to initialize state. If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component.
113 +
114 +It's okay to initialize state based on props if you know what you're doing. Here's an example of a valid `React.Component` subclass constructor:
115 +
116 +```js
117 +constructor(props) {
118 + super(props);
119 + this.state = {
120 + color: props.initialColor
121 + };
122 +}
123 +```
124 +
125 +Beware of this pattern, as it effectively "forks" the props and can lead to bugs. Instead of syncing props to state, you often want to [lift the state up](/react/docs/lifting-state-up.html).
126 +
127 +If you "fork" props by using them for state, you might also want to implement [`componentWillReceiveProps(nextProps)`](#componentwillreceiveprops) to keep the state up-to-date with them. But lifting state up is often easier and less bug-prone.
128 +
129 +* * *
130 +
131 +### `componentWillMount()`
132 +
133 +```javascript
134 +componentWillMount()
135 +```
136 +
137 +`componentWillMount()` is invoked immediately before mounting occurs. It is called before `render()`, therefore setting state in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.
138 +
139 +This is the only lifecycle hook called on server rendering. Generally, we recommend using the `constructor()` instead.
140 +
141 +* * *
142 +
143 +### `componentDidMount()`
144 +
145 +```javascript
146 +componentDidMount()
147 +```
148 +
149 +`componentDidMount()` is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.
150 +
151 +* * *
152 +
153 +### `componentWillReceiveProps()`
154 +
155 +```javascript
156 +componentWillReceiveProps(nextProps)
157 +```
158 +
159 +`componentWillReceiveProps()` is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare `this.props` and `nextProps` and perform state transitions using `this.setState()` in this method.
160 +
161 +Note that React may call this method even if the props have not changed, so make sure to compare the current and next values if you only want to handle changes. This may occur when the parent component causes your component to re-render.
162 +
163 +`componentWillReceiveProps()` is not invoked if you just call `this.setState()`
164 +
165 +* * *
166 +
167 +### `shouldComponentUpdate()`
168 +
169 +```javascript
170 +shouldComponentUpdate(nextProps, nextState)
171 +```
172 +
173 +Use `shouldComponentUpdate()` to let React know if a component's output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.
174 +
175 +`shouldComponentUpdate()` is invoked before rendering when new props or state are being received. Defaults to `true` This method is not called for the initial render or when `forceUpdate()` is used.
176 +
177 +Returning `false` does not prevent child components from re-rendering when *their* state changes.
178 +
179 +Currently, if `shouldComponentUpdate()` returns `false`, then [`componentWillUpdate()`](#componentwillupdate), [`render()`](#render), and [`componentDidUpdate()`](#componentdidupdate) will not be invoked. Note that in the future React may treat `shouldComponentUpdate()` as a hint rather than a strict directive, and returning `false` may still result in a re-rendering of the component.
180 +
181 +If you determine a specific component is slow after profiling, you may change it to inherit from [`React.PureComponent`](/react/docs/react-api.html#react.purecomponent) which implements `shouldComponentUpdate()` with a shallow prop and state comparison. If you are confident you want to write it by hand, you may compare `this.props` with `nextProps` and `this.state` with `nextState` and return `false` to tell React the update can be skipped.
182 +
183 +* * *
184 +
185 +### `componentWillUpdate()`
186 +
187 +```javascript
188 +componentWillUpdate(nextProps, nextState)
189 +```
190 +
191 +`componentWillUpdate()` is invoked immediately before rendering when new props or state are being received. Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render.
192 +
193 +Note that you cannot call `this.setState()` here. If you need to update state in response to a prop change, use `componentWillReceiveProps()` instead.
194 +
195 +> Note
196 +>
197 +> `componentWillUpdate()` will not be invoked if [`shouldComponentUpdate()`](#shouldcomponentupdate) returns false.
198 +
199 +* * *
200 +
201 +### `componentDidUpdate()`
202 +
203 +```javascript
204 +componentDidUpdate(prevProps, prevState)
205 +```
206 +
207 +`componentDidUpdate()` is invoked immediately after updating occurs. This method is not called for the initial render.
208 +
209 +Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).
210 +
211 +> Note
212 +>
213 +> `componentDidUpdate()` will not be invoked if [`shouldComponentUpdate()`](#shouldcomponentupdate) returns false.
214 +
215 +* * *
216 +
217 +### `componentWillUnmount()`
218 +
219 +```javascript
220 +componentWillUnmount()
221 +```
222 +
223 +`componentWillUnmount()` is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any DOM elements that were created in `componentDidMount`
224 +
225 +* * *
226 +
227 +### `setState()`
228 +
229 +```javascript
230 +setState(nextState, callback)
231 +```
232 +
233 +Performs a shallow merge of nextState into current state. This is the primary method you use to trigger UI updates from event handlers and server request callbacks.
234 +
235 +The first argument can be an object (containing zero or more keys to update) or a function (of state and props) that returns an object containing keys to update.
236 +
237 +Here is the simple object usage:
238 +
239 +```javascript
240 +this.setState({mykey: 'my new value'});
241 +```
242 +
243 +It's also possible to pass a function with the signature `function(state, props) => newState`. This enqueues an atomic update that consults the previous value of state and props before setting any values. For instance, suppose we wanted to increment a value in state by `props.step`:
244 +
245 +```javascript
246 +this.setState((prevState, props) => {
247 + return {myInteger: prevState.myInteger + props.step};
248 +});
249 +```
250 +
251 +The second parameter is an optional callback function that will be executed once `setState` is completed and the component is re-rendered. Generally we recommend using `componentDidUpdate()` for such logic instead.
252 +
253 +`setState()` does not immediately mutate `this.state` but creates a pending state transition. Accessing `this.state` after calling this method can potentially return the existing value.
254 +
255 +There is no guarantee of synchronous operation of calls to `setState` and calls may be batched for performance gains.
256 +
257 +`setState()` will always lead to a re-render unless `shouldComponentUpdate()` returns `false`. If mutable objects are being used and conditional rendering logic cannot be implemented in `shouldComponentUpdate()`, calling `setState()` only when the new state differs from the previous state will avoid unnecessary re-renders.
258 +
259 +* * *
260 +
261 +### `forceUpdate()`
262 +
263 +```javascript
264 +component.forceUpdate(callback)
265 +```
266 +
267 +By default, when your component's state or props change, your component will re-render. If your `render()` method depends on some other data, you can tell React that the component needs re-rendering by calling `forceUpdate()`.
268 +
269 +Calling `forceUpdate()` will cause `render()` to be called on the component, skipping `shouldComponentUpdate()`. This will trigger the normal lifecycle methods for child components, including the `shouldComponentUpdate()` method of each child. React will still only update the DOM if the markup changes.
270 +
271 +Normally you should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()`.
272 +
273 +* * *
274 +
275 +## Class Properties
276 +
277 +### `defaultProps`
278 +
279 +`defaultProps` can be defined as a property on the component class itself, to set the default props for the class. This is used for undefined props, but not for null props. For example:
280 +
281 +```js
282 +class CustomButton extends React.Component {
283 + // ...
284 +}
285 +
286 +CustomButton.defaultProps = {
287 + color: 'blue'
288 +};
289 +```
290 +
291 +If `props.color` is not provided, it will be set by default to `'blue'`:
292 +
293 +```js
294 + render() {
295 + return <CustomButton /> ; // props.color will be set to blue
296 + }
297 +```
298 +
299 +If `props.color` is set to null, it will remain null:
300 +
301 +```js
302 + render() {
303 + return <CustomButton color={null} /> ; // props.color will remain null
304 + }
305 +```
306 +
307 +* * *
308 +
309 +### `displayName`
310 +
311 +The `displayName` string is used in debugging messages. JSX sets this value automatically; see [JSX in Depth](/react/docs/jsx-in-depth.html).
312 +
313 +* * *
314 +
315 +### `propTypes`
316 +
317 +`propTypes` can be defined as a property on the component class itself, to define what types the props should be. It should be a map from prop names to types as defined in [`React.PropTypes`](/react/docs/react-api.html#react.proptypes). In development mode, when an invalid value is provided for a prop, a warning will be shown in the JavaScript console. In production mode, `propTypes` checks are skipped for efficiency.
318 +
319 +For example, this code ensures that the `color` prop is a string:
320 +
321 +```js
322 +class CustomButton extends React.Component {
323 + // ...
324 +}
325 +
326 +CustomButton.propTypes = {
327 + name: React.PropTypes.string
328 +};
329 +```
330 +
331 +We recommend using [Flow](https://flowtype.org/) when possible, to get compile-time typechecking instead of runtime typechecking. [Flow has built-in support for React](https://flowtype.org/docs/react.html) so it's easy to run static analysis on a React app.
332 +
333 +* * *
334 +
335 +## Instance Properties
336 +
337 +### `props`
338 +
339 +`this.props` contains the props that were defined by the caller of this component. See [Components and Props](/react/docs/components-and-props.html) for an introduction to props.
340 +
341 +In particular, `this.props.children` is a special prop, typically defined by the child tags in the JSX expression rather than in the tag itself.
342 +
343 +### `state`
344 +
345 +The state contains data specific to this component that may change over time. The state is user-defined, and it should be a plain JavaScript object.
346 +
347 +If you don't use it in `render(), it shouldn't be on the state. For example, you can put timer IDs directly on the instance.
348 +
349 +See [State and Lifecycle](/react/docs/state-and-lifecycle.html) for more information about the state.
350 +
351 +Never mutate `this.state` directly, as calling `setState()` afterwards may replace the mutation you made. Treat `this.state` as if it were immutable.
docs/docs/reference-react-dom-server.md new
+40
@@ -0,0 +1,40 @@
1 +---
2 +id: react-dom-server
3 +title: ReactDOMServer
4 +layout: docs
5 +category: Reference
6 +permalink: docs/react-dom-server.html
7 +---
8 +
9 +If you use React as a script tag, these top-level APIs are available on the `ReactDOMServer` global. If you use ES6 with npm, you can write `import ReactDOMServer from 'react-dom/server'`. If you use ES5 with npm, you can write `var ReactDOMServer = require('react-dom/server')`.
10 +
11 +## Overview
12 +
13 +The `ReactDOMServer` class allows you to render your components on the server.
14 +
15 + - [`renderToString()`](#rendertostring)
16 + - [`renderToStaticMarkup()`](#rendertostaticmarkup)
17 +
18 +* * *
19 +
20 +## Reference
21 +
22 +### `renderToString()`
23 +
24 +```javascript
25 +ReactDOMServer.renderToString(element)
26 +```
27 +
28 +Render a React element to its initial HTML. This should only be used on the server. React will return an HTML string. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
29 +
30 +If you call [`ReactDOM.render()`](/react/docs/react-dom.html#render) on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
31 +
32 +* * *
33 +
34 +### `renderToStaticMarkup()`
35 +
36 +```javascript
37 +ReactDOMServer.renderToStaticMarkup(element)
38 +```
39 +
40 +Similar to [`renderToString`](#rendertostring), except this doesn't create extra DOM attributes such as `data-reactid`, that React uses internally. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save lots of bytes.
docs/docs/reference-react-dom.md new
+82
@@ -0,0 +1,82 @@
1 +---
2 +id: react-dom
3 +title: ReactDOM
4 +layout: docs
5 +category: Reference
6 +permalink: docs/react-dom.html
7 +---
8 +
9 +If you use React as a script tag, these top-level APIs are available on the `ReactDOM` global. If you use ES6 with npm, you can write `import ReactDOM from 'react-dom'`. If you use ES5 with npm, you can write `var ReactDOM = require('react-dom')`.
10 +
11 +## Overview
12 +
13 +The `react-dom` package provides DOM-specific methods that can be used at the top level of your app and as an escape hatch to get outside of the React model if you need to. Most of your components should not need to use this module.
14 +
15 +- [`render()`](#render)
16 +- [`unmountComponentAtNode()`](#unmountcomponentatnode)
17 +- [`findDOMNode()`](#finddomnode)
18 +
19 +### Browser Support
20 +
21 +React supports all popular browsers, including Internet Explorer 9 and above.
22 +
23 +> Note
24 +>
25 +> We don't support older browsers that don't support ES5 methods, but you may find that your apps do work in older browsers if polyfills such as [es5-shim and es5-sham](https://github.com/es-shims/es5-shim) are included in the page. You're on your own if you choose to take this path.
26 +
27 +* * *
28 +
29 +## Reference
30 +
31 +### `render()`
32 +
33 +```javascript
34 +ReactDOM.render(
35 + element,
36 + container,
37 + [callback]
38 +)
39 +```
40 +
41 +Render a React element into the DOM in the supplied `container` and return a [reference](/react/docs/more-about-refs.html) to the component (or returns `null` for [stateless components](/react/docs/components-and-props.html#functional-and-class-components).
42 +
43 +If the React element was previously rendered into `container`, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React element.
44 +
45 +If the optional callback is provided, it will be executed after the component is rendered or updated.
46 +
47 +> Note:
48 +>
49 +> `ReactDOM.render()` controls the contents of the container node you pass in. Any existing DOM elements inside are replaced when first called. Later calls use React’s DOM diffing algorithm for efficient updates.
50 +>
51 +> `ReactDOM.render()` does not modify the container node (only modifies the children of the container). It may be possible to insert a component to an existing DOM node without overwriting the existing children.
52 +>
53 +> `ReactDOM.render()` currently returns a reference to the root `ReactComponent` instance. However, using this return value is legacy
54 +> and should be avoided because future versions of React may render components asynchronously in some cases. If you need a reference to the root `ReactComponent` instance, the preferred solution is to attach a
55 +> [callback ref](/react/docs/more-about-refs.html#the-ref-callback-attribute) to the root element.
56 +
57 +* * *
58 +
59 +### `unmountComponentAtNode()`
60 +
61 +```javascript
62 +ReactDOM.unmountComponentAtNode(container)
63 +```
64 +
65 +Remove a mounted React component from the DOM and clean up its event handlers and state. If no component was mounted in the container, calling this function does nothing. Returns `true` if a component was unmounted and `false` if there was no component to unmount.
66 +
67 +* * *
68 +
69 +### `findDOMNode()`
70 +
71 +```javascript
72 +ReactDOM.findDOMNode(component)
73 +```
74 +If this component has been mounted into the DOM, this returns the corresponding native browser DOM element. This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements. **In most cases, you can attach a ref to the DOM node and avoid using `findDOMNode` at all.** When `render` returns `null` or `false`, `findDOMNode` returns `null`.
75 +
76 +> Note:
77 +>
78 +> `findDOMNode` is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction.
79 +>
80 +> `findDOMNode` only works on mounted components (that is, components that have been placed in the DOM). If you try to call this on a component that has not been mounted yet (like calling `findDOMNode()` in `render()` on a component that has yet to be created) an exception will be thrown.
81 +>
82 +> `findDOMNode` cannot be used on functional components.
docs/docs/reference-react.md new
+445
@@ -0,0 +1,445 @@
1 +---
2 +id: react-api
3 +title: React Top-Level API
4 +layout: docs
5 +category: Reference
6 +permalink: docs/react-api.html
7 +redirect_from: "/docs/reference.html"
8 +redirect_from: "/docs/clone-with-props.html"
9 +redirect_from: "/docs/top-level-api.html"
10 +redirect_from: "/docs/glossary.html"
11 +---
12 +
13 +`React` is the entry point to the React library. If you use React as a script tag, these top-level APIs are available on the `React` global. If you use ES6 with npm, you can write `import React from 'react'`. If you use ES5 with npm, you can write `var React = require('react')`.
14 +
15 +## Overview
16 +
17 +### Components
18 +
19 +React components let you split the UI into independent, reusable pieces, and think about each piece in isolation. React components can be defined by subclassing `React.Component` or `React.PureComponent`.
20 +
21 + - [`React.Component`](#react.component)
22 + - [`React.PureComponent`](#react.purecomponent)
23 +
24 +If you don't use ES6 classes, you may use this helper instead.
25 +
26 + - [`createClass()`](#react.createclass)
27 +
28 +### Creating React Elements
29 +
30 +We recommend [using JSX](/react/docs/introducing-jsx.html) to describe what your UI should look like. Each JSX element is just syntactic sugar for calling [`React.createElement()`](#createelement). You will not typically invoke the following methods directly if you are using JSX.
31 +
32 +- [`createElement()`](#createelement)
33 +- [`createFactory()`](#createfactory)
34 +
35 +See [Using React without JSX](/react/docs/react-without-jsx.html) for more information.
36 +
37 +### Transforming Elements
38 +
39 +`React` also provides some other APIs:
40 +
41 +- [`cloneElement()`](#cloneelement)
42 +- [`isValidElement()`](#isvalidelement)
43 +- [`React.Children`](#react.children)
44 +
45 +### Typechecking with PropTypes
46 +
47 +You can use `React.PropTypes` to run typechecking on the props for a component.
48 +
49 + - [`React.PropTypes`](#react.proptypes)
50 + - [`React.PropTypes.array`](#react.proptypes.array)
51 + - [`React.PropTypes.bool`](#react.proptypes.bool)
52 + - [`React.PropTypes.func`](#react.proptypes.func)
53 + - [`React.PropTypes.number`](#react.proptypes.number)
54 + - [`React.PropTypes.object`](#react.proptypes.object)
55 + - [`React.PropTypes.string`](#react.proptypes.string)
56 + - [`React.PropTypes.symbol`](#react.proptypes.symbol)
57 + - [`React.PropTypes.node`](#react.proptypes.node)
58 + - [`React.PropTypes.element`](#react.proptypes.element)
59 + - [`React.PropTypes.instanceOf()`](#react.proptypes.instanceof)
60 + - [`React.PropTypes.oneOf()`](#react.proptypes.oneof)
61 + - [`React.PropTypes.oneOfType()`](#react.proptypes.oneoftype)
62 + - [`React.PropTypes.arrayOf()`](#react.proptypes.arrayof)
63 + - [`React.PropTypes.objectOf()`](#react.proptypes.objectof)
64 + - [`React.PropTypes.shape()`](#react.proptypes.shape)
65 + - [`React.PropTypes.any`](#react.proptypes.any)
66 +
67 +Validators treat props as optional by default. You can use `isRequired` to make sure a warning is shown if the prop is not provided.
68 +
69 + - [`isRequired`](#isrequired)
70 +
71 +### Add-Ons
72 +
73 +If you're using [`react-with-addons.js`](/react/docs/addons.html), the React Add-Ons will be available via `React.addons`.
74 +
75 + - [`React.addons`](#react.addons)
76 +
77 +* * *
78 +
79 +## Reference
80 +
81 +### `React.Component`
82 +
83 +`React.Component` is the base class for React components when they are defined using [ES6 classes](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes).
84 +
85 +```javascript
86 +class Greeting extends React.Component {
87 + render() {
88 + return <h1>Hello, {this.props.name}</h1>;
89 + }
90 +}
91 +```
92 +
93 +See the [React.Component API Reference](/react/docs/react-component.html) for a list of methods and properties related to the base `React.Component` class.
94 +
95 +* * *
96 +
97 +### `React.PureComponent`
98 +
99 +`React.PureComponent` is exactly like [`React.Component`](#react.component) but implements [`shouldComponentUpdate()`](/react/docs/react-component.html#shouldcomponentupdate) with a shallow prop and state comparison.
100 +
101 +If your React component's `render()` function renders the same result given the same props and state, you can use `React.PureComponent` for a performance boost in some cases.
102 +
103 +> Note
104 +
105 +> `React.PureComponent`'s `shouldComponentUpdate()` only shallowly compares the objects. If these contain complex data structures, it may produce false-negatives for deeper differences. Only mix into components which have simple props and state, or use [`forceUpdate()`](/react/docs/react-component.html#forceupdate) when you know deep data structures have changed. Or, consider using [immutable objects](https://facebook.github.io/immutable-js/) to facilitate fast comparisons of nested data.
106 +>
107 +> Furthermore, `React.PureComponent`'s `shouldComponentUpdate()` skips prop updates for the whole component subtree. Make sure all the children components are also "pure".
108 +
109 +* * *
110 +
111 +### `createClass()`
112 +
113 +```javascript
114 +React.createClass(specification)
115 +```
116 +
117 +If you don't use ES6 yet, you may use the `React.createClass()` helper instead to create a component class.
118 +
119 +```javascript
120 +var Greeting = React.createClass({
121 + render: function() {
122 + return <h1>Hello, {this.props.name}</h1>;
123 + }
124 +});
125 +```
126 +
127 +See [Using React without ES6](/react/docs/react-without-es6.html) for more information.
128 +
129 +* * *
130 +
131 +### `createElement()`
132 +
133 +```javascript
134 +React.createElement(
135 + type,
136 + [props],
137 + [...children]
138 +)
139 +```
140 +
141 +Create and return a new React element of the given type. The type argument can be either an
142 +html tag name string (eg. 'div', 'span', etc), or a React class (created via `React.createClass()`).
143 +
144 +Code written with JSX will be converted to use `React.createElement()`. You will not typically invoke `React.createElement()` directly if you are using JSX. See [React Without JSX](/react/docs/react-without-jsx.html) to learn more.
145 +
146 +Convenience wrappers around `React.createElement()` for DOM components are provided by `React.DOM`. For example, `React.DOM.a(...)` is a convenience wrapper for `React.createElement('a', ...)`.
147 +
148 +* * *
149 +
150 +### `cloneElement()`
151 +
152 +```
153 +React.cloneElement(
154 + element,
155 + [props],
156 + [...children]
157 +)
158 +```
159 +
160 +Clone and return a new React element using `element` as the starting point. The resulting element will have the original element's props with the new props merged in shallowly. New children will replace existing children. `key` and `ref` from the original element will be preserved.
161 +
162 +`React.cloneElement()` is almost equivalent to:
163 +
164 +```js
165 +<element.type {...element.props} {...props}>{children}</element.type>
166 +```
167 +
168 +However, it also preserves `ref`s. This means that if you get a child with a `ref` on it, you won't accidentally steal it from your ancestor. You will get the same `ref` attached to your new element.
169 +
170 +This API was introduced as a replacement of the deprecated `React.addons.cloneWithProps()`.
171 +
172 +* * *
173 +
174 +### `createFactory()`
175 +
176 +```javascript
177 +React.createFactory(type)
178 +```
179 +
180 +Return a function that produces React elements of a given type. Like [`React.createElement()`](#createElement), the type argument can be either an html tag name string (eg. 'div', 'span', etc), or a React class.
181 +
182 +You will not typically invoke `React.createFactory()` directly if you are using JSX. See [React Without JSX](/react/docs/react-without-jsx.html) to learn more.
183 +
184 +* * *
185 +
186 +### `isValidElement()`
187 +
188 +```javascript
189 +React.isValidElement(object)
190 +```
191 +
192 +Verifies the object is a React element. Returns `true` or `false`.
193 +
194 +* * *
195 +
196 +### `React.Children`
197 +
198 +`React.Children` provides utilities for dealing with the `this.props.children` opaque data structure.
199 +
200 +#### `React.Children.map`
201 +
202 +```javascript
203 +React.Children.map(children, function[(thisArg)])
204 +```
205 +
206 +Invokes a function on every immediate child contained within `children` with `this` set to `thisArg`. If `children` is a keyed fragment or array it will be traversed: the function will never be passed the container objects. If children is `null` or `undefined`, returns `null` or `undefined` rather than an array.
207 +
208 +#### `React.Children.forEach`
209 +
210 +```javascript
211 +React.Children.forEach(children, function[(thisArg)])
212 +```
213 +
214 +Like [`React.Children.map()`](#react.children.map) but does not return an array.
215 +
216 +#### `React.Children.count`
217 +
218 +```javascript
219 +Children.count(children)
220 +```
221 +
222 +Returns the total number of components in `children`, equal to the number of times that a callback passed to `map` or `forEach` would be invoked.
223 +
224 +#### `React.Children.only`
225 +
226 +```javascript
227 +React.Children.only(children)
228 +```
229 +
230 +Returns the only child in `children`. Throws otherwise.
231 +
232 +#### `React.Children.toArray`
233 +
234 +```javascript
235 +React.Children.toArray(children)
236 +```
237 +
238 +Returns the `children` opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice `this.props.children` before passing it down.
239 +
240 +> Note:
241 +>
242 +> `React.Children.toArray()` changes keys to preserve the semantics of nested arrays when flattening lists of children. That is, `toArray` prefixes each key in the returned array so that each element's key is scoped to the input array containing it.
243 +
244 +* * *
245 +
246 +### `React.PropTypes`
247 +
248 +`React.PropTypes` exports a range of validators that can be used with a component's `propTypes` object to validate props being passed to your components.
249 +
250 +For more information about `PropTypes`, see [Typechecking with PropTypes](/react/docs/typechecking-with-proptypes.html).
251 +
252 +#### `React.PropTypes.array`
253 +
254 +```javascript
255 +React.PropTypes.array
256 +```
257 +
258 +Validates that a prop is a JavaScript array primitive.
259 +
260 +#### `React.PropTypes.bool`
261 +
262 +```javascript
263 +React.PropTypes.bool
264 +```
265 +
266 +Validates that a prop is a JavaScript bool primitive.
267 +
268 +#### `React.PropTypes.func`
269 +
270 +```javascript
271 +React.PropTypes.func
272 +```
273 +
274 +Validates that a prop is a JavaScript function.
275 +
276 +#### `React.PropTypes.number`
277 +
278 +```javascript
279 +React.PropTypes.number
280 +```
281 +
282 +Validates that a prop is a JavaScript number primitive.
283 +
284 +#### `React.PropTypes.object`
285 +
286 +```javascript
287 +React.PropTypes.object
288 +```
289 +
290 +Validates that a prop is a JavaScript object.
291 +
292 +#### `React.PropTypes.string`
293 +
294 +```javascript
295 +React.PropTypes.string
296 +```
297 +
298 +Validates that a prop is a JavaScript string primitive.
299 +
300 +#### `React.PropTypes.symbol`
301 +
302 +```javascript
303 +React.PropTypes.symbol
304 +```
305 +
306 +Validates that a prop is a JavaScript symbol.
307 +
308 +#### `React.PropTypes.node`
309 +
310 +```javascript
311 +React.PropTypes.node
312 +```
313 +
314 +Validates that a prop is anything that can be rendered: numbers, strings, elements or an array (or fragment) containing these types.
315 +
316 +#### `React.PropTypes.element`
317 +
318 +```javascript
319 +React.PropTypes.element
320 +```
321 +
322 +Validates that a prop is a React element.
323 +
324 +#### `React.PropTypes.instanceOf()`
325 +
326 +```javascript
327 +React.PropTypes.instanceOf(class)
328 +```
329 +
330 +Validates that a prop is an instance of a class. This uses JavaScript's `instanceof` operator.
331 +
332 +#### `React.PropTypes.oneOf()`
333 +
334 +```javascript
335 +React.PropTypes.oneOf(arrayOfValues)
336 +```
337 +
338 +Validates that a prop is limited to specific values by treating it as an enum.
339 +
340 +```javascript
341 +MyComponent.propTypes = {
342 + optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),
343 +}
344 +```
345 +
346 +#### `React.PropTypes.oneOfType()`
347 +
348 +```javascript
349 +React.PropTypes.oneOfType(arrayOfPropTypes)
350 +```
351 +
352 +Validates that a prop is an object that could be one of many types.
353 +
354 +```javascript
355 +MyComponent.propTypes = {
356 + optionalUnion: React.PropTypes.oneOfType([
357 + React.PropTypes.string,
358 + React.PropTypes.number,
359 + React.PropTypes.instanceOf(Message)
360 + ]),
361 +}
362 +```
363 +
364 +#### `React.PropTypes.arrayOf()`
365 +
366 +```javascript
367 +React.PropTypes.arrayOf(propType)
368 +```
369 +
370 +Validates that a prop is an an array of a certain type.
371 +
372 +```javascript
373 +MyComponent.propTypes = {
374 + optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
375 +}
376 +```
377 +
378 +#### `React.PropTypes.objectOf()`
379 +
380 +```javascript
381 +React.PropTypes.objectOf(propType)
382 +```
383 +
384 +Validates that a prop is an object with property values of a certain type.
385 +
386 +```javascript
387 +MyComponent.propTypes = {
388 + optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
389 +}
390 +```
391 +
392 +#### `React.PropTypes.shape()`
393 +
394 +```javascript
395 +React.PropTypes.shape(object)
396 +```
397 +
398 +Validates that a prop is an object taking on a particular shape.
399 +
400 +```javascript
401 +MyComponent.propTypes = {
402 + optionalObjectWithShape: React.PropTypes.shape({
403 + color: React.PropTypes.string,
404 + fontSize: React.PropTypes.number
405 + }),
406 +}
407 +```
408 +
409 +#### `React.PropTypes.any`
410 +
411 +```javascript
412 +React.PropTypes.any
413 +```
414 +
415 +Validates that a prop has a value of any data type. Usually followed by `isRequired`.
416 +
417 +```javascript
418 +MyComponent.propTypes = {
419 + requiredAny: React.PropTypes.any.isRequired,
420 +}
421 +```
422 +
423 +### `isRequired`
424 +
425 +```javascript
426 +propType.isRequired
427 +```
428 +
429 +You can chain any of the above validators with `isRequired` to make sure a warning is shown if the prop is not provided.
430 +
431 +```javascript
432 +MyComponent.propTypes = {
433 + requiredFunc: React.PropTypes.func.isRequired,
434 +}
435 +```
436 +
437 +* * *
438 +
439 +### `React.addons`
440 +
441 +```javascript
442 +React.addons
443 +```
444 +
445 +`React.addons` exports a range of add-ons when using [`react-with-addons.js`](/react/docs/addons.html).
docs/docs/refs-and-the-dom.md new
+92
@@ -0,0 +1,92 @@
1 +---
2 +id: refs-and-the-dom
3 +title: Refs and the DOM
4 +redirect_from: "/docs/working-with-the-browser.html"
5 +redirect_from: "/docs/more-about-refs.html"
6 +redirect_from: "/tips/expose-component-functions.html"
7 +redirect_from: "/tips/children-undefined.html"
8 +permalink: docs/refs-and-the-dom.html
9 +---
10 +
11 +In the typical React dataflow, [props](/react/docs/components-and-props.html) are the only way that parent components interact with their children. To modify a child, you re-render it with new props. However, there are a few cases where you need to imperatively modify a child outside of the typical dataflow. The child to be modified could be an instance of a React component, or it could be a DOM element. For both of these cases, React provides an escape hatch.
12 +
13 +## The ref Callback Attribute
14 +
15 +React supports a special attribute that you can attach to any component. The `ref` attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.
16 +
17 +When the `ref` attribute is used on a HTML element, the `ref` callback receives the underlying DOM element as its argument. For example, this code uses the `ref` callback to store a reference to a DOM node:
18 +
19 +```javascript
20 +class CustomTextInput extends React.Component {
21 + constructor(props) {
22 + super(props);
23 + this.focus = this.focus.bind(this);
24 + }
25 +
26 + focus() {
27 + // Explicitly focus the text input using the raw DOM API
28 + this.textInput.focus();
29 + }
30 +
31 + render() {
32 + // Use the `ref` callback to store a reference to the text input DOM
33 + // element in this.textInput
34 + return (
35 + <div>
36 + <input type="text" ref={(input) => this.textInput = input} />
37 + <input
38 + type="button"
39 + value="Focus the text input"
40 + onClick={this.focus}
41 + />
42 + </div>
43 + );
44 + }
45 +}
46 +```
47 +
48 +React will call the `ref` callback with the DOM element when the component mounts, and call it with `null` when it unmounts.
49 +
50 +Using the `ref` callback just to set a property on the class is a common pattern for accessing DOM elements. If you are currently using `this.refs.myRefName` to access refs, we recommend using this pattern instead.
51 +
52 +When the `ref` attribute is used on a custom component, the `ref` callback receives the mounted instance of the component as its argument. For example, if we wanted to wrap the `CustomTextInput` above to simulate it being clicked immediately after mounting:
53 +
54 +```javascript
55 +class AutoFocusTextInput extends React.Component {
56 + componentDidMount() {
57 + this.textInput.focus();
58 + }
59 +
60 + render() {
61 + return <CustomTextInput ref={(input) => this.textInput = input} />;
62 + }
63 +}
64 +```
65 +
66 +You may not use the `ref` attribute on functional components because they don't have instances. You can, however, use the `ref` attribute inside the `render` function of a functional component:
67 +
68 +```javascript
69 +function CustomTextInput(props) {
70 + // textInput must be declared here so the ref callback can refer to it
71 + let textInput;
72 +
73 + function handleClick() {
74 + textInput.focus();
75 + }
76 +
77 + return (
78 + <div>
79 + <input type="text" ref={(input) => textInput = input} />
80 + <input
81 + type="button"
82 + value="Focus the text input"
83 + onClick={handleClick}
84 + />
85 + </div>
86 + );
87 +}
88 +```
89 +
90 +### Don't Overuse Refs
91 +
92 +Your first inclination may be to use refs to "make things happen" in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. Often, it becomes clear that the proper place to "own" that state is at a higher level in the hierarchy - see the [Lifting State Up](/react/docs/lifting-state-up.html) guide for examples of this.
docs/docs/rendering-elements.md new
+95
@@ -0,0 +1,95 @@
1 +---
2 +id: rendering-elements
3 +title: Rendering Elements
4 +permalink: docs/rendering-elements.html
5 +redirect_from: "/docs/displaying-data.html"
6 +prev: introducing-jsx.html
7 +next: components-and-props.html
8 +---
9 +
10 +Elements are the smallest building blocks of React apps.
11 +
12 +An element describes what you want to see on the screen:
13 +
14 +```js
15 +const element = <h1>Hello, world</h1>;
16 +```
17 +
18 +Unlike browser DOM elements, React elements are plain objects, and are cheap to create. React DOM takes care of updating the DOM to match the React elements.
19 +
20 +>**Note:**
21 +>
22 +>One might confuse elements with a more widely known concept of "components". We will introduce components in the [next section](/react/docs/components-and-props.html). Elements are what components are "made of", and we encourage you to read this section before jumping ahead.
23 +
24 +## Rendering an Element into the DOM
25 +
26 +Let's say there is a `<div>` somewhere in your HTML file:
27 +
28 +```html
29 +<div id="root"></div>
30 +```
31 +
32 +We call this a "root" DOM node because everything inside it will be managed by React DOM.
33 +
34 +Applications built with just React usually have a single root DOM node. If you are integrating React into an existing app, you may have as many isolated root DOM nodes as you like.
35 +
36 +To render a React element into a root DOM node, pass both to `ReactDOM.render()`:
37 +
38 +```js
39 +const element = <h1>Hello, world</h1>;
40 +ReactDOM.render(
41 + element,
42 + document.getElementById('root')
43 +);
44 +```
45 +
46 +[Try it on CodePen.](http://codepen.io/gaearon/pen/rrpgNB?editors=1010)
47 +
48 +It displays "Hello World" on the page.
49 +
50 +## Updating the Rendered Element
51 +
52 +React elements are [immutable](https://en.wikipedia.org/wiki/Immutable_object). Once you create an element, you can't change its children or attributes. An element is like a single frame in a movie: it represents the UI at a certain point in time.
53 +
54 +With our knowledge so far, the only way to update the UI is to create a new element, and pass it to `ReactDOM.render()`.
55 +
56 +Consider this ticking clock example:
57 +
58 +```js{8-11}
59 +function tick() {
60 + const element = (
61 + <div>
62 + <h1>Hello, world!</h1>
63 + <h2>It is {new Date().toLocaleTimeString()}.</h2>
64 + </div>
65 + );
66 + ReactDOM.render(
67 + element,
68 + document.getElementById('root')
69 + );
70 +}
71 +
72 +setInterval(tick, 1000);
73 +```
74 +
75 +[Try it on CodePen.](http://codepen.io/gaearon/pen/gwoJZk?editors=0010)
76 +
77 +It calls `ReactDOM.render()` every second from a [`setInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval) callback.
78 +
79 +>**Note:**
80 +>
81 +>In practice, most React apps only call `ReactDOM.render()` once. In the next sections we will learn how such code gets encapsulated into [stateful components](/react/docs/state-and-lifecycle.html).
82 +>
83 +>We recommend that you don't skip topics because they build on each other.
84 +
85 +## React Only Updates What's Necessary
86 +
87 +React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.
88 +
89 +You can verify by inspecting the [last example](http://codepen.io/gaearon/pen/gwoJZk?editors=0010) with the browser tools:
90 +
91 +![DOM inspector showing granular updates](/react/img/docs/granular-dom-updates.gif)
92 +
93 +Even though we create an element describing the whole UI tree on every tick, only the text node whose contents has changed gets updated by React DOM.
94 +
95 +In our experience, thinking about how the UI should look at any given moment rather than how to change it over time eliminates a whole class of bugs.
docs/docs/state-and-lifecycle.md new
+458
@@ -0,0 +1,458 @@
1 +---
2 +id: state-and-lifecycle
3 +title: State and Lifecycle
4 +permalink: docs/state-and-lifecycle.html
5 +redirect_from: "/docs/interactivity-and-dynamic-uis.html"
6 +prev: components-and-props.html
7 +next: handling-events.html
8 +---
9 +
10 +Consider the ticking clock example from the [one of the previous sections](/react/docs/rendering-elements.html#updating-the-rendered-element).
11 +
12 +So far we have only learned one way to update the UI.
13 +
14 +We call `ReactDOM.render()` to change the rendered output:
15 +
16 +```js{8-11}
17 +function tick() {
18 + const element = (
19 + <div>
20 + <h1>Hello, world!</h1>
21 + <h2>It is {new Date().toLocaleTimeString()}.</h2>
22 + </div>
23 + );
24 + ReactDOM.render(
25 + element,
26 + document.getElementById('root')
27 + );
28 +}
29 +
30 +setInterval(tick, 1000);
31 +```
32 +
33 +[Try it on CodePen.](http://codepen.io/gaearon/pen/gwoJZk?editors=0010)
34 +
35 +In this section, we will learn how to make the `Clock` component truly reusable and encapsulated. It will set up its own timer and update itself every second.
36 +
37 +We can start by encapsulating how the clock looks:
38 +
39 +```js{3-6,12}
40 +function Clock(props) {
41 + return (
42 + <div>
43 + <h1>Hello, world!</h1>
44 + <h2>It is {props.date.toLocaleTimeString()}.</h2>
45 + </div>
46 + );
47 +}
48 +
49 +function tick() {
50 + ReactDOM.render(
51 + <Clock date={new Date()} />,
52 + document.getElementById('root')
53 + );
54 +}
55 +
56 +setInterval(tick, 1000);
57 +```
58 +
59 +[Try it on CodePen.](http://codepen.io/gaearon/pen/dpdoYR?editors=0010)
60 +
61 +However, it misses a crucial requirement: the fact that the `Clock` sets up a timer and updates the UI every second should be an implementation detail of the `Clock`.
62 +
63 +Ideally we want to write this once and have the `Clock` update itself:
64 +
65 +```js{2}
66 +ReactDOM.render(
67 + <Clock />,
68 + document.getElementById('root')
69 +);
70 +```
71 +
72 +To implement this, we need to add "state" to the `Clock` component.
73 +
74 +State is similar to props, but it is private and fully controlled by the component.
75 +
76 +We [mentioned before](/react/docs/components-and-props.html#functional-and-class-components) that components defined as classes have some additional features. Local state is exactly that: a feature available only to classes.
77 +
78 +## Converting a Function to a Class
79 +
80 +You can convert a functional component like `Clock` to a class in five steps:
81 +
82 +1. Create an [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes) with the same name that extends `React.Component`.
83 +
84 +2. Add a single empty method to it called `render()`.
85 +
86 +3. Move the body of the function into the `render()` method.
87 +
88 +4. Replace `props` with `this.props` in the `render()` body.
89 +
90 +5. Delete the remaining empty function declaration.
91 +
92 +```js
93 +class Clock extends React.Component {
94 + render() {
95 + return (
96 + <div>
97 + <h1>Hello, world!</h1>
98 + <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
99 + </div>
100 + );
101 + }
102 +}
103 +```
104 +
105 +[Try it on CodePen.](http://codepen.io/gaearon/pen/zKRGpo?editors=0010)
106 +
107 +`Clock` is now defined as a class rather than a function.
108 +
109 +This lets us use additional features such as local state and lifecycle hooks.
110 +
111 +## Adding Local State to a Class
112 +
113 +We will move the `date` from props to state in three steps:
114 +
115 +1) Replace `this.props.date` with `this.state.date` in the `render()` method:
116 +
117 +```js{6}
118 +class Clock extends React.Component {
119 + render() {
120 + return (
121 + <div>
122 + <h1>Hello, world!</h1>
123 + <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
124 + </div>
125 + );
126 + }
127 +}
128 +```
129 +
130 +2) Add a [class constructor](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes#Constructor) that assigns the initial `this.state`:
131 +
132 +```js{4}
133 +class Clock extends React.Component {
134 + constructor(props) {
135 + super(props);
136 + this.state = {date: new Date()};
137 + }
138 +
139 + render() {
140 + return (
141 + <div>
142 + <h1>Hello, world!</h1>
143 + <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
144 + </div>
145 + );
146 + }
147 +}
148 +```
149 +
150 +Note how we pass `props` to the base constructor:
151 +
152 +```js{2}
153 + constructor(props) {
154 + super(props);
155 + this.state = {date: new Date()};
156 + }
157 +```
158 +
159 +Class components should always call the base constructor with `props`.
160 +
161 +3) Remove the `date` prop from the `<Clock />` element:
162 +
163 +```js{2}
164 +ReactDOM.render(
165 + <Clock />,
166 + document.getElementById('root')
167 +);
168 +```
169 +
170 +We will later add the timer code back to the component itself.
171 +
172 +The result looks like this:
173 +
174 +```js{2-5,11,18}
175 +class Clock extends React.Component {
176 + constructor(props) {
177 + super(props);
178 + this.state = {date: new Date()};
179 + }
180 +
181 + render() {
182 + return (
183 + <div>
184 + <h1>Hello, world!</h1>
185 + <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
186 + </div>
187 + );
188 + }
189 +}
190 +
191 +ReactDOM.render(
192 + <Clock />,
193 + document.getElementById('root')
194 +);
195 +```
196 +
197 +[Try it on CodePen.](http://codepen.io/gaearon/pen/KgQpJd?editors=0010)
198 +
199 +Next, we'll make the `Clock` set up its own timer and update itself every second.
200 +
201 +## Adding Lifecycle Methods to a Class
202 +
203 +In applications with many components, it's very important to free up resources taken by the components when they are destroyed.
204 +
205 +We want to [set up a timer](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval) whenever the `Clock` is rendered to the DOM for the first time. This is called "mounting" in React.
206 +
207 +We also want to [clear that timer](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval) whenever the DOM produced by the `Clock` is removed. This is called "unmounting" in React.
208 +
209 +We can declare special methods on the component class to run some code when a component mounts and unmounts:
210 +
211 +```js{7-9,11-13}
212 +class Clock extends React.Component {
213 + constructor(props) {
214 + super(props);
215 + this.state = {date: new Date()};
216 + }
217 +
218 + componentDidMount() {
219 +
220 + }
221 +
222 + componentWillUnmount() {
223 +
224 + }
225 +
226 + render() {
227 + return (
228 + <div>
229 + <h1>Hello, world!</h1>
230 + <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
231 + </div>
232 + );
233 + }
234 +}
235 +```
236 +
237 +These methods are called "lifecycle hooks".
238 +
239 +The `componentDidMount()` hook runs after the component output has been rendered to the DOM. This is a good place to set up a timer:
240 +
241 +```js{2-5}
242 + componentDidMount() {
243 + this.timerID = setInterval(
244 + () => this.tick(),
245 + 1000
246 + );
247 + }
248 +```
249 +
250 +Note how we save the timer ID right on `this`.
251 +
252 +While `this.props` is set up by React itself and `this.state` has a special meaning, you are free to add additional fields to the class manually if you need to store something that is not used for the visual output.
253 +
254 +If you don't use something in `render()`, it shouldn't be in the state.
255 +
256 +We will tear down the timer in the `componentWillUnmount()` lifecycle hook:
257 +
258 +```js{2}
259 + componentWillUnmount() {
260 + clearInterval(this.timerID);
261 + }
262 +```
263 +
264 +Finally, we will implement the `tick()` method that runs every second.
265 +
266 +It will use `this.setState()` to schedule updates to the component local state:
267 +
268 +```js{18-22}
269 +class Clock extends React.Component {
270 + constructor(props) {
271 + super(props);
272 + this.state = {date: new Date()};
273 + }
274 +
275 + componentDidMount() {
276 + this.timerID = setInterval(
277 + () => this.tick(),
278 + 1000
279 + );
280 + }
281 +
282 + componentWillUnmount() {
283 + clearInterval(this.timerID);
284 + }
285 +
286 + tick() {
287 + this.setState({
288 + date: new Date()
289 + });
290 + }
291 +
292 + render() {
293 + return (
294 + <div>
295 + <h1>Hello, world!</h1>
296 + <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
297 + </div>
298 + );
299 + }
300 +}
301 +
302 +ReactDOM.render(
303 + <Clock />,
304 + document.getElementById('root')
305 +);
306 +```
307 +
308 +[Try it on CodePen.](http://codepen.io/gaearon/pen/amqdNA?editors=0010)
309 +
310 +Now the clock ticks every second.
311 +
312 +## Using State Correctly
313 +
314 +There are three things you should know about `setState()`.
315 +
316 +### Do Not Modify State Directly
317 +
318 +For example, this will not re-render a component:
319 +
320 +```js
321 +// Wrong
322 +this.state.comment = 'Hello';
323 +```
324 +
325 +Instead, use `setState()`:
326 +
327 +```js
328 +// Correct
329 +this.setState({comment: 'Hello'});
330 +```
331 +
332 +### State Updates May Be Asynchronous
333 +
334 +React may batch multiple `setState()` calls into a single update for performance.
335 +
336 +Because `this.props` and `this.state` may be updated asynchronously, you should not rely on their values for calculating the next state.
337 +
338 +For example, this code may fail to update the counter:
339 +
340 +```js
341 +// Wrong
342 +this.setState({
343 + counter: this.state.counter + this.props.increment,
344 +});
345 +```
346 +
347 +To fix it, use a second form of `setState()` that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:
348 +
349 +```js
350 +// Correct
351 +this.setState((prevState, props) => ({
352 + counter: prevState.counter + props.increment
353 +}));
354 +```
355 +
356 +We used an [arrow function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) above, but it also works with regular functions:
357 +
358 +```js
359 +// Correct
360 +this.setState(function(prevState, props) {
361 + return {
362 + counter: prevState.counter + props.increment
363 + };
364 +});
365 +```
366 +
367 +### State Updates are Merged
368 +
369 +When you call `setState()`, React merges the object you provide into the current state.
370 +
371 +For example, your state may contain several independent variables:
372 +
373 +```js{4,5}
374 + constructor(props) {
375 + super(props);
376 + this.state = {
377 + posts: [],
378 + comments: []
379 + };
380 + }
381 +```
382 +
383 +Then you can update them independently with separate `setState()` calls:
384 +
385 +```js{4,10}
386 + componentDidMount() {
387 + fetchPosts().then(response => {
388 + this.setState({
389 + posts: response.posts
390 + });
391 + });
392 +
393 + fetchComments().then(response => {
394 + this.setState({
395 + comments: response.comments
396 + });
397 + });
398 + }
399 +```
400 +
401 +The merging is shallow, so `this.setState({comments})` leaves `this.state.posts` intact, but completely replaces `this.state.comments`.
402 +
403 +## The Data Flows Down
404 +
405 +Neither parent nor child components can know if a certain component is stateful or stateless, and they shouldn't care whether it is defined as a function or a class.
406 +
407 +This is why state is often called local or encapsulated. It is not accessible to any component other than the one that owns and sets it.
408 +
409 +A component may choose to pass its state down as props to its child components:
410 +
411 +```js
412 +<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
413 +```
414 +
415 +This also works for user-defined components:
416 +
417 +```js
418 +<FormattedDate date={this.state.date} />
419 +```
420 +
421 +The `FormattedDate` component would receive the `date` in its props and wouldn't know whether it came from the `Clock`'s state, the props, or was typed by hand:
422 +
423 +```js
424 +function FormattedDate(props) {
425 + return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
426 +}
427 +```
428 +
429 +[Try it on CodePen.](http://codepen.io/gaearon/pen/zKRqNB?editors=0010)
430 +
431 +This is commonly called a "top-down" or "unidirectional" data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components "below" them in the tree.
432 +
433 +If you imagine a component tree as a waterfall of props, each component's state is like an additional water source that joins it at an arbitrary point but also flows down.
434 +
435 +To show that all components are truly isolated, we can create an `App` component that renders three `<Clock>`s:
436 +
437 +```js{4-6}
438 +function App() {
439 + return (
440 + <div>
441 + <Clock />
442 + <Clock />
443 + <Clock />
444 + </div>
445 + );
446 +}
447 +
448 +ReactDOM.render(
449 + <App />,
450 + document.getElementById('root')
451 +);
452 +```
453 +
454 +[Try it on CodePen.](http://codepen.io/gaearon/pen/vXdGmd?editors=0010)
455 +
456 +Each `Clock` sets up its own timer and updates independently.
457 +
458 +In React apps, whether a component is stateful or stateless is considered an implementation detail of the component that may change over time. You can use stateless components inside stateful components, and vice versa.
docs/docs/thinking-in-react.it-IT.md deleted
-148
@@ -1,148 +0,0 @@
1 ----
2 -id: thinking-in-react-it-IT
3 -title: Pensare in React
4 -permalink: docs/thinking-in-react-it-IT.html
5 -prev: tutorial-it-IT.html
6 -next: conferences-it-IT.html
7 -redirect_from: 'blog/2013/11/05/thinking-in-react.html'
8 ----
9 -
10 -di Pete Hunt
11 -
12 -React è, a mio parere, la maniera più adeguata di costruire veloci applicazioni Web di grandi dimensioni con JavaScript. Ha scalato molto bene per noi a Facebook e Instagram.
13 -
14 -Una delle molte parti migliori di React è come ti fa pensare alle applicazioni mentre le costruisci. In questo articolo vi guiderò attraverso il processo di pensiero per la costruzione di una tabella di dati di prodotti che possono essere cercati usando React.
15 -
16 -## Comincia con un mock
17 -
18 -Immagina di possedere già una API JSON e un mock prodotto dai nostri designer. I nostri designer apparentemente non sono molto capaci perché il mock ha questo aspetto:
19 -
20 -![Mockup](/react/img/blog/thinking-in-react-mock.png)
21 -
22 -La nostra API JSON restituisce dei dati che somigliano a quanto segue:
23 -
24 -```
25 -[
26 - {category: "Sporting Goods", price: "$49.99", stocked: true, name: "Football"},
27 - {category: "Sporting Goods", price: "$9.99", stocked: true, name: "Baseball"},
28 - {category: "Sporting Goods", price: "$29.99", stocked: false, name: "Basketball"},
29 - {category: "Electronics", price: "$99.99", stocked: true, name: "iPod Touch"},
30 - {category: "Electronics", price: "$399.99", stocked: false, name: "iPhone 5"},
31 - {category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7"}
32 -];
33 -```
34 -
35 -## Passo 1: suddividi la UI in una gerarchia di componenti
36 -
37 -La prima azione che vorrai compiere è disegnare dei rettangoli attorno a ciascun componente (e subcomponenti) nel mock e dare un nome a ciascuno di essi. Se stai lavorando con i designer, potrebbero averlo già fatto, quindi parla anzitutto con loro! I nomi dei loro layer di Photoshop potrebbero finire per diventare i nomi dei tuoi componenti React!
38 -
39 -Come fai tuttavia a sapere cosa dovrebbe essere un componente a sé? Usa una delle tecniche per decidere se devi creare un nuovo oggetto o una nuova funzione. Una di tali tecniche è il [principio della singola responsibilità](https://en.wikipedia.org/wiki/Single_responsibility_principle), ovvero, un componente dovrebbe idealmente servire a un solo scopo. Se finisce per crescere, dovrebbe essere decomposto in componenti più piccoli.
40 -
41 -Dal momento che stai spesso mostrando un modello di dati JSON all'utente, ti accorgerai che se il tuo modello è stato costruito correttamente, la tua UI (e quindi anche la struttura dei tuoi componenti) si adatterà facilmente. Ciò accade perché le UI e i modelli di dati tendono ad aderire alla medesima *architettura dell'informazione*, che significa che il compito di separare la tua UI in componenti è spesso banale. Suddividila semplicemente in componenti che rappresentano esattamente un frammento del tuo modello di dati.
42 -
43 -![Diagramma dei componenti](/react/img/blog/thinking-in-react-components.png)
44 -
45 -Vedrai che abbiamo in tutto cinque componenti nella nostra semplice applicazione. Ho scritto in corsivo i dati che ciascun componente rappresenta.
46 -
47 - 1. **`FilterableProductTable` (arancione):** contiene l'intero esempio
48 - 2. **`SearchBar` (blu):** riceve tutti gli *input dell'utente*
49 - 3. **`ProductTable` (verde):** mostra e filtra la *collezione dei dati* basandosi sull'*input dell'utente*
50 - 4. **`ProductCategoryRow` (turchese):** mostra un titolo per ciascuna *categoria*
51 - 5. **`ProductRow` (rosso):** mostra una riga per ciascun *prodotto*
52 -
53 -Se osservi la `ProductTable`, ti accorgerai che l'intestazione della tabella (che contiene le etichette "Name" e "Price") non è un componente a sé. Questa è una questione di gusti, e ci sono ragioni valide per ciascun approccio. Per questo esempio, l'ho lasciata parte di `ProductTable` perché fa parte della visualizzazione della *collezione dei dati* che è la responsabilità di `ProductTable`. Tuttavia, se questa intestazione cresce fino a diventare complessa (cioè se dovessimo aggiungere la possibilità di riordinare i dati), avrebbe certamente senso renderla un componente `ProductTableHeader` a sé.
54 -
55 -Adesso che abbiamo identificato i componenti nel nostro mock, organizziamoli in una gerarchia. Questo è un compito facile. I componenti che appaiono all'interno di un altro componente nel the mock devono apparire come figli nella gerarchia:
56 -
57 - * `FilterableProductTable`
58 - * `SearchBar`
59 - * `ProductTable`
60 - * `ProductCategoryRow`
61 - * `ProductRow`
62 -
63 -## Passo 2: Costruisci una versione statica in React
64 -
65 -<iframe width="100%" height="600" src="https://jsfiddle.net/reactjs/yun1vgqb/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
66 -
67 -Adesso che hai la tua gerarchia di componenti, è venuto il momento di implementare la tua applicazione. La maniera più semplice è costruire una versione che prende il tuo modello di dati e visualizza la UI ma non è interattiva. È buona norma disaccoppiare questi processi perché costruire una versione statica richiede la scrittura di parecchio codice e poco pensare, mentre aggiungere l'interattività richiede un parecchio pensare ma non un granché di scrittura. Vedremo perché.
68 -
69 -Per costruire una versione statica della tua applicazione dhe visualizzi il tuo modello dei dati, vorrai costruire componenti che riutilizano altri componenti e passano loro dati usando le *props*. Le *props* sono una maniera di passare dati da genitore a figlio. Se hai dimestichezza con il concetto di *state*, **non usare lo stato** per costruire questa versione statica. Lo stato è riservato solo per l'interattività, cioè dati che cambiano nel tempo. Dal momento che questa è una versione statica dell'applicazione, non ne avrai bisogno.
70 -
71 -Puoi costruire dall'alto in basso, o dal basso in alto. Ovvero, puoi cominciare a costruire i componenti più in alto nella gerarchia (cioè cominciare con `FilterableProductTable`) oppure con quelli più in basso (`ProductRow`). In esempi più semplici, è solitamente più facile andare dall'alto in basso, mentre in progetti più grandi è più facile andare dal basso in alto e scrivere test mentre costruisci.
72 -
73 -Alla fine di questo passo avrai una libreria di componenti riutilizzabili che visualizzano il tuo modello dati. I componenti avranno soltanto metodi `render()` dal momento che questa è una versione statica della tua applicazione. Il componente al vertice della gerarchia (`FilterableProductTable`) prenderà il tuo modello dati come una proprietà. Se apporti un cambiamento al tuo modello dati sottostante e chiami nuovamente `ReactDOM.render()`, la UI sarà aggiornata. È facile vedere come la tua UI viene aggiornata e dove applicare cambiamenti dal momento che non c'è nulla di complicato. Il **flusso dati unidirezionale** di React (detto anche *binding unidirezionale*) mantiene tutto modulare e veloce.
74 -
75 -Fai riferimento alla [documentazione React](/react/docs/) se hai bisogno di aiuto nell'eseguire questo passo.
76 -
77 -### Un breve intermezzo: proprietà oppure stato
78 -
79 -Esistono due tipi di dati "modello" in React: proprietà e stato. È importante capire la distinzione tra i due; scorri [la documentazione ufficiale di React](/react/docs/interactivity-and-dynamic-uis.html) se non hai ben chiara la differenza.
80 -
81 -## Passo 3: Identifica la rappresentazione minima (ma completa) dello stato della UI
82 -
83 -Per rendere la tua UI interattiva, hai bisogno di poter scatenare cambiamenti al tuo modello dati sottostante. React lo rende facile tramite lo **stato**.
84 -
85 -Per costruire correttamente la tua applicaizone, devi prima pensare all'insieme minimo di stato mutevole di cui la tua applicazione ha bisogno. La chiave qui è il principio DRY: *Don't Repeat Yourself (Non ripeterti)*. Una volta compresa la rappresentazione minima in assoluto dello stato della tua applicazione e calcola tutto lil resto sul momento. Ad esempio, se stai costruendo una lista di cose da fare, mantieni un array delle cose da fare; non tenere una variabile di stato separata per il conteggio. Invece, quando vuoi visualizzare il conteggio degli elementi, prendi semplicemente la lunghezza dell'arraiy delle cose da fare.
86 -
87 -Pensa a tutti gli elementi di dati nella nostra applicazione di esempio. Abbiamo:
88 -
89 - * La lista originaria dei prodotti
90 - * Il testo di ricerca che l'utente ha introdotto
91 - * Il valore del checkbox
92 - * La lista filtrata dei prodotti
93 -
94 -Rivediamo ciascuno di essi e capiamo se si tratta di stato. Chiediti queste tre semplici domande su ciascun elemento di dati:
95 -
96 - 1. Viene passato da un genitore attraverso le proprietà? Se sì, probabilmente non è stato.
97 - 2. Cambia nel tempo? Se no, probabilmente non è stato.
98 - 3. Puoi calcolarlo basandoti su altro stato o proprietà del tuo componente? Se sì, non è stato.
99 -
100 -La lista originaria di prodotti viene passata come proprietà, quindi non si tratta di stato. Il testo di ricerca e la checkbox sembrano essere stato perché cambiano nel tempo e non possono essere ricavate da altri dati. Infine, la lista filtrata di prodotti non è stato, perché può essere calcolata combinando la lista originaria dei prodotti con il testo di ricerca e il valore della checkbox.
101 -
102 -Quindi, per concludere, il nostro stato è:
103 -
104 - * Il testo di ricerca che l'utente ha introdotto
105 - * Il valore del checkbox
106 -
107 -## Passo 4: Identifica dove debba risiedere il tuo stato
108 -
109 -<iframe width="100%" height="600" src="https://jsfiddle.net/reactjs/zafjbw1e/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
110 -
111 -OK, abbiamo dunque identificato quale sia l'insieme minimo dello stato dell'applicazione. Successivamente, dobbiamo identificare quale componente muta, o *possiede*, questo stato.
112 -
113 -Ricorda: React è basato esclusivamente su flusso dati unidirezionale verso il basso della gerarchia dei componenti. Potrebbe non essere immediatamente chiaro quale componente debba possedere quale stato. **Questa è spesso la parte più difficile da capire per i principianti,** quindi segui questi passi per capirlo:
114 -
115 -Per ogni elemento dello stato nella tua applicazione:
116 -
117 - * Identifica ciascun componente che visualizza qualcosa basato su quello stato.
118 - * Trova un componente proprietario comune (un singolo componente più in alto nella gerarchia di ciascun componente che ha bisogno dello stato).
119 - * Il proprietario comune o un altro componente più in alto nella gerarchia deve possedere lo stato.
120 - * Se non riesci a trovare un componente per cui abbia senso possedere lo stato, crea un nuovo componente con il solo scopo di contenere lo stato e aggiungilo da qualche parte nella gerarchia sopra il componente proprietario comune.
121 -
122 -Applichiamo questa strategia per la nostra applicazione:
123 -
124 - * `ProductTable` deve filtrare la lista dei prodotti basandosi sullo stato e `SearchBar` deve visualizzare il testo di ricerca e lo stato della checkbox.
125 - * Il componente proprietario comune è `FilterableProductTable`.
126 - * Ha concettualmente senso che il testo di ricerca e lo stato della checkbox appartengano a `FilterableProductTable`
127 -
128 -Bene, abbiamo deciso che il nostro stato appartenga a `FilterableProductTable`. Anzitutto aggiungiamo un metodo `getInitialState()` a `FilterableProductTable` che restituisce `{filterText: '', inStockOnly: false}` per riflettere lo stato iniziale della tua applicazione. Dunque, passiamo `filterText` e `inStockOnly` a `ProductTable` e `SearchBar` come una proprietà. Infine, usiamo queste proprietà per filtrare le righe in `ProductTable` e impostare i valori dei campi del modulo in `SearchBar`.
129 -
130 -Puoi cominciare a vedere come si comporterà la tua applicazione: imposta `filterText` a `"ball"` e aggiorna la tua applicazione. Vedrai che la tabella dei dati è correttamente aggiornata.
131 -
132 -## Passo 5: Aggiungi il flusso dati inverso
133 -
134 -<iframe width="100%" height="600" src="https://jsfiddle.net/reactjs/n47gckhr/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
135 -
136 -Finora abbiamo costruito un'applicazione che visualizza correttamente come una funzione di proprietà e stato che fluiscono verso il basso della gerarchia. Adesso è il momento di supportare il flusso dei dati nella direzione opposta: i componenti del modulo in profondità nella gerarchia devono aggiornare lo stato in `FilterableProductTable`.
137 -
138 -React rende questo flusso dati esplicito per rendere più semplice la comprensione di come funziona la tua applicazione, ma richiede leggermente più codice di un tradizionale binding bidirezionale dei dati. React offre un add-on chiamato `ReactLink` per rendere questo pattern altrettanto conveniente del binding bidirezionale ma, per gli scopi di questo articolo, faremo tutto in modo esplicito.
139 -
140 -Se provi a scrivere o spunti la casella nella versione attuale dell'esempio, vedrai che React ignora il tuo input. Questo è un comportamento intenzionale, in quanto abbiamo impostato la proprietà `value` del campo `input` perché sia sempre uguale al valore di `state` passato da `FilterableProductTable`.
141 -
142 -Pensiamo a cosa vogliamo che accada. Vogliamo assicurarci che quando l'utente cambia il modulo noi aggiorniamo lo stato per riflettere l'input dell'utente. Dal momento che i componenti devono soltanto aggiornare il proprio stato, `FilterableProductTable` passerà una callback a `SearchBar` che sarà eseguita quando lo stato debba essere aggiornato. Possiamo utilizzare l'evento `onChange` sui campi di input per esserne notificati. E la callback passata da `FilterableProductTable` chiamerà `setState()`, e l'applicazione verrà aggiornata.
143 -
144 -Anche se sembra complesso, si tratta realmente di poche righe di codice. Inoltre, il flusso dati attraverso l'applicazione è davvero esplicito.
145 -
146 -## Tutto qui
147 -
148 -Speriamo che questo ti abbia dato un'idea di come pensare a costruire componenti e applicazioni con React. Mentre potrebbe richiedere leggermente più codice di quanto si sia abituati a scrivere, ricorda che il codice è letto più spesso di quanto sia scritto, ed è estremamente facile leggere codice così esplicito e modulare. Mentre ti avvii a costruire grandi librerie di componenti, apprezzerai questa chiarezza e modularità, e con il riutilizzo del codice le tue righe di codice cominceranno a ridursi. :)
docs/docs/thinking-in-react.ja-JP.md deleted
-149
@@ -1,149 +0,0 @@
1 ----
2 -id: thinking-in-react-ja-JP
3 -title: Reactの考え方
4 -permalink: docs/thinking-in-react-ja-JP.html
5 -prev: tutorial-ja-JP.html
6 -next: conferences.html
7 -redirect_from: 'blog/2013/11/05/thinking-in-react.html'
8 ----
9 -
10 -Pete Hunt著
11 -
12 -ReactはJavascriptで大きなアプリを早く作成するのに良い方法だと私は思います。FacebookとInstagram製で規模を大きすすることも容易いです。
13 -
14 -Reactのたくさんある中の偉大なパーツの1つのは、あなたに構築するアプリについて考えさせます。このページで、私はReactを使って検索可能な製品データテーブルを構築する思考プロセスをご案内します。
15 -
16 -## モックから始めましょう
17 -
18 -私たちはすでにデザイナーからJSON APIとモックをもらっていると想像してください。このモックを見ればわかるように私たちのデザイナーは明らかに良くないです。
19 -
20 -![Mockup](/react/img/blog/thinking-in-react-mock.png)
21 -
22 -JSON APIはこれらのようなデータを返します。
23 -
24 -```
25 -[
26 - {category: "Sporting Goods", price: "$49.99", stocked: true, name: "Football"},
27 - {category: "Sporting Goods", price: "$9.99", stocked: true, name: "Baseball"},
28 - {category: "Sporting Goods", price: "$29.99", stocked: false, name: "Basketball"},
29 - {category: "Electronics", price: "$99.99", stocked: true, name: "iPod Touch"},
30 - {category: "Electronics", price: "$399.99", stocked: false, name: "iPhone 5"},
31 - {category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7"}
32 -];
33 -```
34 -
35 -## ステップ1 : コンポーネント階層を用いてUIを改築します
36 -
37 -まずあなたが行いたいことは、モックに必要なすべてのコンポーネント(サブコンポーネントも)の箱を作り、名前をつけることでしょう。もしあなたがデザイナーと共に働いているなら、すでに行っているかもしれませんが、彼らと話に行きましょう!彼らのPhotoshopのレイヤーの名前をReactのコンポーネントの名前にして終わらせることもできます。
38 -
39 -独自コンポーネントがどのようにあるべきか知っていますか? あなたが新しい関数やオブジェクトを作る必要があるかどうかを決定するために同じ技術を使用しています。そのうちの一つのテクニックが[単一責任の原則(single responsibility principle)](https://en.wikipedia.org/wiki/Single_responsibility_principle)です。これは一つのコンポーネントは一つの振る舞いをするべきというものです。もしこれが難しいのであれば、より小さなサブコンポーネントに分ける必要があります。
40 -
41 -あなたは多くの場合、ユーザーにJSONデータ・モデルを表示しているので、あなたのモデルが正しく構築された場合、あなたのUI (したがって、コンポーネントの構造)がうまくマッピングされることがわかります。なぜなら、UIとデータモデルは同じ*情報構造*を持つ傾向にあり、つまりコンポーネントにUIを分離する作業は些細なことです。あなたの一つのデータモデルを表すコンポーネントに分割することが重要です。
42 -
43 -
44 -![Component diagram](/react/img/blog/thinking-in-react-components.png)
45 -
46 -これは私たちのシンプルなアプリの5つのコンポーネントです。各コンポーネントが表すデータが斜体になっています。
47 -
48 - 1. **`FilterableProductTable` (orange):** 例のすべてを含んでいます。
49 - 2. **`SearchBar` (blue):** *ユーザー入力*のすべてを含んでいます。
50 - 3. **`ProductTable` (green):** displays and filters the *ユーザー入力*に基づいた*データコレクション*を表示、選別します
51 - 4. **`ProductCategoryRow` (turquoise):** *カテゴリー*ごとに表示します。
52 - 5. **`ProductRow` (red):** *製品*の行ごとに表示します。
53 -
54 -`ProductTable`を見ると、テーブルのヘッダー("Name"と"Price"ラベルを含んでいる)が独自コンポーネントではないとわかります。これは好みの問題で、どちらの方法が良いかの議論があります。この例では、`ProductTable`の責任の範囲である*データ収集*レンダリングの一部であるため、私は`ProductTable`の一部として残しました。しかし、もしこのヘッダーが複雑になりそうであれば、(ソートにアフォーダンスを追加した場合など)新しい `ProductTableHeader` という独自コンポーネントを作る意味が高まります。
55 -
56 -
57 -私たちは自分たちのモックのコンポーネントを特定し、階層に配置してみましょう。これらは簡単です。モックの中の他のコンポーネントと一緒に使用するコンポーネントはその子供の階層にいなくてはいけません。
58 -
59 - * `FilterableProductTable`
60 - * `SearchBar`
61 - * `ProductTable`
62 - * `ProductCategoryRow`
63 - * `ProductRow`
64 -
65 -## ステップ2 : 静的なReactの構築
66 -
67 -<iframe width="100%" height="600" src="https://jsfiddle.net/reactjs/yun1vgqb/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
68 -
69 -あなたは今コンポーネントの階層を持っており、アプリを実装する時がきました。最も簡単な方法はあなたの持っているデータモデルを受け取りUIをレンダリングするが、双方向性を持っていないバージョンを構築することです。静的なバージョンを構築するには多くのコードを書く必要があるが考えることはなく、双方向性を加えるためには熟考する必要がありコード量は多くないです。そのためこれらのプロセスは分離するのが最善の手段です。理由をみていきましょう。
70 -
71 -データモデルをレンダリングさせる静的なバージョンを構築するために、あなたは他のコンポーネントを再利用したり、*props*を使用してコンポーネントを構築したいと思うでしょう。*props*とは親から子へデータを受け渡す方法のことです。もしあなたが*state*のことを知っているなら、この静的なバージョンを構築する際には**絶対にstateは使わないでください**。stateは双方向性のためにのみ予約されます。それはつまり、時間の経過とともにデータが変化していきます。静的なバージョンのアプリを作っている間はこれは必要のないものです。
72 -
73 -あなたはトップダウンでもボトムアップでも構築することができます。つまりあなたは階層の高い場所から(`FilterableProductTable`)でも、低い場所から(`ProductRow`)でもコンポーネントを構築し始めることができます。簡単な例ではトップダウンから行く方が簡単ですし、大規模なプロジェクトではボトムアップを行って、構築するテストを書く方が簡単です。
74 -
75 -この最後のステップは、データモデルをレンダリングできる再利用可能なコンポーネントのライブラリーを手に入れることです。これはあなたのアプリの静的なバージョンのため、コンポーネントは`render()`メソッドのみを持ちます。階層のトップのコンポーネント(`FilterableProductTable`)は部品としてデータモデルを持ちます。あなたが下の階層にあるデータモデルの変更を行い、`ReactDOM.render()`を呼ぶと、UIも更新されます。複雑なことは何もないので、どのようにあなたのUIが更新され、変更した場所を確認するのは簡単です。Reactの**1方向のデータフロー** (*1方向バインディング*ともよばれます。)はすべてのモジュール式と速さを保ちます。
76 -
77 -このステップでヘルプが必要な場合はここに簡単な説明があります。[React docs](/react/docs/)
78 -
79 -### コラム: props か state か?
80 -
81 -Reactにはpropsとstateの2つのタイプの"model"データがあります。この二つの違いを理解することは重要です。違いを明確に理解していない場合はここを参照してください。[the official React docs](/react/docs/interactivity-and-dynamic-uis.html)
82 -
83 -## ステップ3 : UI部品の最小限の(しかし完全な)表現を特定します
84 -
85 -UIをインタラクティブに作るために、下の階層のデータモデルを変更を行えるようにする必要があります。Reactでは **state** を使うことで簡単に行うことができます。
86 -
87 -アプリの構築を正しく行うために、まずそのアプリのニーズの可変状態の最小セットを考える必要があります。ここで重要なのはDRY、つまり繰り返さないこと、です。アプリケーションの状態の絶対的な最小表現を把握し、オンデマンドで必要他のすべてを計算します。たとえば、TODOリストを構築するとすると、TODOのリストを配列で保持し、個別にカウントの状態変数を保持しません。TODOの個数をレンダリングするときに、単にTODOのアイテムの長さを取得すればよいのです。
88 -
89 -今回のアプリケーションのデータのすべてを考えます。私たちは以下を持っています。
90 -
91 - * 独自製品のリスト
92 - * ユーザーが入力した検索テキスト
93 - * チェックボックスの値
94 - * 製品のフィルターリスト
95 -
96 -それぞれ一つを通し、それぞれの状態を把握しましょう。それぞれのデータに尋ねる質問は3つです。
97 -
98 - 1. それはpropを経由して、親から渡されますか?そうなら、おそらくstateではありません。
99 - 2. それは時間の経過とともに変化しますか?そうでないなら、おそらくstateではありません。
100 - 3. あなたはそれがコンポーネント内の他のstateやpropに基づいて計算することができますか?そうなら、おそらくstateではありません。
101 -
102 -その製品の独自のリストはpropとして渡されるので、stateではありません。検索テキストとチェックボックスは時間の経過とともに変化し、それを計算することはできないので、stateのように見えます。最後に、検索テキストとチェックボックスの値を持つ製品の独自のリストを組み合わせることによって計算することができるため、製品のフィルタリングされたリストはstateではありません。
103 -
104 -つまり最終的にstateはこうなります。
105 -
106 - * ユーザーが入力した検索テキスト
107 - * チェックボックスの値
108 -
109 -## ステップ4 : あなたのstateがあるべき場所を特定します。
110 -
111 -<iframe width="100%" height="600" src="https://jsfiddle.net/reactjs/zafjbw1e/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
112 -
113 -ここまでで、私たちはアプリの状態の最小セットが何であるかを認識することができました。次はコンポーネントの変化か、またはそれ自身の状態を特定する必要があります。
114 -
115 -メモ:Reactはすべてのデータがコンポーネントの階層が1方向に流れるものです。コンポーネントがどのような状況にあるかはすぐには明確にはならないかもしれません。** これはしばしば新しく学ぼうとする方には難しいものになるため** 把握するために次の手順に従います。
116 -
117 -アプリ内のそれぞれのstate
118 -
119 - * 幾つかのstateに基づくレンダリングをするすべてのコンポーネントを識別する
120 - * 共通の所有者を持つコンポーネント(階層内のstateを必要にするすべてのコンポーネント上にあるコンポーネント)
121 - * 階層内の最大の、共通の所有者または別のコンポーネントのいずれか
122 - * 意味のあるstateにコンポーネントを見つけることができない場合には、状態を保持するために、単純に新しいコンポーネントを作成し共通の所有者のコンポーネント上の階層のどこかに追加します。
123 -
124 -アプリケーションのためにこの戦略に沿って実行しましょう
125 -
126 - * `ProductTable`はstateに基づいた製品リストのフィルターを必要とし、 `SearchBar`は検索テキストとチェックの状態を表示する必要があります。
127 - * 共通のコンポーネントの所有者は`FilterableProductTable`です。
128 - * `FilterableProductTable`にあるフィルタテキストと確認された値は概念的に理解する。
129 -
130 -stateは`FilterableProductTable`の中にあると決定しました。まずはアプリケーションの最初の状態を反映させるため、`FilterableProductTable`に `{filterText: '', inStockOnly: false}`を返す、`getInitialState()`という関数を追加します。次に、`ProductTable` と `SearchBar`にpropとして`filterText`と`inStockOnly`を通します。最後にこれらのpropを`ProductTable`の行のフィルターに使い、`SearchBar`のフォームのフィールドの値をセットします。
131 -
132 -アプリケーションがどのように動作(`"ball"`に`filterText`をセットし、アプリを更新する)するかを見て開始することができます。データテーブルが正しく更新されていることがわかるでしょう。
133 -
134 -## ステップ5 : 逆のデータフローを追加
135 -
136 -<iframe width="100%" height="600" src="https://jsfiddle.net/reactjs/n47gckhr/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
137 -
138 -ここまで、階層の下へ向かってpropやstateの関数として正しくレンダリングするアプリを構築しました。ここからは逆の方向へのデータのフローをサポートします。深い階層のフォームのコンポーネントは`FilterableProductTable`のstateを更新する必要があります。
139 -
140 -Reactは、このデータの流れがどのようにあなたのプログラムが動くのかの理解を簡単にする流れですが、それが伝統的な双方向のデータバインディングよりも少しタイピングを必要とします。Reactは`ReactLink`という双方向バインディングを便利に実装できるアドオンを提供していますが、この投稿の目的は私たちが全てを明確にすることです。
141 -
142 -例えば、あなたが入力するか現在のバージョンのチェックボックスをオンにしようとすると、あなたの入力をReactは無視することがわかります。これは意図的なもので、私たちは常に`FilterableProductTable` から渡された` state`に等しくなるように` input`の値を設定しているためです。
143 -
144 -何を起こしたいのかを考えましょう。私たちは確かにユーザーがどのようにフォームを変えても入力した値をstateに反映させようとしています。コンポーネントが自身のstateを更新する必要があるため、`FilterableProductTable`は`SearchBar`が更新するべき時にはいつでもコールバックを渡します。入力の通知に対して`onChange`イベントを使用できます。そして`FilterableProductTable`によって渡されたコールバックは`setState()`を呼び出し、アプリが更新されます。
145 -
146 -これは複雑に見えますが、それはわずか数行のコードのみです。そしてデータがどのようにアプリ内を流れているか、とても明白です。
147 -
148 -## 以上です。
149 -この記事を通してReactでコンポーネントとアプリケーションを構築するかをどのように考えるかのヒントになれば幸いです。あなたが今まで使ってきたものよりも少しタイピングが必要かもしれないが、そのコードは書かれているよりもはるかに多くを認識し、このモジュールを読むためにとても簡単でかつ明白なコードです。あなたが大きなコンポーネントのライブラリを構築するのなら、この明示性とモジュール性に感謝するでしょうし、コードの再利用性とコードのあなたのラインが縮小し始めます。 :)
docs/docs/thinking-in-react.ko-KR.md deleted
-147
@@ -1,147 +0,0 @@
1 ----
2 -id: thinking-in-react-ko-KR
3 -title: 리액트로 생각해보기
4 -permalink: docs/thinking-in-react-ko-KR.html
5 -prev: tutorial-ko-KR.html
6 -next: videos-ko-KR.html
7 ----
8 -
9 -Pete Hunt의 글입니다.
10 -
11 -제가 생각하기에, React는 JavaScript로 크고 빠른 웹 애플리케이션을 만드는데 최고입니다. 페이스북과 인스타그램에서 우리에게 잘 맞도록 조정되어 왔습니다.
12 -
13 -React의 많은 뛰어난 점들 중 하나는 생각을 하면서 애플리케이션을 만들게 한다는 겁니다. 이 포스트에서, React를 이용해 검색이 가능한 상품자료 테이블을 만드는 생각 과정을 이해할 수 있게 차근차근 설명할 겁니다.
14 -
15 -## 모형으로 시작해보기
16 -
17 -우리가 이미 JSON API와 디자이너로부터 넘겨받은 모형을 이미 가지고 있다고 생각해봅시다. 보시다시피 우리 디자이너는 별로 좋지 않습니다:
18 -
19 -![Mockup](/react/img/blog/thinking-in-react-mock.png)
20 -
21 -우리의 JSON API는 아래와 같은 데이터를 리턴합니다:
22 -
23 -```
24 -[
25 - {category: "Sporting Goods", price: "$49.99", stocked: true, name: "Football"},
26 - {category: "Sporting Goods", price: "$9.99", stocked: true, name: "Baseball"},
27 - {category: "Sporting Goods", price: "$29.99", stocked: false, name: "Basketball"},
28 - {category: "Electronics", price: "$99.99", stocked: true, name: "iPod Touch"},
29 - {category: "Electronics", price: "$399.99", stocked: false, name: "iPhone 5"},
30 - {category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7"}
31 -];
32 -```
33 -
34 -## 1단계: UI를 계층 구조의 컴포넌트로 분쇄하세요.
35 -
36 -당신이 하고싶은 첫번째는 모형에 있는 모든 컴포넌트 (그리고 자식엘리먼트) 주위에 상자를 그리고, 이름을 부여하는 것입니다. 만약 당신이 디자이너와 같이 작업중이라면, 그들은 이미 이 작업을 해놨을지도 모릅니다. 당장 가서 이야기해보세요. 그들의 포토샵 레이어 이름이 결국 당신의 React 컴포넌트들의 이름이 될 것입니다.
37 -
38 -그런데 무엇이 컴포넌트가 되어야 할까요? 당신이 새로운 함수나 객체를 만들어야만 한다면, 똑같이 적용하세요. 한가지 방법은 [단일 책임의 원칙](http://ko.wikipedia.org/wiki/%EB%8B%A8%EC%9D%BC_%EC%B1%85%EC%9E%84_%EC%9B%90%EC%B9%99) 입니다. 즉 하나의 컴포넌트는 이상적으로 한가지 작업만 수행해야 합니다. 컴포넌트가 결국 커진다면, 작은 자식 컴포넌트로 쪼개져야 합니다.
39 -
40 -주로 JSON 데이터 모델을 사용자에게 보여주기 때문에, 자료 모델이 잘 설계 되었다면, UI(혹은 컴포넌트 구조)가 잘 맞아 떨어진다는 것을 알게 될 겁니다. UI와 자료 모델은 같은 *정보 설계구조*로 따라가는 경향이 있기 때문입니다. 즉, UI를 컴포넌트들로 쪼개는 작업은 크게 어렵지 않습니다. 확실하게 각각 하나의 부분이 되도록 쪼개세요.
41 -
42 -![Component diagram](/react/img/blog/thinking-in-react-components.png)
43 -
44 -이 간단한 애플리케이션에는 다섯개의 컴포넌트가 있습니다. 각 컴포넌트들이 대표하는 자료를 기울여 표기했습니다.
45 -
46 - 1. **`FilterableProductTable` (오렌지):** 예제 전부를 포함합니다.
47 - 2. **`SearchBar` (파랑):** 모든 *사용자 입력* 을 받습니다.
48 - 3. **`ProductTable` (초록):** *자료 모음*을 *사용자 입력*에 맞게 거르고 보여줍니다.
49 - 4. **`ProductCategoryRow` (청록):** 각 *카테고리*의 제목을 보여줍니다.
50 - 5. **`ProductRow` (빨강):** 각 *프로덕트*를 보여줍니다.
51 -
52 -`ProductTable`을 보면, 테이블 제목("Name", "Price" 라벨들을 포함한)은 컴포넌트가 아닌것을 알 수 있습니다. 이건 기호의 문제이고, 어느쪽으로 만들던 논쟁거리입니다. 이 예제에서는, 저는 *자료 모음*을 그리는 `ProductTable`의 의무라고 생각했기 때문에 남겨 두었습니다. 하지만, 이 제목이 복잡해진다면 (예를 들어 정렬을 추가할 여유가 있다거나 하는), 이건 확실히 `ProductTableHeader` 컴포넌트로 만드는 것이 맞을 겁니다.
53 -
54 -이제 모형에 들어있는 컴포넌트들에 대해 알아보았으니, 계층 구조로 만들어 봅시다. 이건 쉽습니다. 다른 컴포넌트 속에 들어있는 컴포넌트를 자식으로 나타내기만 하면 됩니다.
55 -
56 - * `FilterableProductTable`
57 - * `SearchBar`
58 - * `ProductTable`
59 - * `ProductCategoryRow`
60 - * `ProductRow`
61 -
62 -## 2단계: 정적 버전을 만드세요.
63 -
64 -<iframe width="100%" height="600" src="https://jsfiddle.net/reactjs/yun1vgqb/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
65 -
66 -계층구조의 컴포넌트들을 가지고 있으니, 이젠 애플리케이션을 구현할 시간입니다. 가장 쉬운 방법은 상호작용을 하지 않는 채로 자료 모델을 이용해 UI를 그리는 것입니다. 정적 버전을 만드는 데에는 적은 생각과 많은 노동이 필요하고, 상호작용을 추가하는 데에는 많은 생각과 적은 노동이 필요하기 때문에 둘을 분리하는 것이 가장 좋습니다. 왜 그런지 봅시다.
67 -
68 -자료 모델을 그리는 애플리케이션의 정적버전을 만들기 위해서, 다른 컴포넌트에 재사용할 컴포넌트를 만들고 자료 전달을 위해 *props*를 사용하고 싶을 것입니다. 만약 *상태*라는 개념에 익숙하다면, 정적 버전을 만들때 **절대 상태를 사용하지 마세요**. 상태는 오직 상호작용, 즉 가변적인 자료를 위해서만 준비되어 있습니다. 정적 버전을 만들 때는 필요가 없습니다.
69 -
70 -껍데기부터 혹은 속알맹이부터 만들 수 있습니다. 즉 계층구조상 위에서부터 (`FilterableProductTable` 부터) 혹은 아래에서부터 (`ProductRow`), 어느 방향에서든 시작해도 됩니다. 통상 큰 프로젝트에서는 계층구조상 위에서부터 시작하는 것이 쉽고, 테스트를 작성할때는, 아래에서부터 시작하는 것이 쉽습니다.
71 -
72 -이 단계의 결과, 자료 모델을 그리는 재활용 가능한 컴포넌트의 라이브러리를 갖게 되었습니다. 정적버전 이후로 컴포넌트들은 오직 `render()` 메소드만 갖고 있습니다. 계층구조상 가장 위의 컴포넌트 (`FilterableProductTable`)은 자료 모델을 prop으로 취할 것입니다. 자료 모델이 변했을 때, `ReactDOM.render()`를 다시 부르면 UI가 업데이트 됩니다. 어떻게 UI가 업데이트 되는지 참 알기 쉽습니다. 자료가 바뀌어도 처리해야 할 복잡한 일이 아무것도 없습니다. React의 **단일 방향 자료 흐름** (혹은 *단일방향 바인딩*)이 모든것을 모듈식으로, 추론하기 쉽게, 그리고 빠르게 유지해줍니다.
73 -
74 -이 단계를 진행하는 데에 도움이 필요하시다면, [React 문서](/react/docs/getting-started-ko-KR.html)를 참조하세요.
75 -
76 -### 잠시만: props vs state
77 -
78 -React 에는 두가지 타입의 자료 "모델"이 있습니다: props 와 state. 두가지의 구분점을 이해하는데 매우 중요합니다; 혹시 차이점을 확신하지 못한다면 걷어내세요 [공식 문서](/react/docs/interactivity-and-dynamic-uis-ko-KR.html).
79 -
80 -## 3단계: UI state 의 표현을 작지만 완전하도록 확인하세요.
81 -
82 -상호적인 UI를 만들기 위해서는, 자료 모델 변화에 반응할 수 있어야 합니다. React는 **state**로 이걸 쉽게 만들어주죠.
83 -
84 -올바르게 애플리케이션을 만들기 위해서는, 첫째로 애플리케이션에 필요한 변할 수 있는 state 들의 최소한의 집합에 대해서 생각해볼 필요가 있습니다. 여기 방법이 있습니다: *스스로 반복하지 마세요* (DRY). 애플리케이션의 상태를 나타낼 수 있는 가장 최소한의 표현 방식을 찾고, 그 밖의 것은 필요할 때 계산합니다. 예를들어 TODO 목록를 만든다고 칩시다. TODO 아이템들의 배열만 유지하세요; 갯수를 표현하기 위한 state 변수를 분리하지 마세요. 대신 TODO 아이템들 배열의 길이를 이용하세요.
85 -
86 -예제 애플리케이션에서의 모든 자료유형에 대해 생각해 봅시다:
87 -
88 - * product 들의 원본 목록
89 - * 사용자가 입력한 검색어
90 - * 체크박스의 값
91 - * product 들의 필터된 목록
92 -
93 -어느것이 state 가 될지 따져봅시다. 간단하게 각 자료에 대해 세가지만 생각해 보세요.
94 -
95 - 1. 만약 부모로부터 props 를 이용해 전달됩니까? 그렇다면 이건 state가 아닙니다.
96 - 2. 종종 바뀝니까? 아니라면 이것 역시 state가 아닙니다.
97 - 3. 컴포넌트에 있는 다른 state나 props를 통해서 계산되어질 수 있습니까? 역시 state가 아닙니다.
98 -
99 -product 들의 원본 목록은 props를 통해서 전달되기 때문에, state가 아닙니다. 검색어와 체크박스의 값은 다른것에 의해 계산될 수 있는 값이 아니고, 시시각각 변하기때문에 state가 맞습니다. 마지막으로 product 들의 걸러진 목록 역시 state가 아닙니다. 원본 목록과 검색어, 체크박스의 값 등에 의해 연산되어지는 값이기 때문이죠.
100 -
101 -결국, state는 다음과 같습니다:
102 -
103 - * 사용자가 입력한 검색어
104 - * 체크박스의 값
105 -
106 -## 4단계: 어디서 state가 유지되어야 하는지 확인하세요.
107 -
108 -<iframe width="100%" height="600" src="https://jsfiddle.net/reactjs/zafjbw1e/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
109 -
110 -이제 최소한의 state가 무엇인지 알아냈습니다. 다음은, 어떤 컴포넌트가 이 state를 변형하거나 만들어낼지 알아내야 합니다.
111 -
112 -기억하세요: React는 계층적 아래 컴포넌트로만 향하는 단일방향성 자료 흐름을 가집니다. 지금당장은 어떤 컴포넌트가 자기 자신의 state를 가져야 할지 명확하지 않을 것입니다. **이것이 초심자가 가장 이해하기 어려운 부분입니다**. 이제 개념을 명확히 하기 위해 다음으로 따라가 봅시다:
113 -
114 -애플리케이션에서 state의 경우:
115 -
116 - * 모든 컴포넌트가 state를 통해 무언가를 그려냅니다.
117 - * 대표 컴포넌트가 뭔지 찾으세요 (계층적으로 다른 컴포넌트들의 단일 상위 컴포넌트는 state를 가질 필요가 있습니다).
118 - * 대표 컴포넌트 혹은 또다른 컴포넌트는 가능한 상위의 컴포넌트가 state를 소유해야 합니다.
119 - * 만약 state를 가져야할 컴포넌트가 어느 것인지 모르겠으면, 새로운 컴포넌트를 만들어 state를 부여하고 기존의 대표 컴포넌트 위에 추가하세요.
120 -
121 -이 전략을 우리 애플리케이션에 적용해 봅시다.
122 -
123 - * `ProductTable`은 state에 대해 걸러질 필요가 있고, `SearchBar` 역시 검색어 state와 체크박스 state를 보여줄 필요가 있습니다.
124 - * 대표 컴포넌트는 `FilterableProductTable` 입니다.
125 - * 개념적으로 검색어와 체크박스 값은 `FilterableProductTable`에 있어야 한다는 것이 명확합니다.
126 -
127 -좋습니다. state를 `FilterableProductTable`에서 관리하도록 결정했습니다. 먼저, `getInitialState()` 메소드를 `FilterableProductTable`에 추가하세요. 이 메소드는 애플리케이션의 초기 state를 갖도록 `{filterText: '', inStockOnly: false}`를 리턴하면 됩니다. 그리고, `filterText`와 `inStockOnly` 를 `ProductTable`과 `SearchBar`에 prop으로 전달하세요. 마지막으로, 이 prop들을 `ProductTable`을 걸러내는 데, 그리고 `SearchBar` form fields의 값을 세팅하는데 사용하세요.
128 -
129 -이제 어떻게 애플리케이션이 동작하는지 볼 수 있습니다: `filterText`를 `"ball"`로 설정하고 업데이트합니다. 자료 테이블이 제대로 업데이트 되는 것을 볼 수 있을 겁니다.
130 -
131 -## 5단계: 반대방향 자료 흐름을 추가하세요.
132 -
133 -<iframe width="100%" height="600" src="https://jsfiddle.net/reactjs/n47gckhr/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
134 -
135 -앞서 우리는 계층적으로 아랫방향 흐름의 props, state전달로 잘 동작하는 애플리케이션을 만들었습니다. 이제 다른방향의 자료 흐름을 지원할 시간입니다: form 컴포넌트들은 `FilterableProductTable`의 state를 업데이트할 필요성이 있죠.
136 -
137 -React는 어떻게 이 프로그램이 동작하는지 이해하기 쉽게 이 자료의 흐름을 명시적으로 만들어주지만 전통적인 두 방향의 자료 바인딩보다 다소 입력할 것이 많습니다. React는 이러한 패턴을 양방향 바인딩처럼 편하게 사용할 수 있도록 ReactLink를 제공하지만, 이 글의 목적상 명시적인 방식만 사용했습니다.
138 -
139 -지금 예제에 문자열을 입력하거나 체크박스를 체크하더라도, React가 입력을 무시하는것을 볼 수 있습니다. 의도적으로 `input`의 prop에 `value`를 세팅하면 항상 `state`가 `FilterableProductTable`로부터 전달되어야 합니다.
140 -
141 -우리가 원하는 것이 무엇인지 생각해 봅시다. 사용자 입력을 반영하기 위해, 사용자가 form을 바꿀때마다 업데이트 하기를 원하죠. 컴포넌트들이 오직 자기 자신의 state만 업데이트 하더라도 `FilterableProductTable`은 state가 변할때마다 반영되어야할 `SearchBar`에 콜백을 전달할 것입니다. 이 알림을 위해서 `onChange`이벤트를 사용할 수 있습니다. 그리고 `FilterableProductTable`으로부터 전달된 콜백은 `setState()`를 호출할 것이고, 애플리케이션은 업데이트될 것입니다.
142 -
143 -복잡하게 들릴 수 있지만, 실제로는 몇 줄 되지 않습니다. 그리고 애플리케이션의 구석구석에서 데이터가 어떻게 흐르는지 매우 명확해집니다.
144 -
145 -## 그리고
146 -
147 -이 글이 컴포넌트와 React로 애플리케이션을 어떻게 만들지에 대한 아이디어가 되길 바랍니다. 원래 하던 방식보다 조금 타이핑을 더 해야할지도 모르지만, 코드는 쓰는 경우보다 읽히는 경우가 많다는 점, 매우 읽기 편하고 명시적인 코드를 썼다는 점을 기억하세요. 컴포넌트로 큰 라이브러리를 만들기 시작할 때, 이 명시성과 모듈성에 감사하게 될 것이며, 재사용함에 따라 코드의 양도 줄어들 것입니다. :)
docs/docs/thinking-in-react.md
+19 -19
@@ -2,18 +2,15 @@
2 id: thinking-in-react
3 title: Thinking in React
4 permalink: docs/thinking-in-react.html
5 -prev: tutorial.html
6 -next: conferences.html
5 redirect_from: 'blog/2013/11/05/thinking-in-react.html'
6 +prev: composition-vs-inheritance.html
7 ---
8
10 -by Pete Hunt
9 +React is, in our opinion, the premier way to build big, fast Web apps with JavaScript. It has scaled very well for us at Facebook and Instagram.
10
12 -React is, in my opinion, the premier way to build big, fast Web apps with JavaScript. It has scaled very well for us at Facebook and Instagram.
11 +One of the many great parts of React is how it makes you think about apps as you build them. In this document, we'll walk you through the thought process of building a searchable product data table using React.
12
14 -One of the many great parts of React is how it makes you think about apps as you build them. In this post, I'll walk you through the thought process of building a searchable product data table using React.
15 -
16 -## Start with a mock
13 +## Start With A Mock
14
15 Imagine that we already have a JSON API and a mock from our designer. Our designer apparently isn't very good because the mock looks like this:
16
@@ -32,7 +29,7 @@ Our JSON API returns some data that looks like this:
29 ];
30 ```
31
35 -## Step 1: Break the UI into a component hierarchy
32 +## Step 1: Break The UI Into A Component Hierarchy
33
34 The first thing you'll want to do is to draw boxes around every component (and subcomponent) in the mock and give them all names. If you're working with a designer, they may have already done this, so go talk to them! Their Photoshop layer names may end up being the names of your React components!
35
@@ -42,7 +39,7 @@ Since you're often displaying a JSON data model to a user, you'll find that if y
39
40 ![Component diagram](/react/img/blog/thinking-in-react-components.png)
41
45 -You'll see here that we have five components in our simple app. I've italicized the data each component represents.
42 +You'll see here that we have five components in our simple app. We've italicized the data each component represents.
43
44 1. **`FilterableProductTable` (orange):** contains the entirety of the example
45 2. **`SearchBar` (blue):** receives all *user input*
@@ -50,7 +47,7 @@ You'll see here that we have five components in our simple app. I've italicized
47 4. **`ProductCategoryRow` (turquoise):** displays a heading for each *category*
48 5. **`ProductRow` (red):** displays a row for each *product*
49
53 -If you look at `ProductTable`, you'll see that the table header (containing the "Name" and "Price" labels) isn't its own component. This is a matter of preference, and there's an argument to be made either way. For this example, I left it as part of `ProductTable` because it is part of rendering the *data collection* which is `ProductTable`'s responsibility. However, if this header grows to be complex (i.e. if we were to add affordances for sorting), it would certainly make sense to make this its own `ProductTableHeader` component.
50 +If you look at `ProductTable`, you'll see that the table header (containing the "Name" and "Price" labels) isn't its own component. This is a matter of preference, and there's an argument to be made either way. For this example, we left it as part of `ProductTable` because it is part of rendering the *data collection* which is `ProductTable`'s responsibility. However, if this header grows to be complex (i.e. if we were to add affordances for sorting), it would certainly make sense to make this its own `ProductTableHeader` component.
51
52 Now that we've identified the components in our mock, let's arrange them into a hierarchy. This is easy. Components that appear within another component in the mock should appear as a child in the hierarchy:
53
@@ -60,9 +57,10 @@ Now that we've identified the components in our mock, let's arrange them into a
57 * `ProductCategoryRow`
58 * `ProductRow`
59
63 -## Step 2: Build a static version in React
60 +## Step 2: Build A Static Version in React
61
65 -<iframe width="100%" height="600" src="https://jsfiddle.net/reactjs/yun1vgqb/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
62 +<p data-height="600" data-theme-id="0" data-slug-hash="vXpAgj" data-default-tab="js" data-user="lacker" data-embed-version="2" class="codepen">See the Pen <a href="http://codepen.io/lacker/pen/vXpAgj/">Thinking In React: Step 2</a> on <a href="http://codepen.io">CodePen</a>.</p>
63 +<script async src="//assets.codepen.io/assets/embed/ei.js"></script>
64
65 Now that you have your component hierarchy, it's time to implement your app. The easiest way is to build a version that takes your data model and renders the UI but has no interactivity. It's best to decouple these processes because building a static version requires a lot of typing and no thinking, and adding interactivity requires a lot of thinking and not a lot of typing. We'll see why.
66
@@ -74,11 +72,11 @@ At the end of this step, you'll have a library of reusable components that rende
72
73 Simply refer to the [React docs](/react/docs/) if you need help executing this step.
74
77 -### A brief interlude: props vs state
75 +### A Brief Interlude: Props vs State
76
77 There are two types of "model" data in React: props and state. It's important to understand the distinction between the two; skim [the official React docs](/react/docs/interactivity-and-dynamic-uis.html) if you aren't sure what the difference is.
78
81 -## Step 3: Identify the minimal (but complete) representation of UI state
79 +## Step 3: Identify The Minimal (but complete) Representation Of UI State
80
81 To make your UI interactive, you need to be able to trigger changes to your underlying data model. React makes this easy with **state**.
82
@@ -104,9 +102,10 @@ So finally, our state is:
102 * The search text the user has entered
103 * The value of the checkbox
104
107 -## Step 4: Identify where your state should live
105 +## Step 4: Identify Where Your State Should Live
106
109 -<iframe width="100%" height="600" src="https://jsfiddle.net/reactjs/zafjbw1e/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
107 +<p data-height="600" data-theme-id="0" data-slug-hash="ORzEkG" data-default-tab="js" data-user="lacker" data-embed-version="2" class="codepen">See the Pen <a href="http://codepen.io/lacker/pen/ORzEkG/">Thinking In React: Step 4</a> by Kevin Lacker (<a href="http://codepen.io/lacker">@lacker</a>) on <a href="http://codepen.io">CodePen</a>.</p>
108 +<script async src="//assets.codepen.io/assets/embed/ei.js"></script>
109
110 OK, so we've identified what the minimal set of app state is. Next, we need to identify which component mutates, or *owns*, this state.
111
@@ -129,9 +128,10 @@ Cool, so we've decided that our state lives in `FilterableProductTable`. First,
128
129 You can start seeing how your application will behave: set `filterText` to `"ball"` and refresh your app. You'll see that the data table is updated correctly.
130
132 -## Step 5: Add inverse data flow
131 +## Step 5: Add Inverse Data Flow
132
134 -<iframe width="100%" height="600" src="https://jsfiddle.net/reactjs/n47gckhr/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
133 +<p data-height="600" data-theme-id="0" data-slug-hash="ALxdJq" data-default-tab="js" data-user="lacker" data-embed-version="2" class="codepen">See the Pen <a href="http://codepen.io/lacker/pen/ALxdJq/">Thinking In React: Step 5</a> on <a href="http://codepen.io">CodePen</a>.</p>
134 +<script async src="//assets.codepen.io/assets/embed/ei.js"></script>
135
136 So far, we've built an app that renders correctly as a function of props and state flowing down the hierarchy. Now it's time to support data flowing the other way: the form components deep in the hierarchy need to update the state in `FilterableProductTable`.
137
@@ -143,6 +143,6 @@ Let's think about what we want to happen. We want to make sure that whenever the
143
144 Though this sounds complex, it's really just a few lines of code. And it's really explicit how your data is flowing throughout the app.
145
146 -## And that's it
146 +## And That's It
147
148 Hopefully, this gives you an idea of how to think about building components and applications with React. While it may be a little more typing than you're used to, remember that code is read far more than it's written, and it's extremely easy to read this modular, explicit code. As you start to build large libraries of components, you'll appreciate this explicitness and modularity, and with code reuse, your lines of code will start to shrink. :)
docs/docs/thinking-in-react.zh-CN.md deleted
-148
@@ -1,148 +0,0 @@
1 ----
2 -id: thinking-in-react-zh-CN
3 -title: React 编程思想
4 -permalink: docs/thinking-in-react-zh-CN.html
5 -prev: tutorial-zh-CN.html
6 -next: conferences-zh-CN.html
7 -redirect_from: 'blog/2013/11/05/thinking-in-react.html'
8 ----
9 -
10 -by Pete Hunt
11 -
12 -在我看来,React 是构建大型,快速 Web app 的首选方式。它已经在 Facebook 和 Instagram 被我们有了广泛的应用。
13 -
14 -React 许多优秀的部分之一,是它使得你在构建 app 的过程中不断思考。在本文里,我将带你经历一次使用 React 构建可搜索的商品数据表的思考过程。
15 -
16 -## 从模型(mock)开始
17 -
18 -想象我们已经有个一个 JSON API 和一个来自设计师的模型。我们的设计师显然做得不够好,因为模型看起来像这样:
19 -
20 -![Mockup](/react/img/blog/thinking-in-react-mock.png)
21 -
22 -我们的 JSON API 返回一些看起来像这样的数据:
23 -
24 -```
25 -[
26 - {category: "Sporting Goods", price: "$49.99", stocked: true, name: "Football"},
27 - {category: "Sporting Goods", price: "$9.99", stocked: true, name: "Baseball"},
28 - {category: "Sporting Goods", price: "$29.99", stocked: false, name: "Basketball"},
29 - {category: "Electronics", price: "$99.99", stocked: true, name: "iPod Touch"},
30 - {category: "Electronics", price: "$399.99", stocked: false, name: "iPhone 5"},
31 - {category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7"}
32 -];
33 -```
34 -
35 -## 第一步:把UI拆分为一个组件的层级
36 -
37 -首先你想要做的,是在模型里的每一个组件周围绘制边框,并给它们命名。如果你和设计师一起工作,他们应该已经完成这步了,所以去和他们谈谈!他们的 Photoshop 图层名也许最终会成为你的 React 组件名。
38 -
39 -但是你如何知道什么东西应该是独立的组件?只需在你创建一个函数或者对象时,根据是否使用过相同技术来做决定。一种这样的技术是[单一功能原则(single responsibility principle)](https://en.wikipedia.org/wiki/Single_responsibility_principle),也就是一个组件在理想情况下只做一件事情。如果它最终增长了,它就应该被分解为更小的组件。
40 -
41 -既然你频繁显示一个 JSON 的数据模型给用户,你会发现,如果你的模型构建正确,你的 UI(因此也有你的组件结构)就将映射良好。那是因为 UI 和数据模型趋向附着于相同的 *信息架构*,这意味着,把你的 UI 分离为组件的工作通常是琐碎的,只需把 UI 拆分成能准确对应数据模型的每块组件。
42 -
43 -![Component diagram](/react/img/blog/thinking-in-react-components.png)
44 -
45 -在这里你会看到,在我们的简单 APP 里有五个组件。我用斜体表示每个组件的数据。
46 -
47 - 1. **`FilterableProductTable` (橙色):** 包含示例的整体
48 - 2. **`SearchBar` (蓝色):** 接收所有 *用户输入*
49 - 3. **`ProductTable` (绿色):** 基于 *用户输入* 显示和过滤 *数据集合(data collection)*
50 - 4. **`ProductCategoryRow` (蓝绿色):** 为每个 *分类* 显示一个列表头
51 - 5. **`ProductRow` (红色):** 为每个 *商品* 显示一行
52 -
53 -如果你看着 `ProductTable`,你会看到表头(包含了 "Name" 和 "Price" 标签) 不是独立的组件。这是一个个人喜好问题,并且无论采用哪种方式都有争论。对于这个例子,我把它留做 `ProductTable` 的一部分,因为它是 *data collection*渲染的一部分,而 *data collection* 渲染是 `ProductTable` 的职责。然而,当列表头增长到复杂的时候(例如 如果我们添加排序功能),那么使它成为独立的 `ProductTableHeader` 组件无疑是有意义的。
54 -
55 -既然现在我们已经识别出了我们模型中的组件,让我们把他们安排到一个层级中。这很容易。在模型中,出现在一个组件里面的另一组件 ,应该在层级中表现为一种子级关系:
56 -
57 - * `FilterableProductTable`
58 - * `SearchBar`
59 - * `ProductTable`
60 - * `ProductCategoryRow`
61 - * `ProductRow`
62 -
63 -## 第二步:用React创建一个静态版本
64 -
65 -<iframe width="100%" height="600" src="https://jsfiddle.net/reactjs/yun1vgqb/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
66 -
67 -既然你已经有了你的组件层级,是时候实现你的app了。简单的方式是构建一个版本,它取走你的数据模型并渲染UI,除了没有互动性。这是将过程解耦的最好办法,因为构建一个静态版本需要不假思索地写很多代码,而添加互动性需要很多思考但不需要太多代码。之后我们将会看到原因。
68 -
69 -要构建一个静态版本 app 来渲染你的数据模型,你将会想到构建一个重用其它组件并利用 *props* 传递数据的组件。*props* 是一种从父级传递数据到子级的方式。如果你对 *state* 的观念很熟悉,**绝不要用state** 来构建这个静态版本。State 仅仅是为互动性,也就是随时间变化的数据所预留的。由于这是一个静态版本,你还不需要用到它。
70 -
71 -你可以自顶向下或自底向上的构建。也就是说,你可以既从较高的层级(比如从 `FilterableProductTable` 开始)也可以从较低的层级(`ProductRow`)开始构建组件。在较简单的例子里,通常自顶向下要容易一些,然而在更大的项目上,自底向上地构建更容易,并且更方便伴随着构建写测试。
72 -
73 -在这一步的最后,你会获得一个渲染数据模型的可重用组件库。这些组件只有 `render()` 方法,因为这是一个静态版本。在层级顶端的组件 (`FilterableProductTable`) 将会接受你的数据模型,并将其作为一个prop。如果你改变了底层数据模型,并且再次调用 `React.render()` ,UI 将会更新。你可以很容易地看到 UI 是如何更新的,以及哪里变动了,因为这没什么复杂的。React的 **单向数据流** (也被称为 *单向绑定*)使一切保持了模块化和快速。
74 -
75 -如果你在执行这步时需要帮助,请参阅 [React 文档](/react/docs/)。
76 -
77 -### 小插曲: props vs state
78 -
79 -在React里有两种数据 "模型": props 和 state。明白这二者之间的区别是很重要的;如果你不是很确定它们之间的区别,请概览[React官方文档](/react/docs/interactivity-and-dynamic-uis-zh-CN.html)
80 -
81 -## 第三步:确定最小(但完备)的 UI state 表达
82 -
83 -要让你的 UI 互动,你需要做到触发底层数据模型发生变化。React用 **state** 来让此变得容易。
84 -
85 -要正确的构建你的 app,你首先需要思考你的 app 需要的可变 state 的最小组。这里的关键是 DRY 原则:*Don't Repeat Yourself(不要重复自己)*。想出哪些是你的应用需要的绝对最小 state 表达,并按需计算其他任何数据。例如,如果你要构建一个 TODO list,只要保持一个 TODO 项的数组;不要为了计数保持一个单独的 state 变量。当你想渲染 TODO 的计数时,简单的采用 TODO 项目的数组长度作为替代。
86 -
87 -考虑我们示例应用中的数据所有块,包括:
88 -
89 - * 原始的商品列表
90 - * 用户输入的搜索文本
91 - * 复选框的值
92 - * 商品的过滤列表
93 -
94 -让我们逐个检查出哪一个是state,只需要简单地问以下三个问题:
95 -
96 - 1. 它是通过props从父级传递来的吗?如果是,它可能不是 state。
97 - 2. 它随时间变化吗?如果不是,它可能不是 state。
98 - 3. 你能基于其他任何组件里的 state 或者 props 计算出它吗?如果是,它可能不是state.
99 -
100 -原始的商品列表以 props 传入,所以它不是 state。搜索文本和复选框看起来是 state,因为他们随时间变化并且不能从任何东西计算出。最后,过滤出的商品列表不是 state,因为它可以通过原始列表与搜索文本及复选框的值组合计算得出。
101 -
102 -所以最后,我们的 state 是:
103 -
104 - * 用户输入的搜索文本
105 - * checkbox 的值
106 -
107 -## 第四步:确定你的 state 应该存在于哪里
108 -
109 -<iframe width="100%" height="600" src="https://jsfiddle.net/reactjs/zafjbw1e/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
110 -
111 -OK,我们已经确定好应用的最小 state 集合是什么。接下来,我们需要确定哪个组件可以改变,或者 *拥有* 这个state.
112 -
113 -记住:React 总是在组件层级中单向数据流动的。可能不能立刻明白哪些组件应该拥有哪些 state。 **这对于新手在理解上经常是最具挑战的一部分,** 所以跟着这几步来弄明白它:
114 -
115 -对于你的应用里每一个数据块:
116 -
117 - * 确定哪些组件要基于 state 来渲染内容。
118 - * 找到一个共同的拥有者组件(在所有需要这个state组件的层次之上,找出共有的单一组件)。
119 - * 要么是共同拥有者,要么是其他在层级里更高级的组件应该拥有这个state。
120 - * 如果你不能找到一个组件让其可以有意义地拥有这个 state,可以简单地创建一个新的组件 hold 住这个state,并把它添加到比共同拥有者组件更高的层级上。
121 -
122 -让我们使用这个策略浏览一遍我们的应用:
123 -
124 - * `ProductTable` 需要基于 state 过滤产品列表,`SearchBar` 需要显示搜索文本和选择状态。
125 - * 共同拥有者组件是 `FilterableProductTable`。
126 - * 对于过滤文本和选择框值存在于 `FilterableProductTable`,从概念上讲是有意义的。
127 -
128 -酷,我们已经决定了我们的 state 存在于 `FilterableProductTable`。首先,添加一个 `getInitialState()` 方法到 `FilterableProductTable`,返回 `{filterText: '', inStockOnly: false}` 来反映应用的初始状态。然后,传递`filterText` 和 `inStockOnly` 给 `ProductTable` 和 `SearchBar` 作为 prop。最后,使用这些 prop 来过滤 `ProductTable` 中的行和设置 `SearchBar` 的表单项的值。
129 -
130 -你可以开始看看你的应用将有怎样的行为了: 设置 `filterText` 为 `"ball"` 并刷新你的 app。你将可以看到数据表被正确地更新。
131 -
132 -## 第五步:添加反向数据流
133 -
134 -<iframe width="100%" height="600" src="https://jsfiddle.net/reactjs/n47gckhr/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
135 -
136 -到目前为止,我们已经构建了一个应用, 它以 props 和 state 沿着层级向下流动的功能正确渲染。现在是时候支持另一种数据流动了:在层级深处的表单组件需要更新 `FilterableProductTable` 里的 state。
137 -
138 -React 让数据显式流动,使你理解应用如何工作变得简单,但是相对于传统的双向数据绑定,确实需要多打一些字。React 提供了一个叫做 `ReactLink` 的插件来使这种模式和双向数据绑定一样方便,但是考虑到这篇文章的目的,我们将会保持所有东西都直截了当。
139 -
140 -如果你尝试在当前版本的示例中输入或者选中复选框,你会发现 React 忽略了你的输入。这是有意的,因为我们已经设置了 `input` 的 `value` prop 值总是与 `FilterableProductTable` 传递过来的 `state` 一致。
141 -
142 -让我们思考下希望发生什么。我们想确保每当用户改变表单,就通过更新 state 来反映用户的输入。由于组件应该只更新自己拥有的 state , `FilterableProductTable` 将会传递一个回调函数给 `SearchBar` ,每当 state 应被更新时回调函数就会被调用。我们可以使用 input 的 `onChange` 事件来接受它的通知。 `FilterableProductTable` 传递的回调函数将会调用 `setState()` ,然后应用将会被更新。
143 -
144 -虽然这听起来复杂,但是实际上只是数行代码。并且这明确显示出了数据在应用中从始至终是如何流动的。
145 -
146 -## 好了,就是这样
147 -
148 -希望这给了你一个怎样思考用React构建组件和应用的概念。虽然可能比你过往的习惯要多敲一点代码,但记住,读代码的时间远比写代码的时间多,并且阅读这种模块化的、显式的代码是极为容易的。当你开始构建大型组件库时,你会非常感激这种清晰性和模块化,并且随着代码的重用,你的代码行数将会开始缩减。:)
docs/docs/tutorial.it-IT.md deleted
-719
@@ -1,719 +0,0 @@
1 ----
2 -id: tutorial-it-IT
3 -title: Tutorial
4 -permalink: docs/tutorial-it-IT.html
5 -prev: getting-started-it-IT.html
6 -next: thinking-in-react-it-IT.html
7 ----
8 -
9 -Costruiremo una semplice ma realistica casella dei commenti che puoi inserire in un blog, una versione base dei commenti in tempo reale offerti da Disqus, LiveFyre o Facebook.
10 -
11 -Forniremo:
12 -
13 -* Una vista di tutti i commenti
14 -* Un modulo per inviare un commento
15 -* Hook perché tu fornisca un backend personalizzato
16 -
17 -Avrà anche un paio di caratteristiche interessanti:
18 -
19 -* **Commenti ottimistici:** i commenti appaiono nella lista prima che vengano salvati sul server, in modo da sembrare più veloce.
20 -* **Aggiornamenti in tempo reale:** i commenti degli altri utenti sono aggiunti alla vista dei commenti in tempo reale.
21 -* **Formattazione Markdown:** gli utenti possono utilizzare il Markdown per formattare il proprio testo.
22 -
23 -### Vuoi saltare tutto questo e vedere semplicemente il sorgente?
24 -
25 -[It's all on GitHub.](https://github.com/reactjs/react-tutorial)
26 -
27 -### Eseguire un server
28 -
29 -Per cominciare questo tutorial dobbiamo richiedere un server in esecuzione. Questo servirà puramente come un endpoint per le API che useremo per ottenere e salvare i dati. Per rendere questo compito il più semplice possibile, abbiamo creato un seplice server in un numero di linguaggi di scripting che fa esattamente ciò che ci serve. **Puoi [leggere il sorgente](https://github.com/reactjs/react-tutorial/) o [scaricare un file zip](https://github.com/reactjs/react-tutorial/archive/master.zip) contenente tutto ciò che ti serve per cominciare.**
30 -
31 -Per semplicità, il server che eseguiremo usa un file `JSON` come database. Non è ciò che eseguiresti in produzione, ma rende più facile simulare ciò che faresti per consumare una API. Non appena avvii il server, supporterà il nostro endpoint API e servirà anche le pagine statiche di cui abbiamo bisogno.
32 -
33 -### Per Cominciare
34 -
35 -Per questo tutorial renderemo il tutto il più semplice possibile. Incluso nel pacchetto del server discusso in precedenza si trova un file HTML su cui lavoreremo. Apri `public/index.html` nel tuo editor preferito. Dovrebbe apparire simile a quanto segue (con qualche piccola differenza, aggiungeremo un tag `<script>` aggiuntivo in seguito):
36 -
37 -```html
38 -<!-- index.html -->
39 -<!DOCTYPE html>
40 -<html>
41 - <head>
42 - <meta charset="utf-8" />
43 - <title>React Tutorial</title>
44 - <script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script>
45 - <script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
46 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
47 - <script src="https://unpkg.com/jquery@3.1.0/dist/jquery.min.js"></script>
48 - <script src="https://unpkg.com/remarkable@1.7.1/dist/remarkable.min.js"></script>
49 - </head>
50 - <body>
51 - <div id="content"></div>
52 - <script type="text/babel" src="scripts/example.js"></script>
53 - <script type="text/babel">
54 - // To get started with this tutorial running your own code, simply remove
55 - // the script tag loading scripts/example.js and start writing code here.
56 - </script>
57 - </body>
58 -</html>
59 -```
60 -
61 -Nel resto di questo tutorial, scriveremo il nostro codice JavaScript in questo tag script. Non disponiamo di alcun aggiornamento in tempo reale avanzato, quindi dovremo aggiornare il browser per vedere gli aggiornamenti dopo il salvataggio. Segui il tuo progresso aprendo `http://localhost:3000` nel tuo browser (dopo aver avviato il server). Quando carichi la pagina per la prima volta senza apportare cambiamenti, vedrai il risultato finale di ciò che ci apprestiamo a costruire. Quando sei pronto per cominciare a lavorare, elimina il tag `<script>` precedente e quindi sei pronto a continuare.
62 -
63 -> Nota:
64 ->
65 -> Abbiamo incluso jQuery perché vogliamo semplificare il codice delle nostre chiamate ajax future, ma **NON** è richiesto per far funzionare React.
66 -
67 -### Il tuo primo componente
68 -
69 -In React ciò che importa sono i componenti modulari e componibili. Per il nostro esempio della casella dei commenti, avremo la seguente struttura dei componenti:
70 -
71 -```
72 -- CommentBox
73 - - CommentList
74 - - Comment
75 - - CommentForm
76 -```
77 -
78 -Costruiamo il componente `CommentBox`, che consiste in un semplice `<div>`:
79 -
80 -```javascript
81 -// tutorial1.js
82 -var CommentBox = React.createClass({
83 - render: function() {
84 - return (
85 - <div className="commentBox">
86 - Ciao, mondo! Sono un CommentBox.
87 - </div>
88 - );
89 - }
90 -});
91 -ReactDOM.render(
92 - <CommentBox />,
93 - document.getElementById('content')
94 -);
95 -```
96 -
97 -Nota che i nomi degli elementi nativi HTML cominciano con una lettera minuscola, mentre i nomi di classe personalizzati di React cominciano con una lettera maiuscola.
98 -
99 -#### Sintassi JSX
100 -
101 -La prima cosa che noterai è la sintassi simile a XML nel tuo JavaScript. Abbiamo un semplice preprocessore che traduce lo zucchero sintattico a questo semplice JavaScript:
102 -
103 -```javascript
104 -// tutorial1-raw.js
105 -var CommentBox = React.createClass({displayName: 'CommentBox',
106 - render: function() {
107 - return (
108 - React.createElement('div', {className: "commentBox"},
109 - "Ciao, mondo! Sono un CommentBox."
110 - )
111 - );
112 - }
113 -});
114 -ReactDOM.render(
115 - React.createElement(CommentBox, null),
116 - document.getElementById('content')
117 -);
118 -```
119 -
120 -Il suo uso è opzionale ma abbiamo trovato la sintassi JSX più facile da usare del semplice JavaScript. Leggi maggiori dettagli sull'[articolo sulla sintassi JSX](/react/docs/jsx-in-depth.html).
121 -
122 -#### Cosa sta succedendo?
123 -
124 -Passiamo dei metodi in un oggetto JavaScript a `React.createClass()` per creare un nuovo componente React. Il più importante di questi metodi è chiamato `render` il quale restituisce un albero di componenti React che saranno eventualmente visualizzati come HTML.
125 -
126 -I tag `<div>` non sono veri nodi DOM; sono istanze dei componenti React `div`. Puoi pensare a questi come marcatori o a elementi di dati che React sa come gestire. React è **sicuro**. Non stiamo generando stringhe HTML quindi la protezione XSS è predefinita.
127 -
128 -Non devi necessariamente restituire semplice HTML. Puoi anche restituire un albero di componenti costruiti da te (o da qualcun altro). Questo è ciò che rende React **componibile**: una caratteristica chiave dei front-end manutenibili.
129 -
130 -`ReactDOM.render()` istanzia il componente radice, avvia il framework, e inietta il markup in un elemento DOM nativo, fornito come secondo argomento.
131 -
132 -## Comporre componenti
133 -
134 -Costruiamo degli scheletri per `CommentList` e `CommentForm` che saranno, nuovamente, dei semplici `<div>`. Aggiungi questi due componenti al tuo file, mantenendo la dichiarazione esistente di `CommentBox` e la chiamata a `ReactDOM.render`:
135 -
136 -```javascript
137 -// tutorial2.js
138 -var CommentList = React.createClass({
139 - render: function() {
140 - return (
141 - <div className="commentList">
142 - Hello, world! I am a CommentList.
143 - </div>
144 - );
145 - }
146 -});
147 -
148 -var CommentForm = React.createClass({
149 - render: function() {
150 - return (
151 - <div className="commentForm">
152 - Hello, world! I am a CommentForm.
153 - </div>
154 - );
155 - }
156 -});
157 -```
158 -
159 -Successivamente, aggiorna il componente `CommentBox` per utilizzare questi due nuovi componenti:
160 -
161 -```javascript{6-8}
162 -// tutorial3.js
163 -var CommentBox = React.createClass({
164 - render: function() {
165 - return (
166 - <div className="commentBox">
167 - <h1>Commenti</h1>
168 - <CommentList />
169 - <CommentForm />
170 - </div>
171 - );
172 - }
173 -});
174 -```
175 -
176 -Nota come stiamo mescolando tag HTML e i componenti che abbiamo costruito. I componenti HTML sono componenti regolari React, proprio come quelli che definisci, con una differenza. Il compilatore JSX riscriverà automaticamente i tag HTML come espressioni `React.createElement(tagName)` e lascerà tutto il resto inalterato. Questo è per impedire che il namespace globale venga inquinato.
177 -
178 -### Usare le proprietà
179 -
180 -Creiamo il componente `Comment`, che dipenderà dai dati passatigli dal suo genitore. I dati passati da un componente genitore sono disponibili come una 'proprietà' nel componente figlio. Queste 'proprietà' sono accessibili attraverso `this.props`. Usando le proprietà, saremo in grado di leggere i dati passati al componente `Comment` dal componente `CommentList`, e visualizzare del markup:
181 -
182 -```javascript
183 -// tutorial4.js
184 -var Comment = React.createClass({
185 - render: function() {
186 - return (
187 - <div className="comment">
188 - <h2 className="commentAuthor">
189 - {this.props.author}
190 - </h2>
191 - {this.props.children}
192 - </div>
193 - );
194 - }
195 -});
196 -```
197 -
198 -Racchiudendo un'espressione JavaScript dentro parentesi graffe all'interno di JSX (sia come attributo che come figlio), puoi inserire del testo o componenti React all'interno dell'albero. Accediamo per nome ad attributi passati al componente tramite chiavi in `this.props` e ciascun elemento annidato come `this.props.children`.
199 -
200 -### Proprietà dei Componenti
201 -
202 -Adesso che abbiamo definito il componente `Comment`, vogliamo passargli il nome dell'autore e il testo del commento. Questo ci permette di riutilizzare lo stesso codice per ciascun commento individuale. Ora aggiungiamo dei commenti all'interno del nostro `CommentList`:
203 -
204 -```javascript{6-7}
205 -// tutorial5.js
206 -var CommentList = React.createClass({
207 - render: function() {
208 - return (
209 - <div className="commentList">
210 - <Comment author="Pete Hunt">Questo è un commento</Comment>
211 - <Comment author="Jordan Walke">Questo è un *altro* commento</Comment>
212 - </div>
213 - );
214 - }
215 -});
216 -```
217 -
218 -Nota che abbiamo passato dei dati dal componente genitore `CommentList` al componente figlio `Comment`. Ad esempio, abbiamo passato *Pete Hunt* (tramite un attributo) e *Questo è un commento* (tramite un nodo figlio simil-XML) al primo `Comment`. Come detto in precedenza, il componente `Comment` accederà a queste 'proprietà' attraverso `this.props.author` e `this.props.children`.
219 -
220 -### Aggiungiamo il Markdown
221 -
222 -Il Markdown è una maniera semplice di formattare il tuo testo in linea. Ad esempio, racchiudendo il testo con asterischi gli aggiungerà dell'enfasi.
223 -
224 -Per prima cosa, aggiungiamo la libreria di terze parti **marked** alla tua applicazione. Questa è una libreria JavaScript che prende il testo Markdown e lo converte in HTML nativo. Per fare ciò è richiesto un tag script nel tag head (che abbiamo già incluso nel playground React):
225 -
226 -```html{9}
227 -<!-- index.html -->
228 -<head>
229 - <meta charset="utf-8" />
230 - <title>React Tutorial</title>
231 - <script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script>
232 - <script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
233 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
234 - <script src="https://unpkg.com/jquery@3.1.0/dist/jquery.min.js"></script>
235 - <script src="https://unpkg.com/remarkable@1.7.1/dist/remarkable.min.js"></script>
236 -</head>
237 -```
238 -
239 -Successivamente, convertiamo il testo del commento da Markdown e scriviamolo:
240 -
241 -```javascript{4,10}
242 -// tutorial6.js
243 -var Comment = React.createClass({
244 - render: function() {
245 - var md = new Remarkable();
246 - return (
247 - <div className="comment">
248 - <h2 className="commentAuthor">
249 - {this.props.author}
250 - </h2>
251 - {md.render(this.props.children.toString())}
252 - </div>
253 - );
254 - }
255 -});
256 -```
257 -
258 -Tutto ciò che stiamo facendo qui è chiamare la libreria remarkable. Dobbiamo convertire `this.props.children` dal testo racchiuso di React a una stringa che remarkable è in grado di capire, quindi vi chiamiamo esplicitamente `toString()`.
259 -
260 -Ma c'è un problema! I nostri commenti visualizzati appaiono come segue nel browser: "`<p>`Questo è un `<em>`altro`</em>` commento`</p>`". Noi vogliamo che questi tag vengano in realtà visualizzati come HTML.
261 -
262 -Questo è il risultato della protezione di React da parte di un [attacco XSS](https://en.wikipedia.org/wiki/Cross-site_scripting). C'è una maniera di aggirare questo comportamento, ma il framework ti avvisa di non farlo:
263 -
264 -```javascript{3-7,15}
265 -// tutorial7.js
266 -var Comment = React.createClass({
267 - rawMarkup: function() {
268 - var md = new Remarkable();
269 - var rawMarkup = md.render(this.props.children.toString());
270 - return { __html: rawMarkup };
271 - },
272 -
273 - render: function() {
274 - return (
275 - <div className="comment">
276 - <h2 className="commentAuthor">
277 - {this.props.author}
278 - </h2>
279 - <span dangerouslySetInnerHTML={this.rawMarkup()} />
280 - </div>
281 - );
282 - }
283 -});
284 -```
285 -
286 -Questa è una speciale API che rende intenzionalmente difficile inserire HTML nativo, ma per remarkable ci avvantaggeremo di questa possibilità.
287 -
288 -**Ricorda:** usando questa funzionalità stai assumendo che remarkable sia sicuro.
289 -
290 -### Collega il modello dei dati
291 -
292 -Finora abbiamo inserito i commenti direttamente nel codice sorgente. Invece, visualizziamo un pacchetto di dati JSON nella lista dei commenti. In seguito questi verranno restituiti dal server, ma per adesso scriviamoli nel tuo sorgente:
293 -
294 -```javascript
295 -// tutorial8.js
296 -var data = [
297 - {author: "Pete Hunt", text: "Questo è un commento"},
298 - {author: "Jordan Walke", text: "Questo è un *altro* commento"}
299 -];
300 -```
301 -
302 -Dobbiamo inserire questi dati in `CommentList` in maniera modulare. Modifica `CommentBox` e la chiamata a `ReactDOM.render()` per passare questi dati a `CommentList` tramite proprietà:
303 -
304 -```javascript{7,15}
305 -// tutorial9.js
306 -var CommentBox = React.createClass({
307 - render: function() {
308 - return (
309 - <div className="commentBox">
310 - <h1>Commenti</h1>
311 - <CommentList data={this.props.data} />
312 - <CommentForm />
313 - </div>
314 - );
315 - }
316 -});
317 -
318 -ReactDOM.render(
319 - <CommentBox data={data} />,
320 - document.getElementById('content')
321 -);
322 -```
323 -
324 -Adesso che i dati sono disponibili in `CommentList`, visualizziamo i commenti dinamicamente:
325 -
326 -```javascript{4-10,13}
327 -// tutorial10.js
328 -var CommentList = React.createClass({
329 - render: function() {
330 - var commentNodes = this.props.data.map(function (comment) {
331 - return (
332 - <Comment author={comment.author} key={comment.id}>
333 - {comment.text}
334 - </Comment>
335 - );
336 - });
337 - return (
338 - <div className="commentList">
339 - {commentNodes}
340 - </div>
341 - );
342 - }
343 -});
344 -```
345 -
346 -Tutto qui!
347 -
348 -### Richiedere dati dal server
349 -
350 -Sostituiamo i dati scritti nel codice con dati dinamici ottenuti dal server. Rimuoveremo le proprietà dei dati e le sostituiremo con uno URL da richiedere:
351 -
352 -```javascript{3}
353 -// tutorial11.js
354 -ReactDOM.render(
355 - <CommentBox url="/api/comments" />,
356 - document.getElementById('content')
357 -);
358 -```
359 -
360 -Questo componente differisce dal precedente perché dovrà effettuare un nuovo rendering di se stesso. Il componente non avrà dati finché la risposta del server non sia disponibile, e a quel punto il componente potrebbe dover visualizzare dei nuovi commenti.
361 -
362 -Nota: il codice non funzionerà a questo passo.
363 -
364 -### Stato reattivo
365 -
366 -Finora, basandosi sulle sue proprietà, ogni componente si è visualizzato solo una volta. I valori di `props` sono immutabili: sono passati dal genitore e sono "posseduti" dal genitore. Per implementare le interazioni, introduciamo uno **stato** mutevole nel componente. `this.state` è privato al componente e può essere cambiato chiamando `this.setState()`. Quando lo stato si aggiorna, il componente effettua nuovamente il rendering di se stesso.
367 -
368 -I metodi `render()` sono scritti dichiarativamente come funzioni di `this.props` e `this.state`. Il framework garantisce che la UI sia sempre consistente con gli input.
369 -
370 -Quando il server ci fornisce i dati, dovremo cambiare i dati dei commenti in nostro possesso. Aggiungiamo un array di dati dei commenti al componente `CommentBox` come il suo stato:
371 -
372 -```javascript{3-5,10}
373 -// tutorial12.js
374 -var CommentBox = React.createClass({
375 - getInitialState: function() {
376 - return {data: []};
377 - },
378 - render: function() {
379 - return (
380 - <div className="commentBox">
381 - <h1>Commenti</h1>
382 - <CommentList data={this.state.data} />
383 - <CommentForm />
384 - </div>
385 - );
386 - }
387 -});
388 -```
389 -
390 -`getInitialState()` viene eseguito esattamente una volta durante il ciclo di vita del componente e imposta lo stato iniziale del componente stesso.
391 -
392 -#### Aggiornare lo stato
393 -Quando il componente è creato per la prima volta, vogliamo richiedere tramite GET del JSON dal server e aggiornare lo stato per riflettere i dati più recenti. Useremo jQuery per effettuare una richiesta asincrona al server che abbiamo avviato in precedenza per richiedere i dati che ci servono. Somiglieranno a qualcosa di simile:
394 -
395 -```json
396 -[
397 - {"author": "Pete Hunt", "text": "Questo è un commento"},
398 - {"author": "Jordan Walke", "text": "Questo è un *altro* commento"}
399 -]
400 -```
401 -
402 -```javascript{6-18}
403 -// tutorial13.js
404 -var CommentBox = React.createClass({
405 - getInitialState: function() {
406 - return {data: []};
407 - },
408 - componentDidMount: function() {
409 - $.ajax({
410 - url: this.props.url,
411 - dataType: 'json',
412 - cache: false,
413 - success: function(data) {
414 - this.setState({data: data});
415 - }.bind(this),
416 - error: function(xhr, status, err) {
417 - console.error(this.props.url, status, err.toString());
418 - }.bind(this)
419 - });
420 - },
421 - render: function() {
422 - return (
423 - <div className="commentBox">
424 - <h1>Commenti</h1>
425 - <CommentList data={this.state.data} />
426 - <CommentForm />
427 - </div>
428 - );
429 - }
430 -});
431 -```
432 -
433 -Qui, `componentDidMount` è un metodo chiamato automaticamente da React quando un componente viene visualizzato. La chiave agli aggiornamenti dinamici è la chiamata a `this.setState()`. Sostituiamo il vecchio array di commenti con il nuovo ottenuto dal server e la UI si aggiorna automaticamente. Per via di questa reattività, è richiesto soltanto un piccolo cambiamento per aggiungere gli aggiornamenti in tempo reale. Qui useremo un semplice polling, ma potrai facilmente usare WebSockets o altre tecnologie.
434 -
435 -```javascript{3,15,20-21,35}
436 -// tutorial14.js
437 -var CommentBox = React.createClass({
438 - loadCommentsFromServer: function() {
439 - $.ajax({
440 - url: this.props.url,
441 - dataType: 'json',
442 - cache: false,
443 - success: function(data) {
444 - this.setState({data: data});
445 - }.bind(this),
446 - error: function(xhr, status, err) {
447 - console.error(this.props.url, status, err.toString());
448 - }.bind(this)
449 - });
450 - },
451 - getInitialState: function() {
452 - return {data: []};
453 - },
454 - componentDidMount: function() {
455 - this.loadCommentsFromServer();
456 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
457 - },
458 - render: function() {
459 - return (
460 - <div className="commentBox">
461 - <h1>Commenti</h1>
462 - <CommentList data={this.state.data} />
463 - <CommentForm />
464 - </div>
465 - );
466 - }
467 -});
468 -
469 -ReactDOM.render(
470 - <CommentBox url="/api/comments" pollInterval={2000} />,
471 - document.getElementById('content')
472 -);
473 -
474 -```
475 -
476 -Tutto ciò che abbiamo fatto finora è spostare la chiamata AJAX in un metodo a parte e chiamarlo quando il componente viene caricato per la prima volta e successivamente ogni 2 secondi. Prova ad eseguire questa versione nel tuo browser e a cambiare il file `comments.json` (si trova nella stessa directory del tuo server); entro 2 secondi i cambiamenti saranno visibili!
477 -
478 -### Aggiungere nuovi commenti
479 -
480 -È giunto il momento di costruire il modulo. Il nostro componente `CommentForm` deve chiedere all'utente il nome e un testo del commento, e inviare una richiesta al server per salvare il commento.
481 -
482 -```javascript{5-9}
483 -// tutorial15.js
484 -var CommentForm = React.createClass({
485 - render: function() {
486 - return (
487 - <form className="commentForm">
488 - <input type="text" placeholder="Il tuo nome" />
489 - <input type="text" placeholder="Di' qualcosa..." />
490 - <input type="submit" value="Invia" />
491 - </form>
492 - );
493 - }
494 -});
495 -```
496 -
497 -Rendiamo il modulo interattivo. Quando l'utente invia il modulo, dobbiamo ripulirlo, inviare una richiesta al server, e aggiornare la lista dei commenti. Per cominciare, ascoltiamo l'evento `submit` del modulo e ripuliamolo.
498 -
499 -```javascript{3-14,16-19}
500 -// tutorial16.js
501 -var CommentForm = React.createClass({
502 - handleSubmit: function(e) {
503 - e.preventDefault();
504 - var author = ReactDOM.findDOMNode(this.refs.author).value.trim();
505 - var text = ReactDOM.findDOMNode(this.refs.text).value.trim();
506 - if (!text || !author) {
507 - return;
508 - }
509 - // TODO: invia la richiesta al server
510 - ReactDOM.findDOMNode(this.refs.author).value = '';
511 - ReactDOM.findDOMNode(this.refs.text).value = '';
512 - return;
513 - },
514 - render: function() {
515 - return (
516 - <form className="commentForm" onSubmit={this.handleSubmit}>
517 - <input type="text" placeholder="Il tuo nome" ref="author" />
518 - <input type="text" placeholder="Di' qualcosa..." ref="text" />
519 - <input type="submit" value="Invia" />
520 - </form>
521 - );
522 - }
523 -});
524 -```
525 -
526 -##### Eventi
527 -
528 -React assegna i gestori degli eventi ai componenti usando una convenzione di nomi camelCased. Assegnamo un gestore `onSubmit` al modulo in maniera che ripulisca i campi del modulo quando il modulo stesso è inviato con un input valido.
529 -
530 -Chiamiamo `preventDefault()` sull'evento per prevenire l'azione predefinita del browser per l'invio del modulo.
531 -
532 -##### Refs
533 -
534 -Usiamo l'attributo `ref` per assegnare un nome a un componente figlio e `this.refs` per riferirsi al componente. Possiamo chiamare `ReactDOM.findDOMNode(component)` su di un componente per ottenere l'elemento nativo del DOM del browser.
535 -
536 -##### Callback come proprietà
537 -
538 -Quando un utente invia un commento, dobbiamo aggiornare la lista dei commenti per includere il nuovo commento. Ha senso posizionare questa logica in `CommentBox` dal momento che `CommentBox` possiede lo stato che rappresenta la lista dei commenti.
539 -
540 -Dobbiamo passare i dati dal componente figlio su fino al suo genitore. Lo facciamo nel metodo `render` del nostro genitore passando una nuova callback (`handleCommentSubmit`) al figlio, legandola all'evento `onCommentSubmit` del figlio. Quando questo evento viene emesso, la callback verrà eseguita:
541 -
542 -```javascript{16-18,31}
543 -// tutorial17.js
544 -var CommentBox = React.createClass({
545 - loadCommentsFromServer: function() {
546 - $.ajax({
547 - url: this.props.url,
548 - dataType: 'json',
549 - cache: false,
550 - success: function(data) {
551 - this.setState({data: data});
552 - }.bind(this),
553 - error: function(xhr, status, err) {
554 - console.error(this.props.url, status, err.toString());
555 - }.bind(this)
556 - });
557 - },
558 - handleCommentSubmit: function(comment) {
559 - // TODO: invia al server e aggiorna la lista
560 - },
561 - getInitialState: function() {
562 - return {data: []};
563 - },
564 - componentDidMount: function() {
565 - this.loadCommentsFromServer();
566 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
567 - },
568 - render: function() {
569 - return (
570 - <div className="commentBox">
571 - <h1>Commenti</h1>
572 - <CommentList data={this.state.data} />
573 - <CommentForm onCommentSubmit={this.handleCommentSubmit} />
574 - </div>
575 - );
576 - }
577 -});
578 -```
579 -
580 -Chiamiamo la callback da `CommentForm` quando l'utente invia il modulo:
581 -
582 -```javascript{10}
583 -// tutorial18.js
584 -var CommentForm = React.createClass({
585 - handleSubmit: function(e) {
586 - e.preventDefault();
587 - var author = ReactDOM.findDOMNode(this.refs.author).value.trim();
588 - var text = ReactDOM.findDOMNode(this.refs.text).value.trim();
589 - if (!text || !author) {
590 - return;
591 - }
592 - this.props.onCommentSubmit({author: author, text: text});
593 - ReactDOM.findDOMNode(this.refs.author).value = '';
594 - ReactDOM.findDOMNode(this.refs.text).value = '';
595 - return;
596 - },
597 - render: function() {
598 - return (
599 - <form className="commentForm" onSubmit={this.handleSubmit}>
600 - <input type="text" placeholder="Il tuo nome" ref="author" />
601 - <input type="text" placeholder="Di' qualcosa..." ref="text" />
602 - <input type="submit" value="Invia" />
603 - </form>
604 - );
605 - }
606 -});
607 -```
608 -
609 -Adesso che le callback sono al loro posto, non ci resta che inviare al server e aggiornare la lista:
610 -
611 -```javascript{17-28}
612 -// tutorial19.js
613 -var CommentBox = React.createClass({
614 - loadCommentsFromServer: function() {
615 - $.ajax({
616 - url: this.props.url,
617 - dataType: 'json',
618 - cache: false,
619 - success: function(data) {
620 - this.setState({data: data});
621 - }.bind(this),
622 - error: function(xhr, status, err) {
623 - console.error(this.props.url, status, err.toString());
624 - }.bind(this)
625 - });
626 - },
627 - handleCommentSubmit: function(comment) {
628 - $.ajax({
629 - url: this.props.url,
630 - dataType: 'json',
631 - type: 'POST',
632 - data: comment,
633 - success: function(data) {
634 - this.setState({data: data});
635 - }.bind(this),
636 - error: function(xhr, status, err) {
637 - console.error(this.props.url, status, err.toString());
638 - }.bind(this)
639 - });
640 - },
641 - getInitialState: function() {
642 - return {data: []};
643 - },
644 - componentDidMount: function() {
645 - this.loadCommentsFromServer();
646 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
647 - },
648 - render: function() {
649 - return (
650 - <div className="commentBox">
651 - <h1>Commenti</h1>
652 - <CommentList data={this.state.data} />
653 - <CommentForm onCommentSubmit={this.handleCommentSubmit} />
654 - </div>
655 - );
656 - }
657 -});
658 -```
659 -
660 -### Ottimizzazione: aggiornamenti ottimistici
661 -
662 -La nostra applicazione è adesso completa, ma aspettare che la richiesta completi prima di vedere il commento apparire nella lista la fa sembrare lenta. Possiamo aggiungere ottimisticamente questo commento alla lista per fare apparire l'applicazione più veloce.
663 -
664 -```javascript{17-19,29}
665 -// tutorial20.js
666 -var CommentBox = React.createClass({
667 - loadCommentsFromServer: function() {
668 - $.ajax({
669 - url: this.props.url,
670 - dataType: 'json',
671 - cache: false,
672 - success: function(data) {
673 - this.setState({data: data});
674 - }.bind(this),
675 - error: function(xhr, status, err) {
676 - console.error(this.props.url, status, err.toString());
677 - }.bind(this)
678 - });
679 - },
680 - handleCommentSubmit: function(comment) {
681 - var comments = this.state.data;
682 - var newComments = comments.concat([comment]);
683 - this.setState({data: newComments});
684 - $.ajax({
685 - url: this.props.url,
686 - dataType: 'json',
687 - type: 'POST',
688 - data: comment,
689 - success: function(data) {
690 - this.setState({data: data});
691 - }.bind(this),
692 - error: function(xhr, status, err) {
693 - this.setState({data: comments});
694 - console.error(this.props.url, status, err.toString());
695 - }.bind(this)
696 - });
697 - },
698 - getInitialState: function() {
699 - return {data: []};
700 - },
701 - componentDidMount: function() {
702 - this.loadCommentsFromServer();
703 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
704 - },
705 - render: function() {
706 - return (
707 - <div className="commentBox">
708 - <h1>Commenti</h1>
709 - <CommentList data={this.state.data} />
710 - <CommentForm onCommentSubmit={this.handleCommentSubmit} />
711 - </div>
712 - );
713 - }
714 -});
715 -```
716 -
717 -### Congratulazioni!
718 -
719 -Hai appena costruito una casella di commenti in pochi semplici passi. Leggi maggiori dettagli sul [perché usare React](/react/docs/why-react.html), o approfondisci [la guida di riferimento dell'API](/react/docs/top-level-api.html) e comincia ad hackerare! In bocca al lupo!
docs/docs/tutorial.ja-JP.md deleted
-800
@@ -1,800 +0,0 @@
1 ----
2 -id: tutorial-ja-JP
3 -title: チュートリアル
4 -permalink: docs/tutorial-ja-JP.html
5 -prev: getting-started-ja-JP.html
6 -next: thinking-in-react-ja-JP.html
7 ----
8 -
9 -これから、シンプルながらも現実的なコメントボックスを作ってみましょう。ブログにも設置できるようなもので、Disqus や LiveFyre、Facebook comments が採用しているリアルタイムコメントの基本機能を備えたものを想定しています。
10 -
11 -その機能とは次のようなものです。
12 -
13 -* コメント全件の表示欄
14 -* コメントの送信フォーム
15 -* 自作のバックエンドとの連携機能
16 -
17 -ついでに小洒落た機能もいくつか加えましょう。
18 -
19 -* **コメントの先読み:** 送信したコメントをサーバに保存される前に表示させることで、アプリ動作の体感速度をアップさせます。
20 -* **自動更新:** 他のユーザのコメントをリアルタイムで表示させます。
21 -* **Markdown 記法:** ユーザが Markdown 記法でコメントを書けるようにします。
22 -
23 -### 全部飛ばしてソースを見たいんだけど?
24 -
25 -[全部 GitHub にあります。](https://github.com/reactjs/react-tutorial)
26 -
27 -### サーバを動かす
28 -
29 -このチュートリアルを始めるにあたっては必要ないですが、後半ではサーバに POST を投げる機能を追加します。サーバのことは良く知っていて自分でサーバを建てたいのであれば、それでも構いません。そうではないけれども、サーバサイドは考えずに React のことだけに焦点を絞って学びたい方のため、シンプルなサーバのソースコードを書いておきました。言語は JavaScript (Node.js)または Python、Ruby、Go、ないし PHP で用意してあり、すべて GitHub にあります。[ソースを見る](https://github.com/reactjs/react-tutorial/) ことも出来ますし、 [zip ファイルでダウンロード](https://github.com/reactjs/react-tutorial/archive/master.zip)することも出来ます。
30 -
31 -それでは最初のチュートリアルとして、`public/index.html` の編集から始めましょう。
32 -
33 -### 始めてみましょう
34 -
35 -このチュートリアルでは、あらかじめビルドされた JavaScript ファイルを CDN から読み込むことになります。自分の好きなエディタを立ち上げて、次のように新規の HTML ドキュメントを作りましょう。
36 -
37 -```html
38 -<!-- index.html -->
39 -<!DOCTYPE html>
40 -<html>
41 - <head>
42 - <meta charset="UTF-8" />
43 - <title>React Tutorial</title>
44 - <script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script>
45 - <script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
46 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
47 - <script src="https://unpkg.com/jquery@3.1.0/dist/jquery.min.js"></script>
48 - <script src="https://unpkg.com/remarkable@1.7.1/dist/remarkable.min.js"></script>
49 -
50 - </head>
51 - <body>
52 - <div id="content"></div>
53 - <script type="text/babel">
54 - // ここにコードが入ります
55 - </script>
56 - </body>
57 -</html>
58 -```
59 -
60 -このチュートリアルに関しては、JavaScript コードを script タグの中へ書いていくことにします。
61 -
62 -> 確認:
63 ->
64 -> 上のコードで jQuery を読み込んでいますが、これはチュートリアル後半で ajax のコードを簡潔に書きたいだけなので、React を動かすのに必要なものでは**ありません**。
65 -
66 -### 最初のコンポーネント
67 -
68 -React はすべて、モジュール単位で組み立てられる(composable)コンポーネントからなっています。今回取り上げるコメントボックスの例では、以下のようなコンポーネント構造をとります。
69 -
70 -```
71 -- CommentBox
72 - - CommentList
73 - - Comment
74 - - CommentForm
75 -```
76 -
77 -それではまず `CommentBox` コンポーネントから作っていきましょう。とは言っても単なる `<div>` です。
78 -
79 -```javascript
80 -// tutorial1.js
81 -var CommentBox = React.createClass({
82 - render: function() {
83 - return (
84 - <div className="commentBox">
85 - Hello, world! I am a CommentBox.
86 - </div>
87 - );
88 - }
89 -});
90 -ReactDOM.render(
91 - <CommentBox />,
92 - document.getElementById('content')
93 -);
94 -```
95 -
96 -#### JSX シンタックス
97 -
98 -先程書いた JavaScript の中に、XMLに似たシンタックスがあることに気付いたでしょうか。このシンタックスシュガーは、シンプルなプリコンパイラによって次のような生の JavaScript に変換されます。
99 -
100 -```javascript
101 -// tutorial1-raw.js
102 -var CommentBox = React.createClass({displayName: 'CommentBox',
103 - render: function() {
104 - return (
105 - React.createElement('div', {className: "commentBox"},
106 - "Hello, world! I am a CommentBox."
107 - )
108 - );
109 - }
110 -});
111 -ReactDOM.render(
112 - React.createElement(CommentBox, null),
113 - document.getElementById('content')
114 -);
115 -```
116 -
117 -どちらを採るかは自由ですが、生の JavaScript よりも JSX シンタックスのほうが扱いやすいと考えています。詳しくは [JSX シンタックスの記事](/react/docs/jsx-in-depth.html) を読んでみてください。
118 -
119 -#### 何をしているのか
120 -
121 -先程のコードでは、とあるメソッドを持った JavaScript オブジェクトを `React.createClass()` に渡しています。これは新しい React コンポーネントを作るためです。このメソッドは `render` と呼ばれており、最終的に HTML へレンダリングされる React コンポーネントのツリーを返す点が肝になります。
122 -
123 -コードに書いた `<div>` タグは実際の DOM ノードではありません。これは React の `div` コンポーネントのインスタンスです。 これらは React が理解できるマーカーやデータの一部だと見なせます。React は **安全** です。デフォルトで XSS 対策を行っているので、HTML 文字列を生成することはありません。
124 -
125 -実際の HTML を返す必要はありません。 自分が(もしくは他の誰かが)組み立てたコンポーネントツリーを返せばいいのです。 これこそ React が **composable**な(組み立てられる)ものである理由であり、この大事なルールを守ればフロントエンドはメンテナンスしやすいものとなります。
126 -
127 -`ReactDOM.render()` はまずルートコンポーネントのインスタンスを作り、フレームワークを立ち上げます。そして、第2引数で与えられた実際の DOM 要素にマークアップを挿入します。
128 -
129 -## コンポーネントの組み立て
130 -
131 -それでは `CommentList` と `CommentForm` の骨組みを作りましょう。繰り返しになりますが、これらはただの `<div>` です。
132 -
133 -```javascript
134 -// tutorial2.js
135 -var CommentList = React.createClass({
136 - render: function() {
137 - return (
138 - <div className="commentList">
139 - Hello, world! I am a CommentList.
140 - </div>
141 - );
142 - }
143 -});
144 -
145 -var CommentForm = React.createClass({
146 - render: function() {
147 - return (
148 - <div className="commentForm">
149 - Hello, world! I am a CommentForm.
150 - </div>
151 - );
152 - }
153 -});
154 -```
155 -
156 -さて、この新しいコンポーネントを使えるように `CommentBox` コンポーネントを書き直しましょう。
157 -
158 -```javascript{6-8}
159 -// tutorial3.js
160 -var CommentBox = React.createClass({
161 - render: function() {
162 - return (
163 - <div className="commentBox">
164 - <h1>Comments</h1>
165 - <CommentList />
166 - <CommentForm />
167 - </div>
168 - );
169 - }
170 -});
171 -```
172 -
173 -ここで、HTML タグと組み立てているコンポーネントが、どのようにミックスされているかを確認しましょう。 HTML コンポーネントは既定の React コンポーネントですが、自分で定義したもの同士はそれぞれ別物になります。JSX コンパイラは HTML タグを自動的に `React.createElement(tagName)` の式に書き換え、それぞれを別々のものに変換します。これはグローバルの名前空間が汚染させるのを防ぐためです。
174 -
175 -### Props を使う
176 -
177 -次のステップは `Comment` コンポーネントの作成です。このコンポーネントは、自分の親にあたるコンポーネントから渡されたデータを扱います。親から渡されたデータは、子のコンポーネントで「プロパティ」として利用できます。この「プロパティ」には `this.props` を通してアクセスします。props(プロパティ)を使うと `CommentList` から `Comment` に渡されたデータの読み込み、マークアップのレンダリングが可能になります。
178 -
179 -```javascript
180 -// tutorial4.js
181 -var Comment = React.createClass({
182 - render: function() {
183 - return (
184 - <div className="comment">
185 - <h2 className="commentAuthor">
186 - {this.props.author}
187 - </h2>
188 - {this.props.children}
189 - </div>
190 - );
191 - }
192 -});
193 -```
194 -
195 -JSX の内側で(属性値または子要素として)JavaScript の式を波括弧で囲むと、テキストや React コンポーネントをツリーに加えることが出来ます。コンポーネントに渡された属性値には名前が付けられており、`this.props` をキーとしてアクセスできます。また、ネストされた子要素の値は `this.props.children` でアクセスが可能です。
196 -
197 -### コンポーネントのプロパティ
198 -
199 -さて、これまでに `Comment` コンポーネントを定義しました。これからこのコンポーネントに、コメントの著者名と内容を渡せるようにします。これを実装することで、それぞれ別のコメントに対して同じコードを使い回せるようになります。それでは早速 `CommentList` の中にコメントを追加していきましょう。
200 -
201 -```javascript{6-7}
202 -// tutorial5.js
203 -var CommentList = React.createClass({
204 - render: function() {
205 - return (
206 - <div className="commentList">
207 - <Comment author="Pete Hunt">This is one comment</Comment>
208 - <Comment author="Jordan Walke">This is *another* comment</Comment>
209 - </div>
210 - );
211 - }
212 -});
213 -```
214 -
215 -ここで確認してもらいたいのは、親の `CommentList` コンポーネントから、子の `Comment` コンポーネントにデータが渡されている点です。この例ではまず、*Pete Hunt*(属性値を通して)と *This is one comment*(XML のような子ノードを通して)といったデータを `Comment` コンポーネントに渡しています。少し前に確認した通り、`Comment` コンポーネントからこれらの「プロパティ」にアクセスするには、`this.props.author` と `this.props.children` を使います。
216 -
217 -### Markdown の追加
218 -
219 -Markdown はインラインでテキストをフォーマットする簡単な記法です。例えば、テキストをアスタリスクで挟むと強調されて表示されます。
220 -
221 -まず最初に、サードパーティ製の **remarkable** ライブラリをアプリケーションに追加します。 remarkable は Markdown テキストを生の HTML に変換する JavaScript ライブラリです。 既にある head タグの内側に script タグを書き込み、以下のように remarkable を読み込ませます。
222 -
223 -```html{9}
224 -<!-- index.html -->
225 -<head>
226 - <meta charset="UTF-8" />
227 - <title>Hello React</title>
228 - <script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script>
229 - <script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
230 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
231 - <script src="https://unpkg.com/jquery@3.1.0/dist/jquery.min.js"></script>
232 - <script src="https://unpkg.com/remarkable@1.7.1/dist/remarkable.min.js"></script>
233 -</head>
234 -```
235 -
236 -次に、Markdown で書かれたコメントを変換して出力してみましょう。
237 -
238 -```javascript{4,10}
239 -// tutorial6.js
240 -var Comment = React.createClass({
241 - render: function() {
242 - var md = new Remarkable();
243 - return (
244 - <div className="comment">
245 - <h2 className="commentAuthor">
246 - {this.props.author}
247 - </h2>
248 - {md.render(this.props.children.toString())}
249 - </div>
250 - );
251 - }
252 -});
253 -```
254 -
255 -このコードでは remarkable のライブラリを呼び出すことしかしていません。`this.props.children` は React によってラップされたテキストですが、これを remarkable が理解できる生の文字列に変換する必要があります。そのため、上のコードでは明示的に `toString()` を呼び出しているのです。
256 -
257 -しかし問題があります!ブラウザがレンダリングしたコメントは次のように表示されているはずです -- "`<p>`This is `<em>`another`</em>` comment`</p>`" このようなタグは実際に HTML としてレンダリングさせたいですね。
258 -
259 -このような現象が起きるのは React が XSS 攻撃に対する防御を行っているからです。これを回避する方法はありますが、それを使うときにはフレームワークが警告をします。
260 -
261 -```javascript{3-7,15}
262 -// tutorial7.js
263 -var Comment = React.createClass({
264 - rawMarkup: function() {
265 - var md = new Remarkable();
266 - var rawMarkup = md.render(this.props.children.toString());
267 - return { __html: rawMarkup };
268 - },
269 -
270 - render: function() {
271 - return (
272 - <div className="comment">
273 - <h2 className="commentAuthor">
274 - {this.props.author}
275 - </h2>
276 - <span dangerouslySetInnerHTML={this.rawMarkup()} />
277 - </div>
278 - );
279 - }
280 -});
281 -```
282 -
283 -これは特別な API であり、生の HTML が挿入されにくくなるよう意図的に作ったものです。しかし、ここでは remarkable のためにこのバックドアを利用しています。
284 -
285 -**注意:** この機能を使うことで、remarkable は安全なものと信頼することになります。
286 -
287 -### データモデルとの連携
288 -
289 -これまではソースコードにコメントを直に書き込んでいました。その代わりに、これからは JSON の blob データをコメントリストにレンダリングしてみましょう。サーバからデータを取得するのが最後の目標ですが、とりあえず今はソースコードの中にデータを書いておくことにします。
290 -
291 -```javascript
292 -// tutorial8.js
293 -var data = [
294 - {id: 1, author: "Pete Hunt", text: "This is one comment"},
295 - {id: 2, author: "Jordan Walke", text: "This is *another* comment"}
296 -];
297 -```
298 -
299 -このデータはモジュールを使って `CommentList` に取り込む必要があります。`CommentBox` の `ReactDOM.render()` の部分を手直しして、props を通してデータが `CommentList` へ渡るようにしましょう。
300 -
301 -```javascript{7,15}
302 -// tutorial9.js
303 -var CommentBox = React.createClass({
304 - render: function() {
305 - return (
306 - <div className="commentBox">
307 - <h1>Comments</h1>
308 - <CommentList data={this.props.data} />
309 - <CommentForm />
310 - </div>
311 - );
312 - }
313 -});
314 -
315 -ReactDOM.render(
316 - <CommentBox data={data} />,
317 - document.getElementById('content')
318 -);
319 -```
320 -
321 -こうして `CommentList` がデータを扱えるようになりました。それでは、コメントを動的にレンダリングしてみましょう。
322 -
323 -```javascript{4-10,13}
324 -// tutorial10.js
325 -var CommentList = React.createClass({
326 - render: function() {
327 - var commentNodes = this.props.data.map(function (comment) {
328 - return (
329 - <Comment author={comment.author} key={comment.id}>
330 - {comment.text}
331 - </Comment>
332 - );
333 - });
334 - return (
335 - <div className="commentList">
336 - {commentNodes}
337 - </div>
338 - );
339 - }
340 -});
341 -```
342 -
343 -これだけ!
344 -
345 -### サーバからのデータの取得
346 -
347 -続いて、ハードコーディングしていたデータを、サーバからの動的なデータに置き換えてみましょう。
348 -
349 -```javascript{3}
350 -// tutorial11.js
351 -ReactDOM.render(
352 - <CommentBox url="/api/comments" />,
353 - document.getElementById('content')
354 -);
355 -```
356 -
357 -このコンポーネントは自身を再びレンダリングすることになるので、これまでのコンポーネントとは異なります。レスポンスがサーバから返ってくると、送られてきた新しいコメントをコンポーネントがレンダリングすることになります。ですが、その時点までコンポーネントには何もデータがないはずです。
358 -
359 -確認: 上のコードは、このステップではまだ動きません。
360 -
361 -### Reactive state
362 -
363 -これまで、それぞれのコンポーネントは自身の props の値を用いて、一度だけレンダリングしていました。`props` はイミュータブルです。つまり、props は親から渡されますが、同時に props は親の「所有物」なのです。データが相互にやり取りされるのを実現するため、ここでミュータブルな **state**(状態)をコンポーネントに取り入れましょう。コンポーネントは `this.state` というプライベートな値を持ち、`this.setState()` を呼び出すことで state を更新することが出来ます。コンポーネントの state が更新されれば、そのコンポーネントは自身を再びレンダリングし直します。
364 -
365 -`render()` メソッドは `this.props` や `this.state` と同じく宣言的に書かれています。このフレームワークによって、UI と入力が常に一致するようになります。
366 -
367 -サーバがデータを集めてくれば、今あるコメントのデータを更新することになるかもしれません。state を表すコメントのデータの配列を `CommentBox` コンポーネントに加えましょう。
368 -
369 -```javascript{3-5,10}
370 -// tutorial12.js
371 -var CommentBox = React.createClass({
372 - getInitialState: function() {
373 - return {data: []};
374 - },
375 - render: function() {
376 - return (
377 - <div className="commentBox">
378 - <h1>Comments</h1>
379 - <CommentList data={this.state.data} />
380 - <CommentForm />
381 - </div>
382 - );
383 - }
384 -});
385 -```
386 -
387 -`getInitialState()` メソッドはコンポーネントのライフサイクル内で一回だけ実行され、コンポーネントの state における初期値を設定します。
388 -
389 -#### State の更新
390 -コンポーネントの作成と同時に、サーバから JSON データを GET で取得し、state を更新して最新のデータを反映させてみましょう。実際のアプリケーションでは動的なエンドポイントになるでしょうが、今回の例では話を簡単にするため、以下の静的な JSON ファイルを使います。
391 -
392 -```json
393 -[
394 - {"id": "1", "author": "Pete Hunt", "text": "This is one comment"},
395 - {"id": "2", "author": "Jordan Walke", "text": "This is *another* comment"}
396 -]
397 -```
398 -
399 -サーバへの非同期リクエストを作るため、ここでは jQuery を使います。
400 -
401 -注意: ここからは AJAX アプリケーションを作っていくので、自分のファイルシステム上ではなく Web サーバを使ってアプリを作る必要があります。残りのチュートリアルに必要な機能は [冒頭で紹介した](#running-a-server) サーバに含まれています。ソースコードは [GitHub に](https://github.com/reactjs/react-tutorial/)用意してあります。
402 -
403 -```javascript{6-18}
404 -// tutorial13.js
405 -var CommentBox = React.createClass({
406 - getInitialState: function() {
407 - return {data: []};
408 - },
409 - componentDidMount: function() {
410 - $.ajax({
411 - url: this.props.url,
412 - dataType: 'json',
413 - cache: false,
414 - success: function(data) {
415 - this.setState({data: data});
416 - }.bind(this),
417 - error: function(xhr, status, err) {
418 - console.error(this.props.url, status, err.toString());
419 - }.bind(this)
420 - });
421 - },
422 - render: function() {
423 - return (
424 - <div className="commentBox">
425 - <h1>Comments</h1>
426 - <CommentList data={this.state.data} />
427 - <CommentForm />
428 - </div>
429 - );
430 - }
431 -});
432 -```
433 -
434 -さて、`componentDidMount` はコンポーネントがレンダリングされたときに React が自動的に呼び出すメソッドです。動的な更新の鍵となるのは `this.setState()` の呼び出し方です。ここでは、古いコメントの配列をサーバから取ってきた新しい配列に置き換え、UI を自動的に更新させてみましょう。このような reactivity(反応性・柔軟性)のおかげで、リアルタイム更新を最小限にすることが出来ます。次のコードではシンプルなポーリングをしていますが、WebSockets や他の方法でも簡単に実現できます。
435 -
436 -```javascript{3,15,20-21,35}
437 -// tutorial14.js
438 -var CommentBox = React.createClass({
439 - loadCommentsFromServer: function() {
440 - $.ajax({
441 - url: this.props.url,
442 - dataType: 'json',
443 - cache: false,
444 - success: function(data) {
445 - this.setState({data: data});
446 - }.bind(this),
447 - error: function(xhr, status, err) {
448 - console.error(this.props.url, status, err.toString());
449 - }.bind(this)
450 - });
451 - },
452 - getInitialState: function() {
453 - return {data: []};
454 - },
455 - componentDidMount: function() {
456 - this.loadCommentsFromServer();
457 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
458 - },
459 - render: function() {
460 - return (
461 - <div className="commentBox">
462 - <h1>Comments</h1>
463 - <CommentList data={this.state.data} />
464 - <CommentForm />
465 - </div>
466 - );
467 - }
468 -});
469 -
470 -ReactDOM.render(
471 - <CommentBox url="/api/comments" pollInterval={2000} />,
472 - document.getElementById('content')
473 -);
474 -
475 -```
476 -
477 -ここまでに、AJAX を呼び出す部分を別のメソッド内に移動させました。加えて、コンポーネントが最初に読み込まれてから2秒ごとに AJAX のメソッドが呼び出されるようにしました。ぜひ自分のブラウザで実行させて、`comments.json` ファイルに変更を加えてみてください。2秒以内に表示が更新されるはずです!
478 -
479 -### 新しいコメントの追加
480 -
481 -いよいよフォームを作る段階に来ました。ここで `CommentForm` コンポーネントは、ユーザに自分の名前とコメントの内容を入力させ、コメントを保存するためにサーバにリクエストを送信する必要があります。
482 -
483 -```javascript{5-9}
484 -// tutorial15.js
485 -var CommentForm = React.createClass({
486 - render: function() {
487 - return (
488 - <form className="commentForm">
489 - <input type="text" placeholder="Your name" />
490 - <input type="text" placeholder="Say something..." />
491 - <input type="submit" value="Post" />
492 - </form>
493 - );
494 - }
495 -});
496 -```
497 -
498 -#### 制御コンポーネント
499 -
500 -このチュートリアルの DOM は、`input` 要素がレンダリングされ、ブラウザが状態(そのレンダリングされた値)を管理します。その結果、実際のDOMの状態がコンポーネントとは異なります。ビューの状態がコンポーネントとは異なり、これは理想的ではありません。React では、コンポーネントは初期化の時点だけでなく、常にビューの状態を表している必要があります。
501 -
502 -したがって、ユーザの入力を保存するために `this.state` を使用することになります。2つのプロパティの`author`と`text`に最初の`state`を定義して、空の文字列を設定します。`<input>`の要素では、`onChange`にハンドラをアタッチすると`value` に `state` が反映される。これらの `<input>` の要素は、`value` が設定された制御コンポーネントと呼ばれています。制御コンポーネントの詳細についてはこちらの[Forms article](/react/docs/forms.html#controlled-components)をご覧ください。
503 -
504 -```javascript{3-11,15-26}
505 -// tutorial16.js
506 -var CommentForm = React.createClass({
507 - getInitialState: function() {
508 - return {author: '', text: ''};
509 - },
510 - handleAuthorChange: function(e) {
511 - this.setState({author: e.target.value});
512 - },
513 - handleTextChange: function(e) {
514 - this.setState({text: e.target.value});
515 - },
516 - render: function() {
517 - return (
518 - <form className="commentForm">
519 - <input
520 - type="text"
521 - placeholder="Your name"
522 - value={this.state.author}
523 - onChange={this.handleAuthorChange}
524 - />
525 - <input
526 - type="text"
527 - placeholder="Say something..."
528 - value={this.state.text}
529 - onChange={this.handleTextChange}
530 - />
531 - <input type="submit" value="Post" />
532 - </form>
533 - );
534 - }
535 -});
536 -```
537 -
538 -#### イベント
539 -
540 -React イベントハンドラのアタッチはコンポーネントにキャメルケースの命名規則を使用します。2つの`<input>`要素に`onChange`のハンドラをアタッチします。今、ユーザーの入力は`<input>`フィールド、アタッチされた`onChange`がコールバックされてコンポーネントの` state`が変更されます。その後、`input`要素のレンダリングされた値は、現在のコンポーネント` state`を反映するように更新されます。
541 -
542 -(賢明な読者は、説明したようにこれらのイベントハンドラが動作することを驚かれるかもしれない、明示的な結合を不要にそのコンポーネントインスタンスへの各メソッドは、メソッドの参照が明示的に`this`. `React.createClass(...)` [automatically binds](/react/docs/interactivity-and-dynamic-uis.html#under-the-hood-autobinding-and-event-delegation)にバインドされていないことを自動的に結合する与えられました。)
543 -
544 -#### フォーム送信
545 -
546 -フォームを対話型にしましょう。ユーザーがフォームを送信すると、それをクリアする必要があります。サーバに要求を送信すると、コメントのリストを更新します。開始するとフォームの送信イベントでクリアするか試しましょう。
547 -
548 -```javascript{12-21,24}
549 -// tutorial17.js
550 -var CommentForm = React.createClass({
551 - getInitialState: function() {
552 - return {author: '', text: ''};
553 - },
554 - handleAuthorChange: function(e) {
555 - this.setState({author: e.target.value});
556 - },
557 - handleTextChange: function(e) {
558 - this.setState({text: e.target.value});
559 - },
560 - handleSubmit: function(e) {
561 - e.preventDefault();
562 - var author = this.state.author.trim();
563 - var text = this.state.text.trim();
564 - if (!text || !author) {
565 - return;
566 - }
567 - // TODO: サーバーに要求を送信
568 - this.setState({author: '', text: ''});
569 - },
570 - render: function() {
571 - return (
572 - <form className="commentForm" onSubmit={this.handleSubmit}>
573 - <input
574 - type="text"
575 - placeholder="Your name"
576 - value={this.state.author}
577 - onChange={this.handleAuthorChange}
578 - />
579 - <input
580 - type="text"
581 - placeholder="Say something..."
582 - value={this.state.text}
583 - onChange={this.handleTextChange}
584 - />
585 - <input type="submit" value="Post" />
586 - </form>
587 - );
588 - }
589 -});
590 -```
591 -
592 -フォームが有効な入力でサブミットされたときにフォームフィールドをクリアし、フォームに`onSubmit`ハンドラをアタッチします。
593 -
594 -`preventDefault()` はフォームを送信するイベントにブラウザのデフォルトのアクションを防ぐためにコールします。
595 -
596 -#### Props としてのコールバック
597 -
598 -ユーザがコメントを送信したら、コメントリストをリフレッシュして新しいリストを読み込むことになります。コメントリストを表す state を保持しているのは `CommentBox` なので、必要なロジックは `CommentBox` の中に書くのが筋でしょう。
599 -
600 -ここでは子のコンポーネントから親に向かって、いつもとは逆方向にデータを返す必要があります。まず、親のコンポーネントに新しいコールバック関数(`handleCommentSubmit`)を定義します。続いて `render` メソッド内にある子のコンポーネントにコールバックを渡すことで、`onCommentSubmit` イベントとコールバックを結び付けています。こうすることで、イベントが発生するたびにコールバックが呼び出されます。
601 -
602 -```javascript{16-18,31}
603 -// tutorial18.js
604 -var CommentBox = React.createClass({
605 - loadCommentsFromServer: function() {
606 - $.ajax({
607 - url: this.props.url,
608 - dataType: 'json',
609 - cache: false,
610 - success: function(data) {
611 - this.setState({data: data});
612 - }.bind(this),
613 - error: function(xhr, status, err) {
614 - console.error(this.props.url, status, err.toString());
615 - }.bind(this)
616 - });
617 - },
618 - handleCommentSubmit: function(comment) {
619 - // TODO: submit to the server and refresh the list
620 - },
621 - getInitialState: function() {
622 - return {data: []};
623 - },
624 - componentDidMount: function() {
625 - this.loadCommentsFromServer();
626 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
627 - },
628 - render: function() {
629 - return (
630 - <div className="commentBox">
631 - <h1>Comments</h1>
632 - <CommentList data={this.state.data} />
633 - <CommentForm onCommentSubmit={this.handleCommentSubmit} />
634 - </div>
635 - );
636 - }
637 -});
638 -```
639 -
640 -今、`CommentBox`は`onCommentSubmit`をpropして`CommentForm`にコールバックを利用した、ユーザーがフォームを送信したときに`CommentForm`はコールバックを呼び出すことができます。
641 -
642 -```javascript{19}
643 -// tutorial19.js
644 -var CommentForm = React.createClass({
645 - getInitialState: function() {
646 - return {author: '', text: ''};
647 - },
648 - handleAuthorChange: function(e) {
649 - this.setState({author: e.target.value});
650 - },
651 - handleTextChange: function(e) {
652 - this.setState({text: e.target.value});
653 - },
654 - handleSubmit: function(e) {
655 - e.preventDefault();
656 - var author = this.state.author.trim();
657 - var text = this.state.text.trim();
658 - if (!text || !author) {
659 - return;
660 - }
661 - this.props.onCommentSubmit({author: author, text: text});
662 - this.setState({author: '', text: ''});
663 - },
664 - render: function() {
665 - return (
666 - <form className="commentForm" onSubmit={this.handleSubmit}>
667 - <input
668 - type="text"
669 - placeholder="Your name"
670 - value={this.state.author}
671 - onChange={this.handleAuthorChange}
672 - />
673 - <input
674 - type="text"
675 - placeholder="Say something..."
676 - value={this.state.text}
677 - onChange={this.handleTextChange}
678 - />
679 - <input type="submit" value="Post" />
680 - </form>
681 - );
682 - }
683 -});
684 -```
685 -
686 -こうしてコールバックが出来たので、あとはサーバにコメントを送信してリストをリフレッシュすれば完璧です。
687 -
688 -```javascript{17-28}
689 -// tutorial20.js
690 -var CommentBox = React.createClass({
691 - loadCommentsFromServer: function() {
692 - $.ajax({
693 - url: this.props.url,
694 - dataType: 'json',
695 - cache: false,
696 - success: function(data) {
697 - this.setState({data: data});
698 - }.bind(this),
699 - error: function(xhr, status, err) {
700 - console.error(this.props.url, status, err.toString());
701 - }.bind(this)
702 - });
703 - },
704 - handleCommentSubmit: function(comment) {
705 - $.ajax({
706 - url: this.props.url,
707 - dataType: 'json',
708 - type: 'POST',
709 - data: comment,
710 - success: function(data) {
711 - this.setState({data: data});
712 - }.bind(this),
713 - error: function(xhr, status, err) {
714 - console.error(this.props.url, status, err.toString());
715 - }.bind(this)
716 - });
717 - },
718 - getInitialState: function() {
719 - return {data: []};
720 - },
721 - componentDidMount: function() {
722 - this.loadCommentsFromServer();
723 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
724 - },
725 - render: function() {
726 - return (
727 - <div className="commentBox">
728 - <h1>Comments</h1>
729 - <CommentList data={this.state.data} />
730 - <CommentForm onCommentSubmit={this.handleCommentSubmit} />
731 - </div>
732 - );
733 - }
734 -});
735 -```
736 -
737 -### 最適化: 先読み更新
738 -
739 -アプリケーションに必要な機能は一通り実装できました。しかし、フォームからコメントを送信しても、サーバからのレスポンスが来るまで自分のコメントはリストに載らないため、アプリの動作は遅く感じます。ここでは、送信したコメントをリストに先読みさせて、アプリの体感速度をアップさせましょう。
740 -
741 -```javascript{17-23,33}
742 -// tutorial21.js
743 -var CommentBox = React.createClass({
744 - loadCommentsFromServer: function() {
745 - $.ajax({
746 - url: this.props.url,
747 - dataType: 'json',
748 - cache: false,
749 - success: function(data) {
750 - this.setState({data: data});
751 - }.bind(this),
752 - error: function(xhr, status, err) {
753 - console.error(this.props.url, status, err.toString());
754 - }.bind(this)
755 - });
756 - },
757 - handleCommentSubmit: function(comment) {
758 - var comments = this.state.data;
759 - // Optimistically set an id on the new comment. It will be replaced by an
760 - // id generated by the server. In a production application you would likely
761 - // not use Date.now() for this and would have a more robust system in place.
762 - comment.id = Date.now();
763 - var newComments = comments.concat([comment]);
764 - this.setState({data: newComments});
765 - $.ajax({
766 - url: this.props.url,
767 - dataType: 'json',
768 - type: 'POST',
769 - data: comment,
770 - success: function(data) {
771 - this.setState({data: data});
772 - }.bind(this),
773 - error: function(xhr, status, err) {
774 - this.setState({data: comments});
775 - console.error(this.props.url, status, err.toString());
776 - }.bind(this)
777 - });
778 - },
779 - getInitialState: function() {
780 - return {data: []};
781 - },
782 - componentDidMount: function() {
783 - this.loadCommentsFromServer();
784 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
785 - },
786 - render: function() {
787 - return (
788 - <div className="commentBox">
789 - <h1>Comments</h1>
790 - <CommentList data={this.state.data} />
791 - <CommentForm onCommentSubmit={this.handleCommentSubmit} />
792 - </div>
793 - );
794 - }
795 -});
796 -```
797 -
798 -### おめでとう!
799 -
800 -シンプルな手順を追ううちにコメントボックスを作ることが出来ました。さらに詳しいことは[なぜ React を使うのか](/react/docs/why-react.html)を読んだり、[API リファレンス](/react/docs/top-level-api.html)を開いたりしてハッキングを始めましょう!幸運を祈ります!
docs/docs/tutorial.ko-KR.md deleted
-723
@@ -1,723 +0,0 @@
1 ----
2 -id: tutorial-ko-KR
3 -title: 튜토리얼
4 -permalink: docs/tutorial-ko-KR.html
5 -prev: getting-started-ko-KR.html
6 -next: thinking-in-react-ko-KR.html
7 ----
8 -
9 -블로그에 붙일만한 간단하지만 실용적인 댓글상자를 만들어 볼 것입니다. Disqus, LiveFyre, Facebook에서 제공하는 것 같은 실시간 댓글의 간단한 버전이죠.
10 -
11 -이런 기능을 넣겠습니다:
12 -
13 -* 댓글목록
14 -* 댓글작성폼
15 -* 커스텀 백엔드를 위한 Hooks
16 -
17 -멋진 기능도 조금 넣어보겠습니다:
18 -
19 -* **낙관적 댓글 달기:** 댓글은 서버에 저장되기도 전에 목록에 나타납니다. 그래서 빠르게 느껴집니다.
20 -* **실시간 업데이트:** 다른 사용자가 남기는 댓글이 실시간으로 나타납니다.
21 -* **Markdown 지원:** 사용자는 글을 꾸미기 위해 Markdown 형식을 사용할 수 있습니다.
22 -
23 -### 그냥 다 생략하고 소스만 보고 싶나요?
24 -
25 -[GitHub에 전부 있습니다.](https://github.com/reactjs/react-tutorial)
26 -
27 -### 서버 구동하기
28 -
29 -이 튜토리얼을 시작하기 위해, 서버를 구동할 필요가 있습니다. 이 서버는 순수하게 우리가 받고 저장할 데이터의 API 엔드포인트로써만 사용합니다. 이를 가능한한 쉽게하기 위해, 필요한 것만 제공하는 간단한 서버를 몇가지 스크립트 언어로 만들었습니다. **시작하는데 필요한 모든 것이 들어있는 [소스](https://github.com/reactjs/react-tutorial/)를 보시거나 [zip 파일](https://github.com/reactjs/react-tutorial/archive/master.zip)을 다운로드 할 수 있습니다.**
30 -
31 -단순하게 하기위해, 서버는 `JSON` 파일을 데이터베이스로 사용합니다. 프로덕션에서 사용할 수는 없지만 이렇게 하면 API를 사용할 때 시뮬레이션이 단순해집니다. 서버가 시작되면, API 엔드포인트를 제공하고 필요한 정적 페이지를 서빙합니다.
32 -
33 -### 시작하기
34 -
35 -이 튜토리얼에서는 가능한한 간단하게 만들겠습니다. 위에서 언급된 서버 패키지에 우리가 작업할 HTML 파일 포함되어 있습니다. 편한 편집기에서 `public/index.html`를 여세요. 이는 이런 내용이어야 합니다.(아마 조금 다를 수 있습니다만, 여기에 나중에 `<script>` 태그를 추가 할 것입니다.)
36 -
37 -```html
38 -<!-- index.html -->
39 -<!DOCTYPE html>
40 -<html>
41 - <head>
42 - <meta charset="utf-8" />
43 - <title>React Tutorial</title>
44 - <script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script>
45 - <script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
46 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
47 - <script src="https://unpkg.com/jquery@3.1.0/dist/jquery.min.js"></script>
48 - <script src="https://unpkg.com/remarkable@1.7.1/dist/remarkable.min.js"></script>
49 - </head>
50 - <body>
51 - <div id="content"></div>
52 - <script type="text/babel" src="scripts/example.js"></script>
53 - <script type="text/babel">
54 - // 이 튜토리얼을 시작하려면, 그냥 scripts/example.js를 로드하는 스크립트
55 - // 태그를 제거하고 여기에 코드를 적으세요.
56 - </script>
57 - </body>
58 -</html>
59 -```
60 -
61 -다음 진행을 위해, 위의 스크립트 태그안에 JavaScript 코드를 작성합니다. (이 튜토리얼에서는) 진보된 라이브 리로드가 없기 때문에, 수정 사항을 저장한 다음에는 브라우저를 새로고침해서 확인해야 합니다. 서버를 시작한 다음 브라우저에서 `http://localhost:3000`를 열어 따라해 보세요. 아무런 수정도 하지 않았다면, 최초 로드시 우리가 만들 제품의 완성품을 확인할 수 있을 것입니다. 작업할 준비가 되면, 이전의 `<script>` 태그를 삭제하고 진행하세요.
62 -
63 -> 주의:
64 ->
65 -> 여기서는 ajax 요청 코드를 단순화 하기 위해 jQuery를 넣었지만, 이는 React의 동작에 필수적인 것은 **아닙니다**.
66 -
67 -### 첫 번째 컴포넌트
68 -
69 -모듈화 된, 조합가능한 컴포넌트가 React의 전부입니다. 댓글상자 예제에서 우리는 다음과 같은 컴포넌트 구조를 가질 것입니다:
70 -
71 -```
72 -- CommentBox
73 - - CommentList
74 - - Comment
75 - - CommentForm
76 -```
77 -
78 -자, 이제 `CommentBox` 컴포넌트를 만들어 봅시다. `<div>` 하나로 구성되어 있습니다.
79 -
80 -```javascript
81 -// tutorial1.js
82 -var CommentBox = React.createClass({
83 - render: function() {
84 - return (
85 - <div className="commentBox">
86 - Hello, world! I am a CommentBox.
87 - </div>
88 - );
89 - }
90 -});
91 -ReactDOM.render(
92 - <CommentBox />,
93 - document.getElementById('content')
94 -);
95 -```
96 -
97 -네이티브 HTML 엘리먼트 이름은 소문자로 시작하고 커스텀 React 클래스 이름은 대문자로 시작합니다.
98 -
99 -#### JSX 문법
100 -
101 -JavsScript 안의 유사 XML 구문이 먼저 눈에 띌 것입니다. 우리에겐 이를 JavaScript로 변환해주는 간단한 프리컴파일러(precompiler)가 있습니다.
102 -
103 -```javascript
104 -// tutorial1-raw.js
105 -var CommentBox = React.createClass({displayName: 'CommentBox',
106 - render: function() {
107 - return (
108 - React.createElement('div', {className: "commentBox"},
109 - "Hello, world! I am a CommentBox."
110 - )
111 - );
112 - }
113 -});
114 -ReactDOM.render(
115 - React.createElement(CommentBox, null),
116 - document.getElementById('content')
117 -);
118 -```
119 -
120 -JSX의 사용은 선택적이지만 JSX 문법이 일반 JavsScript보다 사용하기 쉽습니다. [JSX 문법 문서](/react/docs/jsx-in-depth.html)에서 더 알아보세요.
121 -
122 -#### 무슨 일이 일어나고 있는가
123 -
124 -우리는 새로운 React 컴포넌트를 만들기 위해 `React.createClass()`로 JavaScript 객체에 몇 개의 메소드를 담아 넘겼습니다. 이 중 가장 중요한것은 `render` 메소드인데, 이는 React 컴포넌트 트리를 리턴해서 최종적으로 실제 HTML을 그려주게 됩니다.
125 -
126 -`<div>` 태그들은 실제 DOM 노드가 아니라 React `div` 컴포넌트의 인스턴스입니다. 이것은 React가 다룰 수 있는 데이터의 표시자(markers)나 조각이라 생각하셔도 됩니다. React는 **안전합니다**. 생(raw) HTML 문자열을 생성하는 것이 아니기 때문에 XSS을 기본적으로 방지합니다.
127 -
128 -일반적인 HTML만 리턴할 수 있는 것은 아닙니다. 여러분이 직접 만든 (또는 다른 사람들이 만들어 놓은) 컴포넌트의 트리를 리턴할 수도 있습니다. 이것이 React를 **조합가능(composable)하게 만듭니다**: 유지보수 가능한 프론트엔드를 위한 핵심 교리(key tenet)지요.
129 -
130 -`ReactDOM.render()`는 최상위 컴포넌트의 인스턴스를 만들고, 두 번째 인수로 전달받은 DOM 엘리먼트에 마크업을 삽입해 프레임워크를 시작합니다.
131 -
132 -`ReactDOM` 모듈은 DOM 특정 메소드를 노출해, `React`가 코어 툴을 다른 플렛폼(예를 들어, [React Native](http://facebook.github.io/react-native/))에 공유할 수 있게 합니다.
133 -
134 -## 컴포넌트 조합하기
135 -
136 -이제 `CommentList`와 `CommentForm`을 위한 뼈대를 구축해 봅시다. 이전과 마찬가지로 단순히 `<div>` 태그 하나 입니다. 파일에 두 컴포넌트를 추가해, 이미 있는 `CommentBox` 선언을 참고로 `ReactDOM.render`를 호출합시다.
137 -
138 -```javascript
139 -// tutorial2.js
140 -var CommentList = React.createClass({
141 - render: function() {
142 - return (
143 - <div className="commentList">
144 - 안녕! 난 댓글목록이야.
145 - </div>
146 - );
147 - }
148 -});
149 -
150 -var CommentForm = React.createClass({
151 - render: function() {
152 - return (
153 - <div className="commentForm">
154 - 안녕! 난 댓글 폼이야.
155 - </div>
156 - );
157 - }
158 -});
159 -```
160 -
161 -다음은 `CommentBox` 컴포넌트가 새로 만든 컴포넌트들을 사용하도록 수정합니다.
162 -
163 -```javascript{6-8}
164 -// tutorial3.js
165 -var CommentBox = React.createClass({
166 - render: function() {
167 - return (
168 - <div className="commentBox">
169 - <h1>댓글</h1>
170 - <CommentList />
171 - <CommentForm />
172 - </div>
173 - );
174 - }
175 -});
176 -```
177 -
178 -방금 만든 컴포넌트들을 어떻게 HTML 태그들과 섞어 사용하는지 살펴보세요. HTML 컴포넌트들도 한가지 차이만 제외한다면 우리가 정의한 것과 같은 표준적인 React 컴포넌트입니다. JSX 컴파일러가 자동으로 HTML 태그들을 `React.createElement(tagName)` 표현식으로 재작성하고 나머지는 그대로 둘 것입니다. 이는 전역 네임스페이스가 오염되는 것을 막아줍니다.
179 -
180 -### props 사용하기
181 -
182 -부모로 부터 받은 데이터에 의존하는 `Comment` 컴포넌트를 만들어 봅시다. 부모 컴포넌트로 부터 받은 데이터는 자식 컴포넌트에서 '프로퍼티'로 사용가능 합니다. 이 '프로퍼티들'은 `this.props`를 통해 접근합니다. props를 사용해, `CommentList`에서 전달받은 데이터를 읽어들이고, 마크업을 렌더할 수 있을 것입니다.
183 -
184 -
185 -```javascript
186 -// tutorial4.js
187 -var Comment = React.createClass({
188 - render: function() {
189 - return (
190 - <div className="comment">
191 - <h2 className="commentAuthor">
192 - {this.props.author}
193 - </h2>
194 - {this.props.children}
195 - </div>
196 - );
197 - }
198 -});
199 -```
200 -
201 -JSX 내부의 중괄호로 둘러싸인 JavaScript 표현식(어트리뷰트나 엘리먼트의 자식으로 사용된)을 통해 텍스트나 React 컴포넌트를 트리에 더할 수 있습니다. `this.props`를 통해 컴포넌트에 전달된 특정한 어트리뷰트들에, `this.props.children`을 통해 중첩된 엘리먼트들에 접근할 수 있습니다.
202 -
203 -### 컴포넌트 프로퍼티 (Component Properties)
204 -
205 -`Comment` 컴포넌트를 만들었으니, 여기에 글쓴이와 내용을 넘겨보도록 합시다. 이렇게 함으로써 각 고유한 comment에서 같은 코드를 재사용할 수 있습니다. 먼저 댓글 몇 개를 `CommentList`에 추가해 봅시다:
206 -
207 -```javascript{6-7}
208 -// tutorial5.js
209 -var CommentList = React.createClass({
210 - render: function() {
211 - return (
212 - <div className="commentList">
213 - <Comment author="Pete Hunt">댓글입니다</Comment>
214 - <Comment author="Jordan Walke">*또 다른* 댓글입니다</Comment>
215 - </div>
216 - );
217 - }
218 -});
219 -```
220 -
221 -부모 컴포넌트인 `CommentList`에서 자식 컴포넌트인 `Comment`에 데이터들을 전달하고 있는것을 확인할 수 있습니다. 예를 들어, 우리는 어트리뷰트로 *Pete Hunt*를, XML 형식의 자식 노드로 *댓글입니다*를 첫 번째 `Comment`로 넘겼습니다. 위에서 언급했듯이 `Comment` 컴포넌트는 그들의 '프로퍼티'를 `this.props.author`, `this.props.children`를 통해 접근합니다.
222 -
223 -### Markdown 추가하기
224 -
225 -Markdown은 텍스트를 포맷팅하는 간단한 방식입니다. 예를 들어, 별표(`*`)로 텍스트를 둘러싸는 것은 강조의 의미입니다.
226 -
227 -먼저 서드파티 라이브러리인 **remarkable**를 애플리케이션에 추가합니다. 이 JavaScript 라이브러리는 Markdown 텍스트를 HTML 문법으로 변환해줍니다. head 태그안에 스크립트 태그를 추가해 주세요. (React playground에는 이미 포함되어 있습니다):
228 -
229 -```html{9}
230 -<!-- index.html -->
231 -<head>
232 - <meta charset="utf-8" />
233 - <title>React Tutorial</title>
234 - <script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script>
235 - <script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
236 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
237 - <script src="https://unpkg.com/jquery@3.1.0/dist/jquery.min.js"></script>
238 - <script src="https://unpkg.com/remarkable@1.7.1/dist/remarkable.min.js"></script>
239 -</head>
240 -```
241 -
242 -다음은, 댓글 텍스트를 Markdown으로 전환하고 출력해 봅시다.
243 -
244 -```javascript{4,10}
245 -// tutorial6.js
246 -var Comment = React.createClass({
247 - render: function() {
248 - var md = new Remarkable();
249 - return (
250 - <div className="comment">
251 - <h2 className="commentAuthor">
252 - {this.props.author}
253 - </h2>
254 - {md.render(this.props.children.toString())}
255 - </div>
256 - );
257 - }
258 -});
259 -```
260 -
261 -우리가 한 일이라고는 remarkable 라이브러리를 호출한 것 뿐입니다. remarkable가 `this.props.children`에서 텍스트를 읽어들여 처리할 수 있도록 React 형식의 텍스트(React's wrapped text)를 단순 텍스트(raw string)으로 전환하기 위해 명시적으로 `toString()`을 호출했습니다.
262 -
263 -하지만 여기엔 문제가 있습니다! 우리는 HTML 태그들이 정상적으로 렌더되길 원하지만 브라우저에 출력된 결과물은 "`<p>``<em>`또 다른`</em>` 댓글입니다`</p>`"처럼 태그가 그대로 보일것입니다.
264 -
265 -React는 이런 식으로 [XSS 공격](https://en.wikipedia.org/wiki/Cross-site_scripting)을 예방합니다. 우회할 방법이 있긴 하지만 프레임워크는 사용하지 않도록 경고하고 있습니다:
266 -
267 -```javascript{3-7,15}
268 -// tutorial7.js
269 -var Comment = React.createClass({
270 - rawMarkup: function() {
271 - var md = new Remarkable();
272 - var rawMarkup = md.render(this.props.children.toString());
273 - return { __html: rawMarkup };
274 - },
275 -
276 - render: function() {
277 - return (
278 - <div className="comment">
279 - <h2 className="commentAuthor">
280 - {this.props.author}
281 - </h2>
282 - <span dangerouslySetInnerHTML={this.rawMarkup()} />
283 - </div>
284 - );
285 - }
286 -});
287 -```
288 -
289 -이는 의도적으로 생(raw) HTML을 넣기 힘들게 하려고 만든 특별한 API지만 remarkable를 사용하기 위해 이 백도어를 활용합시다.
290 -
291 -**잊지 마세요:** 이 기능은 remarkable가 안전한 것으로 믿고 사용하는 것입니다.
292 -
293 -### 데이터 모델 연결하기
294 -
295 -지금까지는 소스코드에 직접 댓글을 넣었습니다. 이제부터는 JSON 데이터 덩어리를 댓글 목록에 렌더해보겠습니다. 최종적으로는 서버에서 데이터가 내려오겠지만, 지금은 소스에 직접 데이터를 넣어봅시다:
296 -
297 -```javascript
298 -// tutorial8.js
299 -var data = [
300 - {author: "Pete Hunt", text: "댓글입니다"},
301 - {author: "Jordan Walke", text: "*또 다른* 댓글입니다"}
302 -];
303 -```
304 -
305 -이 데이터를 모듈화된 방식으로 `CommentList`에 넣어야 합니다. props을 이용해 데이터를 넘기도록 `CommentBox`와 `ReactDOM.render()` 호출 코드를 수정합시다.
306 -
307 -```javascript{7,15}
308 -// tutorial9.js
309 -var CommentBox = React.createClass({
310 - render: function() {
311 - return (
312 - <div className="commentBox">
313 - <h1>댓글</h1>
314 - <CommentList data={this.props.data} />
315 - <CommentForm />
316 - </div>
317 - );
318 - }
319 -});
320 -
321 -ReactDOM.render(
322 - <CommentBox data={data} />,
323 - document.getElementById('content')
324 -);
325 -```
326 -
327 -이제 `CommentList`에서 데이터를 다룰 수 있습니다. 댓글을 동적으로 렌더해봅시다:
328 -
329 -```javascript{4-10,13}
330 -// tutorial10.js
331 -var CommentList = React.createClass({
332 - render: function() {
333 - var commentNodes = this.props.data.map(function (comment) {
334 - return (
335 - <Comment author={comment.author} key={comment.id}>
336 - {comment.text}
337 - </Comment>
338 - );
339 - });
340 - return (
341 - <div className="commentList">
342 - {commentNodes}
343 - </div>
344 - );
345 - }
346 -});
347 -```
348 -
349 -이게 전부입니다!
350 -
351 -### 서버에서 가져오기(Fetching)
352 -
353 -이제 데이터를 소스에 직접 넣는 방식에서 서버에서 동적으로 받아서 처리하는 방식으로 바꿔봅시다. 데이터 prop을 삭제하고 처리할 URL로 변경해 줍시다.
354 -
355 -```javascript{3}
356 -// tutorial11.js
357 -ReactDOM.render(
358 - <CommentBox url="/api/comments" />,
359 - document.getElementById('content')
360 -);
361 -```
362 -
363 -이 컴포넌트는 이전 것과 다르게, 스스로 다시 렌더링해야 합니다. 컴포넌트는 서버에서 요청이 들어올때까지는 아무 데이터도 가지고 있지 않다가, 특정한 시점에서 새로운 댓글을 렌더할 필요가 있을 것입니다.
364 -
365 -주의: 이 단계에서 코드는 아직 동작하지 않습니다.
366 -
367 -### 반응적 state
368 -
369 -지금까지, 각각의 컴포넌트는 props를 기반으로 한번 렌더되었습니다. `props`는 불변성을 갖습니다: 그것들은 부모에서 전달되어 부모에게 "소유" 되어 있습니다. 컴포넌트에 상호작용을 구현하기 위해서, 가변성을 갖는 **state**를 소개합니다. `this.state`는 컴포넌트에 한정(private)되며 `this.setState()`를 통해 변경할 수 있습니다. state가 업데이트 되면, 컴포넌트는 자신을 스스로 다시 렌더링합니다.
370 -
371 -`render()` 메소드는 `this.props`와 `this.state`를 위한 함수로 선언적으로 작성됩니다. 프레임워크에서 입력값에 따른 UI가 항상 일관성 있음을 보장해줍니다.
372 -
373 -서버가 데이터를 가져오면 댓글 데이터가 변경될 것입니다. 댓글 데이터의 배열을 `CommentBox`의 state로 추가해봅시다:
374 -
375 -```javascript{3-5,10}
376 -// tutorial12.js
377 -var CommentBox = React.createClass({
378 - getInitialState: function() {
379 - return {data: []};
380 - },
381 - render: function() {
382 - return (
383 - <div className="commentBox">
384 - <h1>댓글</h1>
385 - <CommentList data={this.state.data} />
386 - <CommentForm />
387 - </div>
388 - );
389 - }
390 -});
391 -```
392 -
393 -`getInitialState()` 는 컴포넌트의 생명주기동안 한 번만 실행되며 컴포넌트의 초기 state를 설정합니다.
394 -
395 -### state 업데이트하기
396 -
397 -컴포넌트의 최초 생성 시에, 서버에서 GET 방식으로 JSON을 넘겨받아 최신의 데이터가 state에 반영되길 원했습니다. jQuery를 사용해 서버에 비동기 요청을 만들어 필요한 데이터를 빨리 가져올 수 있게 하겠습니다. 이런 식입니다.
398 -
399 -```json
400 -[
401 - {"author": "Pete Hunt", "text": "댓글입니다"},
402 - {"author": "Jordan Walke", "text": "*또 다른* 댓글입니다"}
403 -]
404 -```
405 -
406 -```javascript{6-18}
407 -// tutorial13.js
408 -var CommentBox = React.createClass({
409 - getInitialState: function() {
410 - return {data: []};
411 - },
412 - componentDidMount: function() {
413 - $.ajax({
414 - url: this.props.url,
415 - dataType: 'json',
416 - cache: false,
417 - success: function(data) {
418 - this.setState({data: data});
419 - }.bind(this),
420 - error: function(xhr, status, err) {
421 - console.error(this.props.url, status, err.toString());
422 - }.bind(this)
423 - });
424 - },
425 - render: function() {
426 - return (
427 - <div className="commentBox">
428 - <h1>댓글</h1>
429 - <CommentList data={this.state.data} />
430 - <CommentForm />
431 - </div>
432 - );
433 - }
434 -});
435 -```
436 -
437 -여기서 `componentDidMount`는 컴포넌트가 렌더링 된 다음 React에 의해 자동으로 호출되는 메소드입니다. 동적 업데이트의 핵심은 `this.setState()`의 호출입니다. 우리가 이전의 댓글 목록을 서버에서 넘어온 새로운 목록으로 변경하면 자동으로 UI가 업데이트 될 것입니다. 이 반응성 덕분에 실시간 업데이트에 아주 작은 수정만 가해집니다. 우리는 여기선 간단한 폴링을 사용할 것이지만 웹소켓등의 다른 기술도 쉽게 사용할 수 있습니다.
438 -
439 -```javascript{3,15,20-21,35}
440 -// tutorial14.js
441 -var CommentBox = React.createClass({
442 - loadCommentsFromServer: function() {
443 - $.ajax({
444 - url: this.props.url,
445 - dataType: 'json',
446 - cache: false,
447 - success: function(data) {
448 - this.setState({data: data});
449 - }.bind(this),
450 - error: function(xhr, status, err) {
451 - console.error(this.props.url, status, err.toString());
452 - }.bind(this)
453 - });
454 - },
455 - getInitialState: function() {
456 - return {data: []};
457 - },
458 - componentDidMount: function() {
459 - this.loadCommentsFromServer();
460 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
461 - },
462 - render: function() {
463 - return (
464 - <div className="commentBox">
465 - <h1>댓글</h1>
466 - <CommentList data={this.state.data} />
467 - <CommentForm />
468 - </div>
469 - );
470 - }
471 -});
472 -
473 -ReactDOM.render(
474 - <CommentBox url="/api/comments" pollInterval={2000} />,
475 - document.getElementById('content')
476 -);
477 -
478 -```
479 -
480 -우리가 여기서 한것은 AJAX 호출을 별도의 메소드로 분리하고 컴포넌트가 처음 로드된 시점부터 2초 간격으로 계속 호출되도록 한 것입니다. 브라우저에서 직접 돌려보고 `comments.json` 파일(서버의 같은 디렉토리에 있습니다)을 수정해보세요. 2초 간격으로 변화되는 모습이 보일 것입니다!
481 -
482 -### 새로운 댓글 추가하기
483 -
484 -이제 폼을 만들어볼 시간입니다. 우리의 `CommentForm` 컴포넌트는 사용자에게 이름과 내용을 입력받고 댓글을 저장하기 위해 서버에 요청을 전송해야 합니다.
485 -
486 -```javascript{5-9}
487 -// tutorial15.js
488 -var CommentForm = React.createClass({
489 - render: function() {
490 - return (
491 - <form className="commentForm">
492 - <input type="text" placeholder="이름" />
493 - <input type="text" placeholder="내용을 입력하세요..." />
494 - <input type="submit" value="올리기" />
495 - </form>
496 - );
497 - }
498 -});
499 -```
500 -
501 -이제 폼의 상호작용을 만들어 보겠습니다. 사용자가 폼을 전송하는 시점에 우리는 폼을 초기화하고 서버에 요청을 전송하고 댓글목록을 업데이트해야 합니다. 폼의 submit 이벤트를 감시하고 초기화 해주는 부분부터 시작해 보죠.
502 -
503 -```javascript{3-13,16-19}
504 -// tutorial16.js
505 -var CommentForm = React.createClass({
506 - handleSubmit: function(e) {
507 - e.preventDefault();
508 - var author = this.refs.author.value.trim();
509 - var text = this.refs.text.value.trim();
510 - if (!text || !author) {
511 - return;
512 - }
513 - // TODO: 서버에 요청을 전송합니다
514 - this.refs.author.value = '';
515 - this.refs.text.value = '';
516 - return;
517 - },
518 - render: function() {
519 - return (
520 - <form className="commentForm" onSubmit={this.handleSubmit}>
521 - <input type="text" placeholder="이름" ref="author" />
522 - <input type="text" placeholder="내용을 입력하세요..." ref="text" />
523 - <input type="submit" value="올리기" />
524 - </form>
525 - );
526 - }
527 -});
528 -```
529 -
530 -##### 이벤트
531 -
532 -React는 카멜케이스 네이밍 컨벤션으로 컴포넌트에 이벤트 핸들러를 등록합니다. 폼이 유효한 값으로 submit되었을 때 폼필드들을 초기화하도록 `onSubmit` 핸들러를 등록합니다.
533 -
534 -폼 submit에 대한 브라우저의 기본동작을 막기 위해 이벤트시점에 `preventDefault()`를 호출합니다.
535 -
536 -##### Refs
537 -
538 -자식 컴포넌트의 이름을 지정하기 위해 `ref` 어트리뷰트를, DOM 노드를 참조하기 위해 `this.refs`를 사용합니다.
539 -
540 -##### props으로 콜백 처리하기
541 -
542 -사용자가 댓글을 등록할 때, 새로운 댓글을 추가하기 위해 댓글목록을 업데이트해주어야 합니다. `CommentBox`가 댓글목록의 state를 소유하고 있기 때문에 이 로직 또한 `CommentBox`에 있는것이 타당합니다.
543 -
544 -자식 컴포넌트가 그의 부모에게 데이터를 넘겨줄 필요가 있습니다. 부모의 `render` 메소드에서 새로운 콜백(`handleCommentSubmit`)을 자식에게 넘겨주고, 자식의 `onCommentSubmit` 이벤트에 그것을 바인딩해주는 식으로 구현합니다. 이벤트가 작동될때(triggered)마다, 콜백이 호출됩니다:
545 -
546 -```javascript{16-18,31}
547 -// tutorial17.js
548 -var CommentBox = React.createClass({
549 - loadCommentsFromServer: function() {
550 - $.ajax({
551 - url: this.props.url,
552 - dataType: 'json',
553 - cache: false,
554 - success: function(data) {
555 - this.setState({data: data});
556 - }.bind(this),
557 - error: function(xhr, status, err) {
558 - console.error(this.props.url, status, err.toString());
559 - }.bind(this)
560 - });
561 - },
562 - handleCommentSubmit: function(comment) {
563 - // TODO: 서버에 요청을 수행하고 목록을 업데이트한다
564 - },
565 - getInitialState: function() {
566 - return {data: []};
567 - },
568 - componentDidMount: function() {
569 - this.loadCommentsFromServer();
570 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
571 - },
572 - render: function() {
573 - return (
574 - <div className="commentBox">
575 - <h1>댓글</h1>
576 - <CommentList data={this.state.data} />
577 - <CommentForm onCommentSubmit={this.handleCommentSubmit} />
578 - </div>
579 - );
580 - }
581 -});
582 -```
583 -
584 -사용자가 폼을 전송할 때, `CommentForm`에서 콜백을 호출해 봅시다:
585 -
586 -```javascript{10}
587 -// tutorial18.js
588 -var CommentForm = React.createClass({
589 - handleSubmit: function(e) {
590 - e.preventDefault();
591 - var author = this.refs.author.value.trim();
592 - var text = this.refs.text.value.trim();
593 - if (!text || !author) {
594 - return;
595 - }
596 - this.props.onCommentSubmit({author: author, text: text});
597 - this.refs.author.value = '';
598 - this.refs.text.value = '';
599 - return;
600 - },
601 - render: function() {
602 - return (
603 - <form className="commentForm" onSubmit={this.handleSubmit}>
604 - <input type="text" placeholder="이름" ref="author" />
605 - <input type="text" placeholder="이름을 입력하세요..." ref="text" />
606 - <input type="submit" value="올리기" />
607 - </form>
608 - );
609 - }
610 -});
611 -```
612 -
613 -이제 콜백이 제자리를 찾았습니다. 우리가 할 일은 서버에 요청을 날리고 목록을 업데이트하는 것 뿐입니다:
614 -
615 -```javascript{17-28}
616 -// tutorial19.js
617 -var CommentBox = React.createClass({
618 - loadCommentsFromServer: function() {
619 - $.ajax({
620 - url: this.props.url,
621 - dataType: 'json',
622 - cache: false,
623 - success: function(data) {
624 - this.setState({data: data});
625 - }.bind(this),
626 - error: function(xhr, status, err) {
627 - console.error(this.props.url, status, err.toString());
628 - }.bind(this)
629 - });
630 - },
631 - handleCommentSubmit: function(comment) {
632 - $.ajax({
633 - url: this.props.url,
634 - dataType: 'json',
635 - type: 'POST',
636 - data: comment,
637 - success: function(data) {
638 - this.setState({data: data});
639 - }.bind(this),
640 - error: function(xhr, status, err) {
641 - console.error(this.props.url, status, err.toString());
642 - }.bind(this)
643 - });
644 - },
645 - getInitialState: function() {
646 - return {data: []};
647 - },
648 - componentDidMount: function() {
649 - this.loadCommentsFromServer();
650 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
651 - },
652 - render: function() {
653 - return (
654 - <div className="commentBox">
655 - <h1>댓글</h1>
656 - <CommentList data={this.state.data} />
657 - <CommentForm onCommentSubmit={this.handleCommentSubmit} />
658 - </div>
659 - );
660 - }
661 -});
662 -```
663 -
664 -### 최적화: 낙관적 업데이트
665 -
666 -우리의 애플리케이션은 이제 모든 기능을 갖추었습니다. 하지만 댓글이 목록에 업데이트되기 전에 완료요청을 기다리는 게 조금 느린듯한 느낌이 드네요. 우리는 낙관적 업데이트를 통해 댓글이 목록에 추가되도록 함으로써 앱이 좀 더 빨라진 것처럼 느껴지도록 할 수 있습니다.
667 -
668 -```javascript{17-19,29}
669 -// tutorial20.js
670 -var CommentBox = React.createClass({
671 - loadCommentsFromServer: function() {
672 - $.ajax({
673 - url: this.props.url,
674 - dataType: 'json',
675 - cache: false,
676 - success: function(data) {
677 - this.setState({data: data});
678 - }.bind(this),
679 - error: function(xhr, status, err) {
680 - console.error(this.props.url, status, err.toString());
681 - }.bind(this)
682 - });
683 - },
684 - handleCommentSubmit: function(comment) {
685 - var comments = this.state.data;
686 - var newComments = comments.concat([comment]);
687 - this.setState({data: newComments});
688 - $.ajax({
689 - url: this.props.url,
690 - dataType: 'json',
691 - type: 'POST',
692 - data: comment,
693 - success: function(data) {
694 - this.setState({data: data});
695 - }.bind(this),
696 - error: function(xhr, status, err) {
697 - this.setState({data: comments});
698 - console.error(this.props.url, status, err.toString());
699 - }.bind(this)
700 - });
701 - },
702 - getInitialState: function() {
703 - return {data: []};
704 - },
705 - componentDidMount: function() {
706 - this.loadCommentsFromServer();
707 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
708 - },
709 - render: function() {
710 - return (
711 - <div className="commentBox">
712 - <h1>댓글</h1>
713 - <CommentList data={this.state.data} />
714 - <CommentForm onCommentSubmit={this.handleCommentSubmit} />
715 - </div>
716 - );
717 - }
718 -});
719 -```
720 -
721 -### 축하합니다!
722 -
723 -몇 단계를 거쳐 간단하게 댓글창을 만들어 보았습니다. [왜 React인가](/react/docs/why-react-ko-KR.html)에서 더 알아보거나, 혹은 [API 레퍼런스](/react/docs/top-level-api-ko-KR.html)에 뛰어들어 해킹을 시작하세요! 행운을 빕니다!
docs/docs/tutorial.md deleted
-788
@@ -1,788 +0,0 @@
1 ----
2 -id: tutorial
3 -title: Tutorial
4 -permalink: docs/tutorial.html
5 -prev: getting-started.html
6 -next: thinking-in-react.html
7 ----
8 -
9 -We'll be building a simple but realistic comments box that you can drop into a blog, a basic version of the realtime comments offered by Disqus, LiveFyre or Facebook comments.
10 -
11 -We'll provide:
12 -
13 -* A view of all of the comments
14 -* A form to submit a comment
15 -* Hooks for you to provide a custom backend
16 -
17 -It'll also have a few neat features:
18 -
19 -* **Optimistic commenting:** comments appear in the list before they're saved on the server so it feels fast.
20 -* **Live updates:** other users' comments are popped into the comment view in real time.
21 -* **Markdown formatting:** users can use Markdown to format their text.
22 -
23 -### Want to skip all this and just see the source?
24 -
25 -[It's all on GitHub.](https://github.com/reactjs/react-tutorial)
26 -
27 -### Running a server
28 -
29 -In order to start this tutorial, we're going to require a running server. This will serve purely as an API endpoint which we'll use for getting and saving data. In order to make this as easy as possible, we've created a simple server in a number of scripting languages that does exactly what we need it to do. **You can [view the source](https://github.com/reactjs/react-tutorial/) or [download a zip file](https://github.com/reactjs/react-tutorial/archive/master.zip) containing everything needed to get started.**
30 -
31 -For sake of simplicity, the server we will run uses a `JSON` file as a database. You would not run this in production but it makes it easy to simulate what you might do when consuming an API. Once you [start the server](https://github.com/reactjs/react-tutorial/#to-use), it will support our API endpoint and it will also serve the static pages we need.
32 -
33 -### Getting started
34 -
35 -For this tutorial, we're going to make it as easy as possible. Included in the server package discussed above is an HTML file which we'll work in. Open up `public/index.html` in your favorite editor. It should look something like this:
36 -
37 -```html
38 -<!-- index.html -->
39 -<!DOCTYPE html>
40 -<html>
41 - <head>
42 - <meta charset="utf-8" />
43 - <title>React Tutorial</title>
44 - <script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script>
45 - <script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
46 - <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
47 - <script src="https://unpkg.com/jquery@3.1.0/dist/jquery.min.js"></script>
48 - <script src="https://unpkg.com/remarkable@1.7.1/dist/remarkable.min.js"></script>
49 - </head>
50 - <body>
51 - <div id="content"></div>
52 - <script type="text/babel" src="scripts/example.js"></script>
53 - <script type="text/babel">
54 - // To get started with this tutorial running your own code, simply remove
55 - // the script tag loading scripts/example.js and start writing code here.
56 - </script>
57 - </body>
58 -</html>
59 -```
60 -
61 -For the remainder of this tutorial, we'll be writing our JavaScript code in this script tag. We don't have any advanced live-reloading so you'll need to refresh your browser to see updates after saving. Follow your progress by opening `http://localhost:3000` in your browser (after starting the server). When you load this for the first time without any changes, you'll see the finished product of what we're going to build. When you're ready to start working, just delete the preceding `<script>` tag and then you can continue.
62 -
63 -> Note:
64 ->
65 -> We included jQuery here because we want to simplify the code of our future AJAX calls, but it's **NOT** mandatory for React to work.
66 -
67 -### Your first component
68 -
69 -React is all about modular, composable components. For our comment box example, we'll have the following component structure:
70 -
71 -```
72 -- CommentBox
73 - - CommentList
74 - - Comment
75 - - CommentForm
76 -```
77 -
78 -Let's build the `CommentBox` component, which is just a simple `<div>`:
79 -
80 -```javascript
81 -// tutorial1.js
82 -var CommentBox = React.createClass({
83 - render: function() {
84 - return (
85 - <div className="commentBox">
86 - Hello, world! I am a CommentBox.
87 - </div>
88 - );
89 - }
90 -});
91 -ReactDOM.render(
92 - <CommentBox />,
93 - document.getElementById('content')
94 -);
95 -```
96 -
97 -Note that native HTML element names start with a lowercase letter, while custom React class names begin with an uppercase letter.
98 -
99 -#### JSX Syntax
100 -
101 -The first thing you'll notice is the XML-ish syntax in your JavaScript. We have a simple precompiler that translates the syntactic sugar to this plain JavaScript:
102 -
103 -```javascript
104 -// tutorial1-raw.js
105 -var CommentBox = React.createClass({displayName: 'CommentBox',
106 - render: function() {
107 - return (
108 - React.createElement('div', {className: "commentBox"},
109 - "Hello, world! I am a CommentBox."
110 - )
111 - );
112 - }
113 -});
114 -ReactDOM.render(
115 - React.createElement(CommentBox, null),
116 - document.getElementById('content')
117 -);
118 -```
119 -
120 -Its use is optional but we've found JSX syntax easier to use than plain JavaScript. Read more on the [JSX Syntax article](/react/docs/jsx-in-depth.html).
121 -
122 -#### What's going on
123 -
124 -We pass some methods in a JavaScript object to `React.createClass()` to create a new React component. The most important of these methods is called `render` which returns a tree of React components that will eventually render to HTML.
125 -
126 -The `<div>` tags are not actual DOM nodes; they are instantiations of React `div` components. You can think of these as markers or pieces of data that React knows how to handle. React is **safe**. We are not generating HTML strings so XSS protection is the default.
127 -
128 -You do not have to return basic HTML. You can return a tree of components that you (or someone else) built. This is what makes React **composable**: a key tenet of maintainable frontends.
129 -
130 -`ReactDOM.render()` instantiates the root component, starts the framework, and injects the markup into a raw DOM element, provided as the second argument.
131 -
132 -The `ReactDOM` module exposes DOM-specific methods, while `React` has the core tools shared by React on different platforms (e.g., [React Native](http://facebook.github.io/react-native/)).
133 -
134 -It is important that `ReactDOM.render` remain at the bottom of the script for this tutorial. `ReactDOM.render` should only be called after the composite components have been defined.
135 -
136 -## Composing components
137 -
138 -Let's build skeletons for `CommentList` and `CommentForm` which will, again, be simple `<div>`s. Add these two components to your file, keeping the existing `CommentBox` declaration and `ReactDOM.render` call:
139 -
140 -```javascript
141 -// tutorial2.js
142 -var CommentList = React.createClass({
143 - render: function() {
144 - return (
145 - <div className="commentList">
146 - Hello, world! I am a CommentList.
147 - </div>
148 - );
149 - }
150 -});
151 -
152 -var CommentForm = React.createClass({
153 - render: function() {
154 - return (
155 - <div className="commentForm">
156 - Hello, world! I am a CommentForm.
157 - </div>
158 - );
159 - }
160 -});
161 -```
162 -
163 -Next, update the `CommentBox` component to use these new components:
164 -
165 -```javascript{6-8}
166 -// tutorial3.js
167 -var CommentBox = React.createClass({
168 - render: function() {
169 - return (
170 - <div className="commentBox">
171 - <h1>Comments</h1>
172 - <CommentList />
173 - <CommentForm />
174 - </div>
175 - );
176 - }
177 -});
178 -```
179 -
180 -Notice how we're mixing HTML tags and components we've built. HTML components are regular React components, just like the ones you define, with one difference. The JSX compiler will automatically rewrite HTML tags to `React.createElement(tagName)` expressions and leave everything else alone. This is to prevent the pollution of the global namespace.
181 -
182 -### Using props
183 -
184 -Let's create the `Comment` component, which will depend on data passed in from our `CommentList` component. Data passed in from the `CommentList` component is available as a 'property' on our `Comment` component. These 'properties' are accessed through `this.props`. Using props, we will be able to read the data passed to the `Comment` from the `CommentList`, and render some markup:
185 -
186 -```javascript
187 -// tutorial4.js
188 -var Comment = React.createClass({
189 - render: function() {
190 - return (
191 - <div className="comment">
192 - <h2 className="commentAuthor">
193 - {this.props.author}
194 - </h2>
195 - {this.props.children}
196 - </div>
197 - );
198 - }
199 -});
200 -```
201 -
202 -By surrounding a JavaScript expression in braces inside JSX (as either an attribute or child), you can drop text or React components into the tree. We access named attributes passed to the component as keys on `this.props` and any nested elements as `this.props.children`.
203 -
204 -### Component Properties
205 -
206 -Now that we have defined the `Comment` component, we will want to pass it the author name and comment text. This allows us to reuse the same code for each unique comment. Now let's add some comments within our `CommentList`:
207 -
208 -```javascript{6-7}
209 -// tutorial5.js
210 -var CommentList = React.createClass({
211 - render: function() {
212 - return (
213 - <div className="commentList">
214 - <Comment author="Pete Hunt">This is one comment</Comment>
215 - <Comment author="Jordan Walke">This is *another* comment</Comment>
216 - </div>
217 - );
218 - }
219 -});
220 -```
221 -
222 -Note that we have passed some data from the parent `CommentList` component to the child `Comment` components. For example, we passed *Pete Hunt* (via the `author` attribute) and *This is one comment* (via an XML-like child node) to the first `Comment`. As noted above, the `Comment` component will access these 'properties' through `this.props.author`, and `this.props.children`.
223 -
224 -### Adding Markdown
225 -
226 -Markdown is a simple way to format your text inline. For example, surrounding text with asterisks will make it emphasized.
227 -
228 -In this tutorial we use a third-party library **remarkable** which takes Markdown text and converts it to raw HTML. We already included this library with the original markup for the page, so we can just start using it. Let's convert the comment text to Markdown and output it:
229 -
230 -```javascript{4,10}
231 -// tutorial6.js
232 -var Comment = React.createClass({
233 - render: function() {
234 - var md = new Remarkable();
235 - return (
236 - <div className="comment">
237 - <h2 className="commentAuthor">
238 - {this.props.author}
239 - </h2>
240 - {md.render(this.props.children.toString())}
241 - </div>
242 - );
243 - }
244 -});
245 -```
246 -
247 -All we're doing here is calling the remarkable library. We need to convert `this.props.children` from React's wrapped text to a raw string that remarkable will understand so we explicitly call `toString()`.
248 -
249 -But there's a problem! Our rendered comments look like this in the browser: "`<p>`This is `<em>`another`</em>` comment`</p>`". We want those tags to actually render as HTML.
250 -
251 -That's React protecting you from an [XSS attack](https://en.wikipedia.org/wiki/Cross-site_scripting). There's a way to get around it but the framework warns you not to use it:
252 -
253 -```javascript{3-7,15}
254 -// tutorial7.js
255 -var Comment = React.createClass({
256 - rawMarkup: function() {
257 - var md = new Remarkable();
258 - var rawMarkup = md.render(this.props.children.toString());
259 - return { __html: rawMarkup };
260 - },
261 -
262 - render: function() {
263 - return (
264 - <div className="comment">
265 - <h2 className="commentAuthor">
266 - {this.props.author}
267 - </h2>
268 - <span dangerouslySetInnerHTML={this.rawMarkup()} />
269 - </div>
270 - );
271 - }
272 -});
273 -```
274 -
275 -This is a special API that intentionally makes it difficult to insert raw HTML, but for remarkable we'll take advantage of this backdoor.
276 -
277 -**Remember:** by using this feature you're relying on remarkable to be secure. In this case, remarkable automatically strips HTML markup and insecure links from the output.
278 -
279 -### Hook up the data model
280 -
281 -So far we've been inserting the comments directly in the source code. Instead, let's render a blob of JSON data into the comment list. Eventually this will come from the server, but for now, write it in your source:
282 -
283 -```javascript
284 -// tutorial8.js
285 -var data = [
286 - {id: 1, author: "Pete Hunt", text: "This is one comment"},
287 - {id: 2, author: "Jordan Walke", text: "This is *another* comment"}
288 -];
289 -```
290 -
291 -We need to get this data into `CommentList` in a modular way. Modify `CommentBox` and the `ReactDOM.render()` call to pass this data into the `CommentList` via props:
292 -
293 -```javascript{7,15}
294 -// tutorial9.js
295 -var CommentBox = React.createClass({
296 - render: function() {
297 - return (
298 - <div className="commentBox">
299 - <h1>Comments</h1>
300 - <CommentList data={this.props.data} />
301 - <CommentForm />
302 - </div>
303 - );
304 - }
305 -});
306 -
307 -ReactDOM.render(
308 - <CommentBox data={data} />,
309 - document.getElementById('content')
310 -);
311 -```
312 -
313 -Now that the data is available in the `CommentList`, let's render the comments dynamically:
314 -
315 -```javascript{4-10,13}
316 -// tutorial10.js
317 -var CommentList = React.createClass({
318 - render: function() {
319 - var commentNodes = this.props.data.map(function(comment) {
320 - return (
321 - <Comment author={comment.author} key={comment.id}>
322 - {comment.text}
323 - </Comment>
324 - );
325 - });
326 - return (
327 - <div className="commentList">
328 - {commentNodes}
329 - </div>
330 - );
331 - }
332 -});
333 -```
334 -
335 -That's it!
336 -
337 -### Fetching from the server
338 -
339 -Let's replace the hard-coded data with some dynamic data from the server. We will remove the data prop and replace it with a URL to fetch:
340 -
341 -```javascript{3}
342 -// tutorial11.js
343 -ReactDOM.render(
344 - <CommentBox url="/api/comments" />,
345 - document.getElementById('content')
346 -);
347 -```
348 -
349 -This component is different from the prior components because it will have to re-render itself. The component won't have any data until the request from the server comes back, at which point the component may need to render some new comments.
350 -
351 -Note: the code will not be working at this step.
352 -
353 -### Reactive state
354 -
355 -So far, based on its props, each component has rendered itself once. `props` are immutable: they are passed from the parent and are "owned" by the parent. To implement interactions, we introduce mutable **state** to the component. `this.state` is private to the component and can be changed by calling `this.setState()`. When the state updates, the component re-renders itself.
356 -
357 -`render()` methods are written declaratively as functions of `this.props` and `this.state`. The framework guarantees the UI is always consistent with the inputs.
358 -
359 -When the server fetches data, we will be changing the comment data we have. Let's add an array of comment data to the `CommentBox` component as its state:
360 -
361 -```javascript{3-5,10}
362 -// tutorial12.js
363 -var CommentBox = React.createClass({
364 - getInitialState: function() {
365 - return {data: []};
366 - },
367 - render: function() {
368 - return (
369 - <div className="commentBox">
370 - <h1>Comments</h1>
371 - <CommentList data={this.state.data} />
372 - <CommentForm />
373 - </div>
374 - );
375 - }
376 -});
377 -```
378 -
379 -`getInitialState()` executes exactly once during the lifecycle of the component and sets up the initial state of the component.
380 -
381 -#### Updating state
382 -When the component is first created, we want to GET some JSON from the server and update the state to reflect the latest data. We're going to use jQuery to make an asynchronous request to the server we started earlier to fetch the data we need. The data is already included in the server you started (based on the `comments.json` file), so once it's fetched, `this.state.data` will look something like this:
383 -
384 -```json
385 -[
386 - {"id": "1", "author": "Pete Hunt", "text": "This is one comment"},
387 - {"id": "2", "author": "Jordan Walke", "text": "This is *another* comment"}
388 -]
389 -```
390 -
391 -```javascript{6-18}
392 -// tutorial13.js
393 -var CommentBox = React.createClass({
394 - getInitialState: function() {
395 - return {data: []};
396 - },
397 - componentDidMount: function() {
398 - $.ajax({
399 - url: this.props.url,
400 - dataType: 'json',
401 - cache: false,
402 - success: function(data) {
403 - this.setState({data: data});
404 - }.bind(this),
405 - error: function(xhr, status, err) {
406 - console.error(this.props.url, status, err.toString());
407 - }.bind(this)
408 - });
409 - },
410 - render: function() {
411 - return (
412 - <div className="commentBox">
413 - <h1>Comments</h1>
414 - <CommentList data={this.state.data} />
415 - <CommentForm />
416 - </div>
417 - );
418 - }
419 -});
420 -```
421 -
422 -Here, `componentDidMount` is a method called automatically by React after a component is rendered for the first time. The key to dynamic updates is the call to `this.setState()`. We replace the old array of comments with the new one from the server and the UI automatically updates itself. Because of this reactivity, it is only a minor change to add live updates. We will use simple polling here but you could easily use WebSockets or other technologies.
423 -
424 -```javascript{3,15,20-21,35}
425 -// tutorial14.js
426 -var CommentBox = React.createClass({
427 - loadCommentsFromServer: function() {
428 - $.ajax({
429 - url: this.props.url,
430 - dataType: 'json',
431 - cache: false,
432 - success: function(data) {
433 - this.setState({data: data});
434 - }.bind(this),
435 - error: function(xhr, status, err) {
436 - console.error(this.props.url, status, err.toString());
437 - }.bind(this)
438 - });
439 - },
440 - getInitialState: function() {
441 - return {data: []};
442 - },
443 - componentDidMount: function() {
444 - this.loadCommentsFromServer();
445 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
446 - },
447 - render: function() {
448 - return (
449 - <div className="commentBox">
450 - <h1>Comments</h1>
451 - <CommentList data={this.state.data} />
452 - <CommentForm />
453 - </div>
454 - );
455 - }
456 -});
457 -
458 -ReactDOM.render(
459 - <CommentBox url="/api/comments" pollInterval={2000} />,
460 - document.getElementById('content')
461 -);
462 -
463 -```
464 -
465 -All we have done here is move the AJAX call to a separate method and call it when the component is first loaded and every 2 seconds after that. Try running this in your browser and changing the `comments.json` file (in the same directory as your server); within 2 seconds, the changes will show!
466 -
467 -### Adding new comments
468 -
469 -Now it's time to build the form. Our `CommentForm` component should ask the user for their name and comment text and send a request to the server to save the comment.
470 -
471 -```javascript{5-9}
472 -// tutorial15.js
473 -var CommentForm = React.createClass({
474 - render: function() {
475 - return (
476 - <form className="commentForm">
477 - <input type="text" placeholder="Your name" />
478 - <input type="text" placeholder="Say something..." />
479 - <input type="submit" value="Post" />
480 - </form>
481 - );
482 - }
483 -});
484 -```
485 -
486 -#### Controlled components
487 -
488 -With the traditional DOM, `input` elements are rendered and the browser manages the state (its rendered value). As a result, the state of the actual DOM will differ from that of the component. This is not ideal as the state of the view will differ from that of the component. In React, components should always represent the state of the view and not only at the point of initialization.
489 -
490 -Hence, we will be using `this.state` to save the user's input as it is entered. We define an initial `state` with two properties `author` and `text` and set them to be empty strings. In our `<input>` elements, we set the `value` prop to reflect the `state` of the component and attach `onChange` handlers to them. These `<input>` elements with a `value` set are called controlled components. Read more about controlled components on the [Forms article](/react/docs/forms.html#controlled-components).
491 -
492 -```javascript{3-11,15-26}
493 -// tutorial16.js
494 -var CommentForm = React.createClass({
495 - getInitialState: function() {
496 - return {author: '', text: ''};
497 - },
498 - handleAuthorChange: function(e) {
499 - this.setState({author: e.target.value});
500 - },
501 - handleTextChange: function(e) {
502 - this.setState({text: e.target.value});
503 - },
504 - render: function() {
505 - return (
506 - <form className="commentForm">
507 - <input
508 - type="text"
509 - placeholder="Your name"
510 - value={this.state.author}
511 - onChange={this.handleAuthorChange}
512 - />
513 - <input
514 - type="text"
515 - placeholder="Say something..."
516 - value={this.state.text}
517 - onChange={this.handleTextChange}
518 - />
519 - <input type="submit" value="Post" />
520 - </form>
521 - );
522 - }
523 -});
524 -```
525 -
526 -#### Events
527 -
528 -React attaches event handlers to components using a camelCase naming convention. We attach `onChange` handlers to the two `<input>` elements. Now, as the user enters text into the `<input>` fields, the attached `onChange` callbacks are fired and the `state` of the component is modified. Subsequently, the rendered value of the `input` element will be updated to reflect the current component `state`.
529 -
530 -(The astute reader may be surprised that these event handlers work as described, given that the method references are not explicitly bound to `this`. `React.createClass(...)` [automatically binds](/react/docs/interactivity-and-dynamic-uis.html#under-the-hood-autobinding-and-event-delegation) each method to its component instance, obviating the need for explicit binding.)
531 -
532 -#### Submitting the form
533 -
534 -Let's make the form interactive. When the user submits the form, we should clear it, submit a request to the server, and refresh the list of comments. To start, let's listen for the form's submit event and clear it.
535 -
536 -```javascript{12-21,24}
537 -// tutorial17.js
538 -var CommentForm = React.createClass({
539 - getInitialState: function() {
540 - return {author: '', text: ''};
541 - },
542 - handleAuthorChange: function(e) {
543 - this.setState({author: e.target.value});
544 - },
545 - handleTextChange: function(e) {
546 - this.setState({text: e.target.value});
547 - },
548 - handleSubmit: function(e) {
549 - e.preventDefault();
550 - var author = this.state.author.trim();
551 - var text = this.state.text.trim();
552 - if (!text || !author) {
553 - return;
554 - }
555 - // TODO: send request to the server
556 - this.setState({author: '', text: ''});
557 - },
558 - render: function() {
559 - return (
560 - <form className="commentForm" onSubmit={this.handleSubmit}>
561 - <input
562 - type="text"
563 - placeholder="Your name"
564 - value={this.state.author}
565 - onChange={this.handleAuthorChange}
566 - />
567 - <input
568 - type="text"
569 - placeholder="Say something..."
570 - value={this.state.text}
571 - onChange={this.handleTextChange}
572 - />
573 - <input type="submit" value="Post" />
574 - </form>
575 - );
576 - }
577 -});
578 -```
579 -
580 -We attach an `onSubmit` handler to the form that clears the form fields when the form is submitted with valid input.
581 -
582 -Call `preventDefault()` on the event to prevent the browser's default action of submitting the form.
583 -
584 -#### Callbacks as props
585 -
586 -When a user submits a comment, we will need to refresh the list of comments to include the new one. It makes sense to do all of this logic in `CommentBox` since `CommentBox` owns the state that represents the list of comments.
587 -
588 -We need to pass data from the child component back up to its parent. We do this in our parent's `render` method by passing a new callback (`handleCommentSubmit`) into the child, binding it to the child's `onCommentSubmit` event. Whenever the event is triggered, the callback will be invoked:
589 -
590 -```javascript{16-18,31}
591 -// tutorial18.js
592 -var CommentBox = React.createClass({
593 - loadCommentsFromServer: function() {
594 - $.ajax({
595 - url: this.props.url,
596 - dataType: 'json',
597 - cache: false,
598 - success: function(data) {
599 - this.setState({data: data});
600 - }.bind(this),
601 - error: function(xhr, status, err) {
602 - console.error(this.props.url, status, err.toString());
603 - }.bind(this)
604 - });
605 - },
606 - handleCommentSubmit: function(comment) {
607 - // TODO: submit to the server and refresh the list
608 - },
609 - getInitialState: function() {
610 - return {data: []};
611 - },
612 - componentDidMount: function() {
613 - this.loadCommentsFromServer();
614 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
615 - },
616 - render: function() {
617 - return (
618 - <div className="commentBox">
619 - <h1>Comments</h1>
620 - <CommentList data={this.state.data} />
621 - <CommentForm onCommentSubmit={this.handleCommentSubmit} />
622 - </div>
623 - );
624 - }
625 -});
626 -```
627 -
628 -Now that `CommentBox` has made the callback available to `CommentForm` via the `onCommentSubmit` prop, the `CommentForm` can call the callback when the user submits the form:
629 -
630 -```javascript{19}
631 -// tutorial19.js
632 -var CommentForm = React.createClass({
633 - getInitialState: function() {
634 - return {author: '', text: ''};
635 - },
636 - handleAuthorChange: function(e) {
637 - this.setState({author: e.target.value});
638 - },
639 - handleTextChange: function(e) {
640 - this.setState({text: e.target.value});
641 - },
642 - handleSubmit: function(e) {
643 - e.preventDefault();
644 - var author = this.state.author.trim();
645 - var text = this.state.text.trim();
646 - if (!text || !author) {
647 - return;
648 - }
649 - this.props.onCommentSubmit({author: author, text: text});
650 - this.setState({author: '', text: ''});
651 - },
652 - render: function() {
653 - return (
654 - <form className="commentForm" onSubmit={this.handleSubmit}>
655 - <input
656 - type="text"
657 - placeholder="Your name"
658 - value={this.state.author}
659 - onChange={this.handleAuthorChange}
660 - />
661 - <input
662 - type="text"
663 - placeholder="Say something..."
664 - value={this.state.text}
665 - onChange={this.handleTextChange}
666 - />
667 - <input type="submit" value="Post" />
668 - </form>
669 - );
670 - }
671 -});
672 -```
673 -
674 -Now that the callbacks are in place, all we have to do is submit to the server and refresh the list:
675 -
676 -```javascript{17-28}
677 -// tutorial20.js
678 -var CommentBox = React.createClass({
679 - loadCommentsFromServer: function() {
680 - $.ajax({
681 - url: this.props.url,
682 - dataType: 'json',
683 - cache: false,
684 - success: function(data) {
685 - this.setState({data: data});
686 - }.bind(this),
687 - error: function(xhr, status, err) {
688 - console.error(this.props.url, status, err.toString());
689 - }.bind(this)
690 - });
691 - },
692 - handleCommentSubmit: function(comment) {
693 - $.ajax({
694 - url: this.props.url,
695 - dataType: 'json',
696 - type: 'POST',
697 - data: comment,
698 - success: function(data) {
699 - this.setState({data: data});
700 - }.bind(this),
701 - error: function(xhr, status, err) {
702 - console.error(this.props.url, status, err.toString());
703 - }.bind(this)
704 - });
705 - },
706 - getInitialState: function() {
707 - return {data: []};
708 - },
709 - componentDidMount: function() {
710 - this.loadCommentsFromServer();
711 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
712 - },
713 - render: function() {
714 - return (
715 - <div className="commentBox">
716 - <h1>Comments</h1>
717 - <CommentList data={this.state.data} />
718 - <CommentForm onCommentSubmit={this.handleCommentSubmit} />
719 - </div>
720 - );
721 - }
722 -});
723 -```
724 -
725 -### Optimization: optimistic updates
726 -
727 -Our application is now feature complete but it feels slow to have to wait for the request to complete before your comment appears in the list. We can optimistically add this comment to the list to make the app feel faster.
728 -
729 -```javascript{17-23,33}
730 -// tutorial21.js
731 -var CommentBox = React.createClass({
732 - loadCommentsFromServer: function() {
733 - $.ajax({
734 - url: this.props.url,
735 - dataType: 'json',
736 - cache: false,
737 - success: function(data) {
738 - this.setState({data: data});
739 - }.bind(this),
740 - error: function(xhr, status, err) {
741 - console.error(this.props.url, status, err.toString());
742 - }.bind(this)
743 - });
744 - },
745 - handleCommentSubmit: function(comment) {
746 - var comments = this.state.data;
747 - // Optimistically set an id on the new comment. It will be replaced by an
748 - // id generated by the server. In a production application you would likely
749 - // not use Date.now() for this and would have a more robust system in place.
750 - comment.id = Date.now();
751 - var newComments = comments.concat([comment]);
752 - this.setState({data: newComments});
753 - $.ajax({
754 - url: this.props.url,
755 - dataType: 'json',
756 - type: 'POST',
757 - data: comment,
758 - success: function(data) {
759 - this.setState({data: data});
760 - }.bind(this),
761 - error: function(xhr, status, err) {
762 - this.setState({data: comments});
763 - console.error(this.props.url, status, err.toString());
764 - }.bind(this)
765 - });
766 - },
767 - getInitialState: function() {
768 - return {data: []};
769 - },
770 - componentDidMount: function() {
771 - this.loadCommentsFromServer();
772 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
773 - },
774 - render: function() {
775 - return (
776 - <div className="commentBox">
777 - <h1>Comments</h1>
778 - <CommentList data={this.state.data} />
779 - <CommentForm onCommentSubmit={this.handleCommentSubmit} />
780 - </div>
781 - );
782 - }
783 -});
784 -```
785 -
786 -### Congrats!
787 -
788 -You have just built a comment box in a few simple steps. Learn more about [why to use React](/react/docs/why-react.html), or dive into the [API reference](/react/docs/top-level-api.html) and start hacking! Good luck!
docs/docs/tutorial.zh-CN.md deleted
-786
@@ -1,786 +0,0 @@
1 ----
2 -id: tutorial-zh-CN
3 -title: 教程
4 -permalink: docs/tutorial-zh-CN.html
5 -prev: getting-started-zh-CN.html
6 -next: thinking-in-react-zh-CN.html
7 ----
8 -
9 -我们将建立一个你可以放进博客的简单却真实的评论框,一个 Disqus、LiveFyre 或 Facebook comments 提供的实时评论的基础版本。
10 -
11 -我们将提供:
12 -
13 -* 一个所有评论的视图
14 -* 一个用于提交评论的表单
15 -* 为你提供制定后台的挂钩(Hooks)
16 -
17 -同时也会有一些简洁的功能:
18 -
19 -* **优化的评论:** 评论在它们保存到服务器之前就显示在列表里,所以感觉很快。
20 -* **实时更新:** 其他用户的评论被实时浮现到评论中。
21 -* **Markdown格式化:** 用户可以用Markdown格式化它们的文字。
22 -
23 -### 想要跳过所有内容,只查看源代码?
24 -
25 -[全在 GitHub .](https://github.com/reactjs/react-tutorial)
26 -
27 -### 运行服务器
28 -
29 -为了开始本教程,我们将要需要一个运行着的服务器。这将是我们纯粹用来获取和保存数据的伺服终端。为了让这尽可能的容易,我们已经用许多不同的语言编写了简单的服务器,它正好完成我们需要的事。 **你可以[查看源代码](https://github.com/reactjs/react-tutorial/) 或者 [下载 zip 文件](https://github.com/reactjs/react-tutorial/archive/master.zip) 包括了所有你开始学习需要的东西**
30 -
31 -为了简单起见,我们将要运行的服务器使用 `JSON` 文件作为数据库。你不会在生产环境运行这个,但是它让我们更容易模拟使用一个API时你可能会做的事。一旦你启动服务器,它将会支持我们的API终端,同时也将伺服我们需要的静态页面。
32 -
33 -### 开始
34 -
35 -对于此教程,我们将使它尽可能的容易。被包括在上面讨论的服务器包里的是一个我们将在其中工作的 HTML 文件。在你最喜欢的编辑器里打开 `public/index.html`。它应该看起来像这样 (可能有一些小的不同,稍后我们将添加一个额外的 `<script>` 标签):
36 -
37 -```html
38 -<!-- index.html -->
39 -<!DOCTYPE html>
40 -<html>
41 - <head>
42 - <meta charset="utf-8" />
43 - <title>React Tutorial</title>
44 - <script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script>
45 - <script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
46 - <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
47 - <script src="https://unpkg.com/jquery@3.1.0/dist/jquery.min.js"></script>
48 - <script src="https://unpkg.com/remarkable@1.7.1/dist/remarkable.min.js"></script>
49 - </head>
50 - <body>
51 - <div id="content"></div>
52 - <script type="text/babel" src="scripts/example.js"></script>
53 - <script type="text/babel">
54 - // To get started with this tutorial running your own code, simply remove
55 - // the script tag loading scripts/example.js and start writing code here.
56 - </script>
57 - </body>
58 -</html>
59 -```
60 -
61 -在本教程剩余的部分,我们将在此 script 标签中编写我们的 JavaScript 代码。我们没有任何高级的实时加载所以在保存以后你需要刷新你的浏览器来观察更新。通过在浏览器打开 `http://localhost:3000` 关注你的进展。当你没有任何修改第一次加载时,你将看到我们将要准备建立的已经完成的产品。当你准备开始工作,请删除前面的 `<script>` 标签然后你就可以继续了。
62 -
63 -> 注意:
64 ->
65 -> 我们在这里引入 jQuery 是因为我们想简化我们未来的 ajax 请求,但这对React的正常工作 **不是** 必要的。
66 -
67 -### 你的第一个组件
68 -
69 -React 中都是关于模块化、可组装的组件。以我们的评论框为例,我们将有如下的组件结构:
70 -
71 -```
72 -- CommentBox
73 - - CommentList
74 - - Comment
75 - - CommentForm
76 -```
77 -
78 -让我们构造 `CommentBox` 组件,仅是一个简单的 `<div>` :
79 -
80 -```javascript
81 -// tutorial1.js
82 -var CommentBox = React.createClass({
83 - render: function() {
84 - return (
85 - <div className="commentBox">
86 - Hello, world! I am a CommentBox.
87 - </div>
88 - );
89 - }
90 -});
91 -ReactDOM.render(
92 - <CommentBox />,
93 - document.getElementById('content')
94 -);
95 -```
96 -
97 -注意原生的HTML元素以小写开头,而制定的 React 类以大写开头。
98 -
99 -#### JSX 语法
100 -
101 -首先你会注意到你的 JavaScript 中 XML 式的语法。我们有一个简单的预编译器,将语法糖转换成这种纯的JavaScript:
102 -
103 -```javascript
104 -// tutorial1-raw.js
105 -var CommentBox = React.createClass({displayName: 'CommentBox',
106 - render: function() {
107 - return (
108 - React.createElement('div', {className: "commentBox"},
109 - "Hello, world! I am a CommentBox."
110 - )
111 - );
112 - }
113 -});
114 -ReactDOM.render(
115 - React.createElement(CommentBox, null),
116 - document.getElementById('content')
117 -);
118 -```
119 -
120 -它的使用是可选的,但是我们发现 JSX 语法比单纯的 JavaScript 更加容易使用。阅读更多关于[JSX 语法的文章](/react/docs/jsx-in-depth-zh-CN.html)。
121 -
122 -#### What's going on
123 -
124 -我们在一个 JavaScript 对象中传递一些方法到 `React.createClass()` 来创建一个新的React组件。这些方法中最重要的是 `render`,该方法返回一颗 React 组件树,这棵树最终将会渲染成 HTML。
125 -
126 -这个 `<div>` 标签不是真实的DOM节点;他们是 React `div` 组件的实例化。你可以把这些看做是React知道如何处理的标记或者是一些数据 。React 是**安全的**。我们不生成 HTML 字符串,因此XSS防护是默认特性。
127 -
128 -你没有必要返回基本的 HTML。你可以返回一个你(或者其他人)创建的组件树。这就使 React **组件化**:一个可维护前端的关键原则。
129 -
130 -`ReactDOM.render()` 实例化根组件,启动框架,注入标记到原始的 DOM 元素中,作为第二个参数提供。
131 -
132 -`ReactDOM` 模块暴露了 DOM 相关的方法, 而 `React` 保有被不同平台的 React 共享的核心工具 (例如 [React Native](http://facebook.github.io/react-native/))。
133 -
134 -对于本教程 `ReactDOM.render` 保持在脚本底部是很重要的。`ReactDOM.render` 应该只在复合组件被定义之后被调用。
135 -
136 -## 组合组件
137 -
138 -让我们为 `CommentList` 和 `CommentForm` 建造骨架,它们将会,再一次的,是一些简单的 `<div>`。添加这两个组件到你的文件里,保持现存的 `CommentBox` 声明和 `ReactDOM.render` 调用:
139 -
140 -```javascript
141 -// tutorial2.js
142 -var CommentList = React.createClass({
143 - render: function() {
144 - return (
145 - <div className="commentList">
146 - Hello, world! I am a CommentList.
147 - </div>
148 - );
149 - }
150 -});
151 -
152 -var CommentForm = React.createClass({
153 - render: function() {
154 - return (
155 - <div className="commentForm">
156 - Hello, world! I am a CommentForm.
157 - </div>
158 - );
159 - }
160 -});
161 -```
162 -
163 -接着,更新 `CommentBox` 以使用这些新的组件:
164 -
165 -```javascript{6-8}
166 -// tutorial3.js
167 -var CommentBox = React.createClass({
168 - render: function() {
169 - return (
170 - <div className="commentBox">
171 - <h1>Comments</h1>
172 - <CommentList />
173 - <CommentForm />
174 - </div>
175 - );
176 - }
177 -});
178 -```
179 -
180 -注意我们是如何混合 HTML 标签和我们建立的组件。HTML 组件是正常的 React 组件,就和你定义的一样,只有一个区别。JSX 编译器会自动重写 HTML 标签为 `React.createElement(tagName)` 表达式,其它什么都不做。这是为了避免污染全局命名空间。
181 -
182 -### 使用 props
183 -
184 -让我们创建 `Comment` 组件,它将依赖于从父级传来的数据。从父级传来的数据在子组件里作为 '属性' 可供使用。 这些 '属性' 可以通过 `this.props` 访问。使用属性,我们将能读取从 `CommentList` 传递给 `Comment` 的数据,并且渲染一些标记:
185 -
186 -```javascript
187 -// tutorial4.js
188 -var Comment = React.createClass({
189 - render: function() {
190 - return (
191 - <div className="comment">
192 - <h2 className="commentAuthor">
193 - {this.props.author}
194 - </h2>
195 - {this.props.children}
196 - </div>
197 - );
198 - }
199 -});
200 -```
201 -
202 -在 JSX 中,通过将 JavaScript 表达式放在大括号中(作为属性或者子节点),你可以把文本或者 React 组件放置到树中。我们以 `this.props` 的 keys 访问传递给组件的命名属性,以 `this.props.children` 访问任何嵌套的元素。
203 -
204 -### 组件的属性
205 -
206 -既然我们已经定义了 `Comment` 组件,我们将要传递作者名和评论文字给它。这允许我们为每个评论重用相同的代码。现在让我们在我们的 `CommentList` 里添加一些评论。
207 -
208 -```javascript{6-7}
209 -// tutorial5.js
210 -var CommentList = React.createClass({
211 - render: function() {
212 - return (
213 - <div className="commentList">
214 - <Comment author="Pete Hunt">This is one comment</Comment>
215 - <Comment author="Jordan Walke">This is *another* comment</Comment>
216 - </div>
217 - );
218 - }
219 -});
220 -```
221 -
222 -注意,我们已经从 `CommentList` 组件传递了一些数据到 `Comment` 组件。例如,我们传递了 *Pete Hunt* (通过属性)和 *This is one comment* (通过 XML-风格的子节点)给第一个 `Comment`。如上面提到的那样, `Comment` 组件将会通过 `this.props.author` 和 `this.props.children` 访问 这些 '属性'。
223 -
224 -### 添加 Markdown
225 -
226 -Markdown 是一种简单的内联格式化你的文字的方法。例如,用星号包围文本将会使其强调突出。
227 -
228 -在本教程中我们使用第三方库 **remarkable**,它接受 Markdown 文本并且转换为原始的 HTML。我们已经在初始的页面标记里包含了这个库,所以我们可以直接开始使用它,让我们转换评论文本为 Markdown 并输出它:
229 -
230 -```javascript{4,10}
231 -// tutorial6.js
232 -var Comment = React.createClass({
233 - render: function() {
234 - var md = new Remarkable();
235 - return (
236 - <div className="comment">
237 - <h2 className="commentAuthor">
238 - {this.props.author}
239 - </h2>
240 - {md.render(this.props.children.toString())}
241 - </div>
242 - );
243 - }
244 -});
245 -```
246 -
247 -我们在这里唯一做的就是调用 remarkable 库。我们需要把 从 React 的包裹文本来的 `this.props.children` 转换成 remarkable 能理解的原始字符串,所以我们显示地调用了`toString()`。
248 -
249 -但是这里有一个问题!我们渲染的评论在浏览器里看起来像这样: "`<p>`This is `<em>`another`</em>` comment`</p>`" 。我们想让这些标签真正地渲染为 HTML。
250 -
251 -那是 React 在保护你免受 [XSS 攻击](https://en.wikipedia.org/wiki/Cross-site_scripting)。有一个方法解决这个问题,但是框架会警告你别使用这种方法:
252 -
253 -```javascript{3-7,15}
254 -// tutorial7.js
255 -var Comment = React.createClass({
256 - rawMarkup: function() {
257 - var md = new Remarkable();
258 - var rawMarkup = md.render(this.props.children.toString());
259 - return { __html: rawMarkup };
260 - },
261 -
262 - render: function() {
263 - return (
264 - <div className="comment">
265 - <h2 className="commentAuthor">
266 - {this.props.author}
267 - </h2>
268 - <span dangerouslySetInnerHTML={this.rawMarkup()} />
269 - </div>
270 - );
271 - }
272 -});
273 -```
274 -
275 -这是一个特殊的 API,故意让插入原始的 HTML 变得困难,但是对于 remarkable 我们将利用这个后门。
276 -
277 -**记住:** 使用这个功能你会依赖于 remarkable 是安全的。
278 -
279 -### 挂钩数据模型
280 -
281 -到目前为止我们已经完成了在源码里直接插入评论。作为替代,让我们渲染一团 JSON 数据到评论列表里。最终数据将会来自服务器,但是现在,写在你的源代码中:
282 -
283 -```javascript
284 -// tutorial8.js
285 -var data = [
286 - {id: 1, author: "Pete Hunt", text: "This is one comment"},
287 - {id: 2, author: "Jordan Walke", text: "This is *another* comment"}
288 -];
289 -```
290 -
291 -我们需要以一种模块化的方式将这个数据传入到 `CommentList`。修改 `CommentBox` 和 `ReactDOM.render()` 方法,以便于通过 props 传入数据到 `CommentList`:
292 -
293 -```javascript{7,15}
294 -// tutorial9.js
295 -var CommentBox = React.createClass({
296 - render: function() {
297 - return (
298 - <div className="commentBox">
299 - <h1>Comments</h1>
300 - <CommentList data={this.props.data} />
301 - <CommentForm />
302 - </div>
303 - );
304 - }
305 -});
306 -
307 -ReactDOM.render(
308 - <CommentBox data={data} />,
309 - document.getElementById('content')
310 -);
311 -```
312 -
313 -既然现在数据在 `CommentList` 中可用了,让我们动态地渲染评论:
314 -
315 -```javascript{4-10,13}
316 -// tutorial10.js
317 -var CommentList = React.createClass({
318 - render: function() {
319 - var commentNodes = this.props.data.map(function(comment) {
320 - return (
321 - <Comment author={comment.author} key={comment.id}>
322 - {comment.text}
323 - </Comment>
324 - );
325 - });
326 - return (
327 - <div className="commentList">
328 - {commentNodes}
329 - </div>
330 - );
331 - }
332 -});
333 -```
334 -
335 -就是这样!
336 -
337 -### 从服务器获取数据
338 -
339 -让我们用一些来自服务器的动态数据替换硬编码的数据。我们将移除数据的prop,用获取数据的URL来替换它:
340 -
341 -```javascript{3}
342 -// tutorial11.js
343 -ReactDOM.render(
344 - <CommentBox url="/api/comments" />,
345 - document.getElementById('content')
346 -);
347 -```
348 -
349 -这个组件不同于和前面的组件,因为它必须重新渲染自己。该组件将不会有任何数据,直到请求从服务器返回,此时该组件或许需要渲染一些新的评论。
350 -
351 -注意: 此代码在这个阶段不会工作。
352 -
353 -### Reactive state
354 -
355 -迄今为止,基于它自己的props,每个组件都渲染了自己一次。`props` 是不可变的:它们从父级传来并被父级“拥有”。为了实现交互,我们给组件引进了可变的 **state**。`this.state` 是组件私有的,可以通过调用 `this.setState()` 改变它。每当state更新,组件就重新渲染自己。
356 -
357 -`render()` 方法被声明为一个带有 `this.props` 和 `this.state` 的函数。框架保证了 UI 总是与输入一致。
358 -
359 -当服务器获取数据时,我们将会改变我们已有的评论数据。让我们给 `CommentBox` 组件添加一组评论数据作为它的状态:
360 -
361 -```javascript{3-5,10}
362 -// tutorial12.js
363 -var CommentBox = React.createClass({
364 - getInitialState: function() {
365 - return {data: []};
366 - },
367 - render: function() {
368 - return (
369 - <div className="commentBox">
370 - <h1>Comments</h1>
371 - <CommentList data={this.state.data} />
372 - <CommentForm />
373 - </div>
374 - );
375 - }
376 -});
377 -```
378 -
379 -`getInitialState()` 在生命周期里只执行一次,并设置组件的初始状态。
380 -
381 -#### 更新状态
382 -当组件第一次创建时,我们想从服务器获取一些 JSON 并且更新状态以反映最新的数据。我们将用 jQuery 来发送一个异步请求到我们刚才启动的服务器以获取我们需要的数据。这些数据已经被包含在了你已启动的服务器里(基于`comments.json`文件),所以一旦被获取,`this.state.data` 会看起来像这样:
383 -
384 -```json
385 -[
386 - {"author": "Pete Hunt", "text": "This is one comment"},
387 - {"author": "Jordan Walke", "text": "This is *another* comment"}
388 -]
389 -```
390 -
391 -```javascript{6-18}
392 -// tutorial13.js
393 -var CommentBox = React.createClass({
394 - getInitialState: function() {
395 - return {data: []};
396 - },
397 - componentDidMount: function() {
398 - $.ajax({
399 - url: this.props.url,
400 - dataType: 'json',
401 - cache: false,
402 - success: function(data) {
403 - this.setState({data: data});
404 - }.bind(this),
405 - error: function(xhr, status, err) {
406 - console.error(this.props.url, status, err.toString());
407 - }.bind(this)
408 - });
409 - },
410 - render: function() {
411 - return (
412 - <div className="commentBox">
413 - <h1>Comments</h1>
414 - <CommentList data={this.state.data} />
415 - <CommentForm />
416 - </div>
417 - );
418 - }
419 -});
420 -```
421 -
422 -这里, `componentDidMount` 是一个当组件被渲染时被React自动调用的方法。动态更新的关键是对 `this.setState()` 的调用。我们用新的从服务器来的替换掉旧的评论组,然后UI自动更新自己。因为这种反应性,仅是一个微小的变化就添加了实时更新。我们这里将用简单的轮询,但是你可以容易的使用 WebSockets 或者其他技术。
423 -
424 -```javascript{3,15,20-21,35}
425 -// tutorial14.js
426 -var CommentBox = React.createClass({
427 - loadCommentsFromServer: function() {
428 - $.ajax({
429 - url: this.props.url,
430 - dataType: 'json',
431 - cache: false,
432 - success: function(data) {
433 - this.setState({data: data});
434 - }.bind(this),
435 - error: function(xhr, status, err) {
436 - console.error(this.props.url, status, err.toString());
437 - }.bind(this)
438 - });
439 - },
440 - getInitialState: function() {
441 - return {data: []};
442 - },
443 - componentDidMount: function() {
444 - this.loadCommentsFromServer();
445 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
446 - },
447 - render: function() {
448 - return (
449 - <div className="commentBox">
450 - <h1>Comments</h1>
451 - <CommentList data={this.state.data} />
452 - <CommentForm />
453 - </div>
454 - );
455 - }
456 -});
457 -
458 -ReactDOM.render(
459 - <CommentBox url="/api/comments" pollInterval={2000} />,
460 - document.getElementById('content')
461 -);
462 -
463 -```
464 -
465 -我们在这里做的全部事情是把 AJAX 调用移动到独立的方法里,然后在组件第一次加载时及其后每2秒 调用它。试着在你的浏览器里运行它并且改变 `comments.json` 文件(在你的服务器的相同目录);2秒内,变化将会显现!
466 -
467 -### 添加新评论
468 -
469 -现在是时候建立表单了,我们的 `CommentForm` 组件应该询问用户他们的名字和评论文本然后发送一个请求到服务器来保存评论.
470 -
471 -```javascript{5-9}
472 -// tutorial15.js
473 -var CommentForm = React.createClass({
474 - render: function() {
475 - return (
476 - <form className="commentForm">
477 - <input type="text" placeholder="Your name" />
478 - <input type="text" placeholder="Say something..." />
479 - <input type="submit" value="Post" />
480 - </form>
481 - );
482 - }
483 -});
484 -```
485 -
486 -#### 受控组件
487 -
488 -对于传统的 DOM, `input` 元素被渲染并且浏览器管理它的状态(它的渲染值)。结果是,DOM的实际值会和组件不同。这是不理想的,因为视图的值会和组件的值不同。在React中,组件应该总是表示视图的值而不只是在初始化时。
489 -
490 -因此,我们将使用 `this.state` 来在用户输入时保存输入。我们定义一个初始 `state`,它带有 `author` 和 `text` 两个属性并将他们设置为空字符串。在我们的 `<input>` 元素里,我们设置 `value` prop 来反映组件的 `state` 并给他们附加 `onChange` 事件处理。这些带有设置了 `value` 的 `<input>` 元素被称为受控组件。更多关于受控组件请阅读 [Forms article](/react/docs/forms.html#controlled-components)。
491 -
492 -```javascript{3-11,15-26}
493 -// tutorial16.js
494 -var CommentForm = React.createClass({
495 - getInitialState: function() {
496 - return {author: '', text: ''};
497 - },
498 - handleAuthorChange: function(e) {
499 - this.setState({author: e.target.value});
500 - },
501 - handleTextChange: function(e) {
502 - this.setState({text: e.target.value});
503 - },
504 - render: function() {
505 - return (
506 - <form className="commentForm">
507 - <input
508 - type="text"
509 - placeholder="Your name"
510 - value={this.state.author}
511 - onChange={this.handleAuthorChange}
512 - />
513 - <input
514 - type="text"
515 - placeholder="Say something..."
516 - value={this.state.text}
517 - onChange={this.handleTextChange}
518 - />
519 - <input type="submit" value="Post" />
520 - </form>
521 - );
522 - }
523 -});
524 -```
525 -
526 -##### 事件
527 -
528 -React使用小驼峰命名规范(camelCase)给组件绑定事件处理器。我们附加 `onChange` 给两个 `<input>` 元素。现在,当用户输入文本到 `<input>` 中,被附加的 `onChange` 回调函数被激发并且组件的 `state` 被修改。然后,被渲染的 `input` 元素的值将会更新以反映当前组件的 `state`。
529 -
530 -#### 提交表单
531 -
532 -让我们使表单具有交互性。当用户提交表单时,我们应该清除它,提交一个请求到服务器,并刷新评论列表。让我们监听表单的提交事件并清除它。
533 -
534 -```javascript{12-21,24}
535 -// tutorial17.js
536 -var CommentForm = React.createClass({
537 - getInitialState: function() {
538 - return {author: '', text: ''};
539 - },
540 - handleAuthorChange: function(e) {
541 - this.setState({author: e.target.value});
542 - },
543 - handleTextChange: function(e) {
544 - this.setState({text: e.target.value});
545 - },
546 - handleSubmit: function(e) {
547 - e.preventDefault();
548 - var author = this.state.author.trim();
549 - var text = this.state.text.trim();
550 - if (!text || !author) {
551 - return;
552 - }
553 - // TODO: send request to the server
554 - this.setState({author: '', text: ''});
555 - },
556 - render: function() {
557 - return (
558 - <form className="commentForm" onSubmit={this.handleSubmit}>
559 - <input
560 - type="text"
561 - placeholder="Your name"
562 - value={this.state.author}
563 - onChange={this.handleAuthorChange}
564 - />
565 - <input
566 - type="text"
567 - placeholder="Say something..."
568 - value={this.state.text}
569 - onChange={this.handleTextChange}
570 - />
571 - <input type="submit" value="Post" />
572 - </form>
573 - );
574 - }
575 -});
576 -```
577 -
578 -我们给表单绑定一个`onSubmit`处理器,它在表单提交了合法的输入后清空表单字段。
579 -
580 -在事件中调用`preventDefault()`来阻止浏览器提交表单的默认行为。
581 -
582 -##### 回调函数作为属性
583 -
584 -当用户提交评论时,我们需要刷新评论列表来包含这条新评论。在`CommentBox`中完成所有逻辑是有道理的,因为`CommentBox` 拥有代表了评论列表的状态(state)。
585 -
586 -我们需要从子组件传回数据到它的父组件。我们在父组件的`render`方法中以传递一个新的回调函数(`handleCommentSubmit`)到子组件完成这件事,绑定它到子组件的 `onCommentSubmit` 事件上。无论事件什么时候触发,回调函数都将被调用:
587 -
588 -```javascript{16-18,31}
589 -// tutorial18.js
590 -var CommentBox = React.createClass({
591 - loadCommentsFromServer: function() {
592 - $.ajax({
593 - url: this.props.url,
594 - dataType: 'json',
595 - cache: false,
596 - success: function(data) {
597 - this.setState({data: data});
598 - }.bind(this),
599 - error: function(xhr, status, err) {
600 - console.error(this.props.url, status, err.toString());
601 - }.bind(this)
602 - });
603 - },
604 - handleCommentSubmit: function(comment) {
605 - // TODO: submit to the server and refresh the list
606 - },
607 - getInitialState: function() {
608 - return {data: []};
609 - },
610 - componentDidMount: function() {
611 - this.loadCommentsFromServer();
612 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
613 - },
614 - render: function() {
615 - return (
616 - <div className="commentBox">
617 - <h1>Comments</h1>
618 - <CommentList data={this.state.data} />
619 - <CommentForm onCommentSubmit={this.handleCommentSubmit} />
620 - </div>
621 - );
622 - }
623 -});
624 -```
625 -
626 -既然 `CommentBox` 已经通过 `onCommentSubmit` prop 使回调函数对于 `CommentForm` 可用,`CommentForm` 就可以在用户提交表单时调用回调函数:
627 -
628 -```javascript{19}
629 -// tutorial19.js
630 -var CommentForm = React.createClass({
631 - getInitialState: function() {
632 - return {author: '', text: ''};
633 - },
634 - handleAuthorChange: function(e) {
635 - this.setState({author: e.target.value});
636 - },
637 - handleTextChange: function(e) {
638 - this.setState({text: e.target.value});
639 - },
640 - handleSubmit: function(e) {
641 - e.preventDefault();
642 - var author = this.state.author.trim();
643 - var text = this.state.text.trim();
644 - if (!text || !author) {
645 - return;
646 - }
647 - this.props.onCommentSubmit({author: author, text: text});
648 - this.setState({author: '', text: ''});
649 - },
650 - render: function() {
651 - return (
652 - <form className="commentForm" onSubmit={this.handleSubmit}>
653 - <input
654 - type="text"
655 - placeholder="Your name"
656 - value={this.state.author}
657 - onChange={this.handleAuthorChange}
658 - />
659 - <input
660 - type="text"
661 - placeholder="Say something..."
662 - value={this.state.text}
663 - onChange={this.handleTextChange}
664 - />
665 - <input type="submit" value="Post" />
666 - </form>
667 - );
668 - }
669 -});
670 -```
671 -
672 -既然现在回调函数已经就绪,我们所需要做的就是提交到服务器然后刷新列表:
673 -
674 -```javascript{17-28}
675 -// tutorial20.js
676 -var CommentBox = React.createClass({
677 - loadCommentsFromServer: function() {
678 - $.ajax({
679 - url: this.props.url,
680 - dataType: 'json',
681 - cache: false,
682 - success: function(data) {
683 - this.setState({data: data});
684 - }.bind(this),
685 - error: function(xhr, status, err) {
686 - console.error(this.props.url, status, err.toString());
687 - }.bind(this)
688 - });
689 - },
690 - handleCommentSubmit: function(comment) {
691 - $.ajax({
692 - url: this.props.url,
693 - dataType: 'json',
694 - type: 'POST',
695 - data: comment,
696 - success: function(data) {
697 - this.setState({data: data});
698 - }.bind(this),
699 - error: function(xhr, status, err) {
700 - console.error(this.props.url, status, err.toString());
701 - }.bind(this)
702 - });
703 - },
704 - getInitialState: function() {
705 - return {data: []};
706 - },
707 - componentDidMount: function() {
708 - this.loadCommentsFromServer();
709 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
710 - },
711 - render: function() {
712 - return (
713 - <div className="commentBox">
714 - <h1>Comments</h1>
715 - <CommentList data={this.state.data} />
716 - <CommentForm onCommentSubmit={this.handleCommentSubmit} />
717 - </div>
718 - );
719 - }
720 -});
721 -```
722 -
723 -### 优化: 优化的更新
724 -
725 -我们的应用现在已经功能完备,但是它感觉很慢,因为在评论出现在列表前必须等待请求完成。我们可以优化添加这条评论到列表以使应用感觉更快。
726 -
727 -```javascript{17-23,33}
728 -// tutorial21.js
729 -var CommentBox = React.createClass({
730 - loadCommentsFromServer: function() {
731 - $.ajax({
732 - url: this.props.url,
733 - dataType: 'json',
734 - cache: false,
735 - success: function(data) {
736 - this.setState({data: data});
737 - }.bind(this),
738 - error: function(xhr, status, err) {
739 - console.error(this.props.url, status, err.toString());
740 - }.bind(this)
741 - });
742 - },
743 - handleCommentSubmit: function(comment) {
744 - var comments = this.state.data;
745 - // Optimistically set an id on the new comment. It will be replaced by an
746 - // id generated by the server. In a production application you would likely
747 - // not use Date.now() for this and would have a more robust system in place.
748 - comment.id = Date.now();
749 - var newComments = comments.concat([comment]);
750 - this.setState({data: newComments});
751 - $.ajax({
752 - url: this.props.url,
753 - dataType: 'json',
754 - type: 'POST',
755 - data: comment,
756 - success: function(data) {
757 - this.setState({data: data});
758 - }.bind(this),
759 - error: function(xhr, status, err) {
760 - this.setState({data: comments});
761 - console.error(this.props.url, status, err.toString());
762 - }.bind(this)
763 - });
764 - },
765 - getInitialState: function() {
766 - return {data: []};
767 - },
768 - componentDidMount: function() {
769 - this.loadCommentsFromServer();
770 - setInterval(this.loadCommentsFromServer, this.props.pollInterval);
771 - },
772 - render: function() {
773 - return (
774 - <div className="commentBox">
775 - <h1>Comments</h1>
776 - <CommentList data={this.state.data} />
777 - <CommentForm onCommentSubmit={this.handleCommentSubmit} />
778 - </div>
779 - );
780 - }
781 -});
782 -```
783 -
784 -### 祝贺!
785 -
786 -你刚刚通过几个简单的步骤建立了一个评论框。学习更多关于[为什么使用 React](/react/docs/why-react-zh-CN.html), 或者深入 [API 参考](/react/docs/top-level-api-zh-CN.html) 开始钻研!祝你好运!
docs/docs/typechecking-with-proptypes.md new
+157
@@ -0,0 +1,157 @@
1 +---
2 +id: typechecking-with-proptypes
3 +title: Typechecking With PropTypes
4 +permalink: docs/typechecking-with-proptypes.html
5 +---
6 +
7 +As your app grows, you can catch a lot of bugs with typechecking. For some applications, you can use JavaScript extensions like [Flow](https://flowtype.org/) or [TypeScript](https://www.typescriptlang.org/) to typecheck your whole application. But even if you don't use those, React has some built-in typechecking abilities. To run typechecking on the props for a component, you can assign the special `propTypes` property:
8 +
9 +```javascript
10 +class Greeting extends React.Component {
11 + render() {
12 + return (
13 + <h1>Hello, {this.props.name}</h1>
14 + );
15 + }
16 +}
17 +
18 +Greeting.propTypes = {
19 + name: React.PropTypes.string
20 +};
21 +```
22 +
23 +`React.PropTypes` exports a range of validators that can be used to make sure the data you receive is valid. In this example, we're using `React.PropTypes.string`. When an invalid value is provided for a prop, a warning will be shown in the JavaScript console. For performance reasons, `propTypes` is only checked in development mode.
24 +
25 +### React.PropTypes
26 +
27 +Here is an example documenting the different validators provided:
28 +
29 +```javascript
30 +MyComponent.propTypes = {
31 + // You can declare that a prop is a specific JS primitive. By default, these
32 + // are all optional.
33 + optionalArray: React.PropTypes.array,
34 + optionalBool: React.PropTypes.bool,
35 + optionalFunc: React.PropTypes.func,
36 + optionalNumber: React.PropTypes.number,
37 + optionalObject: React.PropTypes.object,
38 + optionalString: React.PropTypes.string,
39 + optionalSymbol: React.PropTypes.symbol,
40 +
41 + // Anything that can be rendered: numbers, strings, elements or an array
42 + // (or fragment) containing these types.
43 + optionalNode: React.PropTypes.node,
44 +
45 + // A React element.
46 + optionalElement: React.PropTypes.element,
47 +
48 + // You can also declare that a prop is an instance of a class. This uses
49 + // JS's instanceof operator.
50 + optionalMessage: React.PropTypes.instanceOf(Message),
51 +
52 + // You can ensure that your prop is limited to specific values by treating
53 + // it as an enum.
54 + optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),
55 +
56 + // An object that could be one of many types
57 + optionalUnion: React.PropTypes.oneOfType([
58 + React.PropTypes.string,
59 + React.PropTypes.number,
60 + React.PropTypes.instanceOf(Message)
61 + ]),
62 +
63 + // An array of a certain type
64 + optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
65 +
66 + // An object with property values of a certain type
67 + optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
68 +
69 + // An object taking on a particular shape
70 + optionalObjectWithShape: React.PropTypes.shape({
71 + color: React.PropTypes.string,
72 + fontSize: React.PropTypes.number
73 + }),
74 +
75 + // You can chain any of the above with `isRequired` to make sure a warning
76 + // is shown if the prop isn't provided.
77 + requiredFunc: React.PropTypes.func.isRequired,
78 +
79 + // A value of any data type
80 + requiredAny: React.PropTypes.any.isRequired,
81 +
82 + // You can also specify a custom validator. It should return an Error
83 + // object if the validation fails. Don't `console.warn` or throw, as this
84 + // won't work inside `oneOfType`.
85 + customProp: function(props, propName, componentName) {
86 + if (!/matchme/.test(props[propName])) {
87 + return new Error(
88 + 'Invalid prop `' + propName + '` supplied to' +
89 + ' `' + componentName + '`. Validation failed.'
90 + );
91 + }
92 + },
93 +
94 + // You can also supply a custom validator to `arrayOf` and `objectOf`.
95 + // It should return an Error object if the validation fails. The validator
96 + // will be called for each key in the array or object. The first two
97 + // arguments of the validator are the array or object itself, and the
98 + // current item's key.
99 + customArrayProp: React.PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
100 + if (!/matchme/.test(propValue[key])) {
101 + return new Error(
102 + 'Invalid prop `' + propFullName + '` supplied to' +
103 + ' `' + componentName + '`. Validation failed.'
104 + );
105 + }
106 + })
107 +};
108 +```
109 +
110 +### Requiring Single Children
111 +
112 +With `React.PropTypes.element` you can specify that only a single child can be passed to a component as children.
113 +
114 +```javascript
115 +class MyComponent extends React.Component {
116 + render() {
117 + // This must be exactly one element or it will warn.
118 + var children = this.props.children;
119 + return (
120 + <div>
121 + {children}
122 + </div>
123 + );
124 + }
125 +}
126 +
127 +MyComponent.propTypes = {
128 + children: React.PropTypes.element.isRequired
129 +};
130 +```
131 +
132 +### Default Prop Values
133 +
134 +You can define default values for your `props` by assigning to the special `defaultProps` property:
135 +
136 +```javascript
137 +class Greeting extends React.Component {
138 + render() {
139 + return (
140 + <h1>Hello, {this.props.name}</h1>
141 + );
142 + }
143 +}
144 +
145 +// Specifies the default values for props:
146 +Greeting.defaultProps = {
147 + name: 'Stranger'
148 +};
149 +
150 +// Renders "Hello, Stranger":
151 +ReactDOM.render(
152 + <Greeting />,
153 + document.getElementById('example')
154 +);
155 +```
156 +
157 +The `defaultProps` will be used to ensure that `this.props.name` will have a value if it was not specified by the parent component. The `propTypes` typechecking happens after `defaultProps` are resolved, so typechecking will also apply to the `defaultProps`.
docs/docs/videos.md deleted
-173
@@ -1,173 +0,0 @@
1 ----
2 -id: videos
3 -title: Videos
4 -permalink: docs/videos.html
5 -prev: conferences.html
6 -next: complementary-tools.html
7 ----
8 -
9 -### Rethinking best practices - JSConf.eu
10 -
11 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe>
12 -
13 -"At Facebook and Instagram, we’re trying to push the limits of what’s possible on the web with React. My talk will start with a brief introduction to the framework, and then dive into three controversial topics: Throwing out the notion of templates and building views with JavaScript, “re-rendering” your entire application when your data changes, and a lightweight implementation of the DOM and events." -- [Pete Hunt](http://www.petehunt.net/)
14 -
15 -* * *
16 -
17 -### Thinking in react - tagtree.tv
18 -
19 -A [tagtree.tv](http://tagtree.tv/) video conveying the principles of [Thinking in React](/react/docs/thinking-in-react.html) while building a simple app
20 -<figure>[![](/react/img/docs/thinking-in-react-tagtree.png)](http://tagtree.tv/thinking-in-react)</figure>
21 -
22 -* * *
23 -
24 -### Secrets of the Virtual DOM - MtnWest JS
25 -
26 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/h3KksH8gfcQ" frameborder="0" allowfullscreen></iframe>
27 -
28 -"In this talk I’ll be discussing why we built a virtual DOM, how it compares to other systems, and its relevance to the future of browser technologies." -- [Pete Hunt](http://www.petehunt.net/)
29 -
30 -* * *
31 -
32 -### Going big with React
33 -
34 -"On paper, all those JS frameworks look promising: clean implementations, quick code design, flawless execution. But what happens when you stress test Javascript? What happens when you throw 6 megabytes of code at it? In this talk, we'll investigate how React performs in a high stress situation, and how it has helped our team build safe code on a massive scale."
35 -<figure>[![](https://i.vimeocdn.com/video/481670116_650.jpg)](https://skillsmatter.com/skillscasts/5429-going-big-with-react#video)</figure>
36 -
37 -* * *
38 -
39 -### CodeWinds
40 -
41 -[Pete Hunt](http://www.petehunt.net/) talked with [Jeff Barczewski](http://jeff.barczewski.com/) about React in CodeWinds Episode 4.
42 -<figure>[![](/react/img/docs/codewinds-004.png)](http://codewinds.com/4)</figure>
43 -
44 -<table width="100%"><tr><td>
45 -02:08 - What is React and why use it?<br />
46 -03:08 - The symbiotic relationship of ClojureScript and React<br />
47 -04:54 - The history of React and why it was created<br />
48 -09:43 - Updating web page with React without using data binding<br />
49 -13:11 - Using the virtual DOM to change the browser DOM<br />
50 -13:57 - Programming with React, render targets HTML, canvas, other<br />
51 -16:45 - Working with designers. Contrasted with Ember and AngularJS<br />
52 -21:45 - JSX Compiler bridging HTML and React javascript<br />
53 -23:50 - Autobuilding JSX and in browser tools for React<br />
54 -24:50 - Tips and tricks to working with React, getting started<br />
55 -</td><td>
56 -27:17 - Rendering HTML on the server with Node.js. Rendering backends<br />
57 -29:20 - React evolved through survival of the fittest at Facebook<br />
58 -30:15 - Ideas for having state on server and client, using web sockets.<br />
59 -32:05 - React-multiuser - distributed shared mutable state using Firebase<br />
60 -33:03 - Better debugging with React using the state transitions, replaying events<br />
61 -34:08 - Differences from Web Components<br />
62 -34:25 - Notable companies using React<br />
63 -35:16 - Could a React backend plugin be created to target PDF?<br />
64 -36:30 - Future of React, what's next?<br />
65 -39:38 - Contributing and getting help<br />
66 -</td></tr></table>
67 -
68 -[Read the episode notes](http://codewinds.com/4)
69 -
70 -* * *
71 -
72 -### JavaScript Jabber
73 -
74 -[Pete Hunt](http://www.petehunt.net/) and [Jordan Walke](https://github.com/jordwalke) talked about React in JavaScript Jabber 73.
75 -<figure>[![](/react/img/docs/javascript-jabber.png)](http://javascriptjabber.com/073-jsj-react-with-pete-hunt-and-jordan-walke/#content)</figure>
76 -
77 -<table width="100%"><tr><td>
78 -01:34 – Pete Hunt Introduction<br />
79 -02:45 – Jordan Walke Introduction<br />
80 -04:15 – React<br />
81 -06:38 – 60 Frames Per Second<br />
82 -09:34 – Data Binding<br />
83 -12:31 – Performance<br />
84 -17:39 – Diffing Algorithm<br />
85 -19:36 – DOM Manipulation
86 -</td><td>
87 -23:06 – Supporting node.js<br />
88 -24:03 – rendr<br />
89 -26:02 – JSX<br />
90 -30:31 – requestAnimationFrame<br />
91 -34:15 – React and Applications<br />
92 -38:12 – React Users Khan Academy<br />
93 -39:53 – Making it work
94 -</td></tr></table>
95 -
96 -[Read the full transcript](http://javascriptjabber.com/073-jsj-react-with-pete-hunt-and-jordan-walke/)
97 -
98 -* * *
99 -
100 -### Introduction to React.js - Facebook Seattle
101 -
102 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/XxVg_s8xAms" frameborder="0" allowfullscreen></iframe>
103 -
104 -By [Tom Occhino](http://tomocchino.com/) and [Jordan Walke](https://github.com/jordwalke)
105 -
106 -* * *
107 -
108 -### Backbone + React + Middleman Screencast
109 -<iframe width="650" height="488" src="https://www.youtube-nocookie.com/embed/iul1fWHVU6A" frameborder="0" allowfullscreen></iframe>
110 -
111 -Backbone is a great way in interface a REST API with React. This screencast shows how to integrate the two using [Backbone-React-Component](https://github.com/magalhas/backbone-react-component). Middleman is the framework used in this example but could easily be replaced with other frameworks. A supported template of this can be found [here](https://github.com/jbhatab/middleman-backbone-react-template). -- [Open Minded Innovations](http://www.openmindedinnovations.com/)
112 -
113 -* * *
114 -
115 -### Developing User Interfaces With React - Super VanJS
116 -
117 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/1OeXsL5mr4g" frameborder="0" allowfullscreen></iframe>
118 -
119 -By [Steven Luscher](https://github.com/steveluscher)
120 -
121 -* * *
122 -
123 -### Introduction to React - LAWebSpeed meetup
124 -
125 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/SMMRJif5QW0" frameborder="0" allowfullscreen></iframe>
126 -
127 -by [Stoyan Stefanov](http://www.phpied.com/)
128 -
129 -* * *
130 -
131 -### React, or how to make life simpler - FrontEnd Dev Conf '14
132 -
133 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/YJNUK0EA_Jo" frameborder="0" allowfullscreen></iframe>
134 -
135 -**In Russian** by [Alexander Solovyov](http://solovyov.net/)
136 -
137 -* * *
138 -
139 -### "Functional DOM programming" - Meteor DevShop 11
140 -
141 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/qqVbr_LaCIo" frameborder="0" allowfullscreen></iframe>
142 -
143 -* * *
144 -
145 -### "Rethinking Web App Development at Facebook" - Facebook F8 Conference 2014
146 -
147 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/nYkdrAPrdcw" frameborder="0" allowfullscreen></iframe>
148 -
149 -* * *
150 -
151 -### React and Flux: Building Applications with a Unidirectional Data Flow - Forward JS 2014
152 -
153 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/i__969noyAM" frameborder="0" allowfullscreen></iframe>
154 -
155 -Facebook engineers [Bill Fisher](https://twitter.com/fisherwebdev) and [Jing Chen](https://twitter.com/jingc) talk about Flux and React, and how using an application architecture with a unidirectional data flow cleans up a lot of their code.
156 -
157 -* * *
158 -
159 -### Server-Side Rendering of Isomorphic Apps at SoundCloud
160 -
161 -<iframe src="https://player.vimeo.com/video/108488724" width="650" height="365" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
162 -
163 -Walk-through by [Andres Suarez](https://github.com/zertosh) on how [SoundCloud](https://developers.soundcloud.com/blog/) is using React and Flux for server-side rendering.
164 -
165 -[Slides and sample code](https://github.com/zertosh/ssr-demo-kit)
166 -
167 -* * *
168 -
169 -### Introducing React Native (+Playlist) - React.js Conf 2015
170 -
171 -<iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe>
172 -
173 -[Tom Occhino](https://twitter.com/tomocchino) reviews the past and present of React in 2015, and teases where it's going next.
docs/docs/web-components.md new
+60
@@ -0,0 +1,60 @@
1 +---
2 +id: web-components
3 +title: Web Components
4 +permalink: docs/web-components.html
5 +redirect_from: "/docs/webcomponents.html"
6 +---
7 +
8 +React and [Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components) are built to solve different problems. Web Components provide strong encapsulation for reusable components, while React provides a declarative library that keeps the DOM in sync with your data. The two goals are complementary. As a developer, you are free to use React in your Web Components, or to use Web Components in React, or both.
9 +
10 +Most people who use React don't use Web Components, but you may want to, especially if you are using third-party UI components that are written using Web Components.
11 +
12 +## Using Web Components in React
13 +
14 +```javascript
15 +class HelloMessage extends React.Component {
16 + render() {
17 + return <div>Hello <x-search>{this.props.name}</x-search>!</div>;
18 + }
19 +}
20 +```
21 +
22 +> Note:
23 +>
24 +> Web Components often expose an imperative API. For instance, a `video` Web Component might expose `play()` and `pause()` functions). To access the imperative APIs of a Web Component, you will need to use a ref to interact with the DOM node directly. If you are using third-party Web Components, the best solution is to write a React component that behaves as a wrapper for your Web Component.
25 +>
26 +> Events emitted by a Web Component may not properly propagate through a React render tree.
27 +> You will need to manually attach event handlers to handle these events within your React components.
28 +
29 +One common confusion is that Web Components use "class" instead of "className".
30 +
31 +```javascript
32 +function BrickFlipbox() {
33 + return (
34 + <brick-flipbox class="demo" ref="foo">
35 + <div>front</div>
36 + <div>back</div>
37 + </brick-flipbox>
38 + );
39 +}
40 +```
41 +
42 +## Using React in your Web Components
43 +
44 +```javascript
45 +var proto = Object.create(HTMLElement.prototype, {
46 + attachedCallback: {
47 + value: function() {
48 + var mountPoint = document.createElement('span');
49 + this.createShadowRoot().appendChild(mountPoint);
50 +
51 + var name = this.getAttribute('name');
52 + var url = 'https://www.google.com/search?q=' + encodeURIComponent(name);
53 + ReactDOM.render(<a href={url}>{name}</a>, mountPoint);
54 + }
55 + }
56 +});
57 +document.registerElement('x-search', {prototype: proto});
58 +```
59 +
60 +You can also check out this [complete Web Components example on GitHub](https://github.com/facebook/react/tree/master/examples/webcomponents).
docs/downloads.md deleted
-78
@@ -1,78 +0,0 @@
1 ----
2 -id: downloads
3 -title: Downloads
4 -layout: single
5 -permalink: downloads.html
6 ----
7 -Download the starter kit to get everything you need to
8 -[get started with React](/react/docs/getting-started.html). The starter kit includes React and some simple example apps.
9 -
10 -<div class="buttons-unit downloads">
11 - <a href="/react/downloads/react-{{site.react_version}}.zip" class="button">
12 - Download Starter Kit {{site.react_version}}
13 - </a>
14 -</div>
15 -
16 -## Development vs. Production Builds
17 -
18 -We provide two versions of React: an uncompressed version for development and a minified version for production. The development version includes extra warnings about common mistakes, whereas the production version includes extra performance optimizations and strips all error messages.
19 -
20 -If you're just starting out, make sure to use the development version.
21 -
22 -## Individual Downloads
23 -
24 -#### React {{site.react_version}} (development)
25 -The uncompressed, development version of [react.js](https://unpkg.com/react@{{site.react_version}}/dist/react.js) and [react-dom.js](https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js) with inline documentation (you need both files).
26 -
27 -```html
28 -<script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script>
29 -<script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
30 -```
31 -
32 -#### React {{site.react_version}} (production)
33 -The compressed, production version of [react.js](https://unpkg.com/react@{{site.react_version}}/dist/react.min.js) and [react-dom.js](https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.min.js) (you need both).
34 -
35 -```html
36 -<script src="https://unpkg.com/react@{{site.react_version}}/dist/react.min.js"></script>
37 -<script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.min.js"></script>
38 -```
39 -
40 -#### React with Add-Ons {{site.react_version}} (development)
41 -The uncompressed, development version of React with [optional add-ons](/react/docs/addons.html).
42 -
43 -```html
44 -<script src="https://unpkg.com/react@{{site.react_version}}/dist/react-with-addons.js"></script>
45 -<script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
46 -```
47 -
48 -#### React with Add-Ons {{site.react_version}} (production)
49 -The compressed, production version of React with [optional add-ons](/react/docs/addons.html).
50 -
51 -```html
52 -<script src="https://unpkg.com/react@{{site.react_version}}/dist/react-with-addons.min.js"></script>
53 -<script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.min.js"></script>
54 -```
55 -
56 -> Note:
57 ->
58 -> We're using [unpkg](https://unpkg.com) to serve these files. This is a free service with the goal to provide a hassle-free CDN for npm package authors. React is also available on other free CDNs including [cdnjs](https://cdnjs.com/libraries/react/) and [jsDelivr](https://www.jsdelivr.com/projects/react). If you have concerns with relying on an external host, we always recommend that you download React and serve it from your own servers.
59 -
60 -## npm
61 -
62 -We recommend using React from npm with a bundler like [browserify](http://browserify.org/) or [webpack](https://webpack.github.io/). You can use the `react` and `react-dom` packages. After installing it using `npm install --save react react-dom`, you can use:
63 -
64 -```js
65 -var React = require('react');
66 -var ReactDOM = require('react-dom');
67 -ReactDOM.render(<App />, ...);
68 -```
69 -
70 -Each of the [add-ons](/react/docs/addons.html) lives in its own package.
71 -
72 -**Note:** by default, React will be in development mode. To use React in production mode, set the environment variable `NODE_ENV` to `production` (using envify or webpack's DefinePlugin). A minifier that performs dead-code elimination such as [UglifyJS](https://github.com/mishoo/UglifyJS2) is recommended to completely remove the extra code present in development mode.
73 -
74 -## Bower
75 -
76 -```sh
77 -$ bower install --save react
78 -```
docs/downloads/single-file-example.html new
+21
@@ -0,0 +1,21 @@
1 +<!DOCTYPE html>
2 +<html>
3 + <head>
4 + <meta charset="UTF-8" />
5 + <title>Hello World</title>
6 + <script src="https://unpkg.com/react@latest/dist/react.js"></script>
7 + <script src="https://unpkg.com/react-dom@latest/dist/react-dom.js"></script>
8 + <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
9 + </head>
10 + <body>
11 + <div id="root"></div>
12 + <script type="text/babel">
13 +
14 + ReactDOM.render(
15 + <h1>Hello, world!</h1>,
16 + document.getElementById('root')
17 + );
18 +
19 + </script>
20 + </body>
21 +</html>
docs/img/docs/granular-dom-updates.gif
Binary files /dev/null and b/docs/img/docs/granular-dom-updates.gif differ
docs/img/docs/react-devtools-state.gif
Binary files /dev/null and b/docs/img/docs/react-devtools-state.gif differ
docs/img/logo_small.png
Binary files a/docs/img/logo_small.png and b/docs/img/logo_small.png differ
docs/img/logo_small_2x.png
Binary files a/docs/img/logo_small_2x.png and b/docs/img/logo_small_2x.png differ
docs/img/logo_small_gray.png
Binary files /dev/null and b/docs/img/logo_small_gray.png differ
docs/img/logo_small_gray_2x.png
Binary files /dev/null and b/docs/img/logo_small_gray_2x.png differ
docs/img/oss_logo.png
Binary files /dev/null and b/docs/img/oss_logo.png differ
docs/img/tutorial/devtools.png
Binary files /dev/null and b/docs/img/tutorial/devtools.png differ
docs/img/tutorial/tictac-empty.png
Binary files /dev/null and b/docs/img/tutorial/tictac-empty.png differ
docs/img/tutorial/tictac-numbers.png
Binary files /dev/null and b/docs/img/tutorial/tictac-numbers.png differ
docs/index.md
+3 -3
@@ -1,5 +1,5 @@
1 ---
2 -layout: page
2 +layout: hero
3 title: A JavaScript library for building user interfaces
4 id: home
5 ---
@@ -81,7 +81,7 @@ id: home
81 <hr class="home-divider" />
82 <section class="home-bottom-section">
83 <div class="buttons-unit">
84 - <a href="docs/getting-started.html" class="button">Get Started</a>
85 - <a href="downloads.html" class="button">Download React v{{site.react_version}}</a>
84 + <a href="docs/hello-world.html" class="button">Get Started</a>
85 + <a href="tutorial/tutorial.html" class="button">Take the Tutorial</a>
86 </div>
87 </section>
docs/tips/01-introduction.ja-JP.md deleted
-13
@@ -1,13 +0,0 @@
1 ----
2 -id: introduction-ja-JP
3 -title: イントロダクション
4 -layout: tips
5 -permalink: tips/introduction-ja-JP.html
6 -next: inline-styles-ja-JP.html
7 ----
8 -
9 -Reactのtipsのセクションでは、あなたの質問の多くに答えられたり、はまりそうな罠に対する注意を行う適当な大きさの情報を提供します。
10 -
11 -## コントリビューティング
12 -
13 -[Reactのリポジトリ](https://github.com/facebook/react)に[現在のtips](https://github.com/facebook/react/tree/master/docs)の記事のスタイルに沿った形でプルリクエストを投げてください。プルリクエストを投げる前にレビューが必要な場合は[freenodeの #reactjs チャンネル](irc://chat.freenode.net/reactjs)や[discuss.reactjs.org フォーラム](https://discuss.reactjs.org/)で助けを求めることができます。
docs/tips/01-introduction.ko-KR.md deleted
-13
@@ -1,13 +0,0 @@
1 ----
2 -id: introduction-ko-KR
3 -title: 개요
4 -layout: tips
5 -permalink: tips/introduction-ko-KR.html
6 -next: inline-styles-ko-KR.html
7 ----
8 -
9 -React 팁 섹션에서는 여러 궁금증을 해결해주고 흔히 하는 실수를 피할 수 있도록 짧은 정보들을 제공합니다.
10 -
11 -## 기여하기
12 -
13 -[현재 팁](https://github.com/facebook/react/tree/master/docs)의 형식을 따르는 풀 리퀘스트를 [React 저장소](https://github.com/facebook/react)에 보내주세요. PR을 보내기 전에 리뷰가 필요하다면 [freenode의 #reactjs 채널](irc://chat.freenode.net/reactjs)이나 [discuss.reactjs.org 포럼](https://discuss.reactjs.org/)에서 도움을 요청하실 수 있습니다.
docs/tips/01-introduction.md deleted
-13
@@ -1,13 +0,0 @@
1 ----
2 -id: introduction
3 -title: Introduction
4 -layout: tips
5 -permalink: tips/introduction.html
6 -next: inline-styles.html
7 ----
8 -
9 -The React tips section provides bite-sized information that can answer lots of questions you might have and warn you against common pitfalls.
10 -
11 -## Contributing
12 -
13 -Submit a pull request to the [React repository](https://github.com/facebook/react) following the [current tips](https://github.com/facebook/react/tree/master/docs) entries' style. If you have a recipe that needs review prior to submitting a PR you can find help in the [#reactjs channel on freenode](irc://chat.freenode.net/reactjs) or the [discuss.reactjs.org forum](https://discuss.reactjs.org/).
docs/tips/01-introduction.ru-RU.md deleted
-13
@@ -1,13 +0,0 @@
1 ----
2 -id: introduction-ru-RU
3 -title: Введение
4 -layout: tips
5 -permalink: tips/introduction-ru-RU.html
6 -next: inline-styles-ru-RU.html
7 ----
8 -
9 -Данный раздел советов по React содержит краткую информацию, которая поможет ответить на многие вопросы и предостеречь от распространенных ошибок.
10 -
11 -## Принятие участия
12 -
13 -Чтобы принять участие необходимо отправить pull request в [репозиторий React](https://github.com/facebook/react) следуя [данной инструкции](https://github.com/facebook/react/tree/master/docs). Если есть решение, которое нуждается в обсуждении перед тем как сделать PR, можно обратиться за помощью на [#reactjs канал на freenode](irc://chat.freenode.net/reactjs) или [discuss.reactjs.org форум](https://discuss.reactjs.org/).
docs/tips/02-inline-styles.ko-KR.md deleted
-23
@@ -1,23 +0,0 @@
1 ----
2 -id: inline-styles-ko-KR
3 -title: 인라인 스타일
4 -layout: tips
5 -permalink: tips/inline-styles-ko-KR.html
6 -next: if-else-in-JSX-ko-KR.html
7 -prev: introduction-ko-KR.html
8 ----
9 -
10 -React에서는 인라인 스타일을 문자열로 지정하지 않습니다. 대신 스타일 이름을 camelCased 형식으로 바꾼 키와 스타일의 값(주로 문자열입니다 - [자세히 알아보기](/react/tips/style-props-value-px-ko-KR.html))을 가진 객체로 지정됩니다.
11 -
12 -```js
13 -var divStyle = {
14 - color: 'white',
15 - backgroundImage: 'url(' + imgUrl + ')',
16 - WebkitTransition: 'all', // 'W'가 대문자임에 주의하세요
17 - msTransition: 'all' // 'ms'는 유일한 소문자 벤더 프리픽스(vendor prefix)입니다
18 -};
19 -
20 -ReactDOM.render(<div style={divStyle}>Hello World!</div>, mountNode);
21 -```
22 -
23 -스타일 키는 JS에서 DOM 노드의 프로퍼티에 접근하는 것과 일관성있도록 camelCased 형식입니다. (예를 들어 `node.style.backgroundImage`) [`ms`를 제외한](http://www.andismith.com/blog/2012/02/modernizr-prefixed/) 벤더 프리픽스는 대문자로 시작해야 합니다. 따라서 `WebkitTransition`은 대문자 "W"를 사용합니다.
docs/tips/02-inline-styles.md deleted
-23
@@ -1,23 +0,0 @@
1 ----
2 -id: inline-styles
3 -title: Inline Styles
4 -layout: tips
5 -permalink: tips/inline-styles.html
6 -next: if-else-in-JSX.html
7 -prev: introduction.html
8 ----
9 -
10 -In React, inline styles are not specified as a string. Instead they are specified with an object whose key is the camelCased version of the style name, and whose value is the style's value, usually a string ([more on that later](/react/tips/style-props-value-px.html)):
11 -
12 -```js
13 -var divStyle = {
14 - color: 'white',
15 - backgroundImage: 'url(' + imgUrl + ')',
16 - WebkitTransition: 'all', // note the capital 'W' here
17 - msTransition: 'all' // 'ms' is the only lowercase vendor prefix
18 -};
19 -
20 -ReactDOM.render(<div style={divStyle}>Hello World!</div>, mountNode);
21 -```
22 -
23 -Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes from JS (e.g. `node.style.backgroundImage`). Vendor prefixes [other than `ms`](http://www.andismith.com/blog/2012/02/modernizr-prefixed/) should begin with a capital letter. This is why `WebkitTransition` has an uppercase "W".
docs/tips/02-inline-styles.ru-RU.md deleted
-23
@@ -1,23 +0,0 @@
1 ----
2 -id: inline-styles-ru-RU
3 -title: Встроенные стили
4 -layout: tips
5 -permalink: tips/inline-styles-ru-RU.html
6 -next: if-else-in-JSX-ru-RU.html
7 -prev: introduction-ru-RU.html
8 ----
9 -
10 -В React, встроенные стили не указываются в виде строки. Вместо этого они определяются как объект, ключ которого является camelCase версией названия стиля, а значение которого является значением стиля, обычно строкой ([подробнее об этом далее](/react/tips/style-props-value-px.html)):
11 -
12 -```js
13 -var divStyle = {
14 - color: 'white',
15 - backgroundImage: 'url(' + imgUrl + ')',
16 - WebkitTransition: 'all', // обратите внимание на заглавную 'W'
17 - msTransition: 'all' // 'ms' это единственный префикс в нижнем регистре
18 -};
19 -
20 -ReactDOM.render(<div style={divStyle}>Hello World!</div>, mountNode);
21 -```
22 -
23 -Ключи стиля указываются в camelCase, в прямом соответствии с названиями свойств DOM-узлов в JS (например, `node.style.backgroundImage`). Префиксы [отличные от `ms`](http://www.andismith.com/blog/2012/02/modernizr-prefixed/) должны начинаться с заглавной буквы. Вот почему у `WebkitTransition` в верхнем регистре "W".
docs/tips/03-if-else-in-JSX.ko-KR.md deleted
-81
@@ -1,81 +0,0 @@
1 ----
2 -id: if-else-in-JSX-ko-KR
3 -title: JSX에서 If-Else
4 -layout: tips
5 -permalink: tips/if-else-in-JSX-ko-KR.html
6 -prev: inline-styles-ko-KR.html
7 -next: self-closing-tag-ko-KR.html
8 ----
9 -
10 -JSX 안에서는 `if-else` 구문이 작동하지 않습니다. 왜냐하면 JSX가 그저 함수 호출과 객체 생성의 편의 문법이기 때문입니다. 다음의 기본적인 예제를 살펴봅시다.
11 -
12 -```js
13 -// 이 JSX 코드는
14 -ReactDOM.render(<div id="msg">Hello World!</div>, mountNode);
15 -
16 -// 다음의 JS 코드로 변환됩니다.
17 -ReactDOM.render(React.createElement("div", {id:"msg"}, "Hello World!"), mountNode);
18 -```
19 -
20 -그렇기 때문에 `if` 구문을 넣을 수 없습니다. 다음 예제를 봅시다.
21 -
22 -```js
23 -// 이 JSX 코드는
24 -<div id={if (condition) { 'msg' }}>Hello World!</div>
25 -
26 -// 다음의 JS 코드로 변환됩니다.
27 -React.createElement("div", {id: if (condition) { 'msg' }}, "Hello World!");
28 -```
29 -
30 -이는 올바른 JS가 아닙니다. 대신 삼항 연산자를 사용할 수 있습니다.
31 -
32 -```js
33 -ReactDOM.render(<div id={condition ? 'msg' : ''}>Hello World!</div>, mountNode);
34 -```
35 -
36 -삼항 연산자가 충분하지 않다면 JSX구문 밖에서 `if` 문을 사용해 어떤 컴포넌트가 사용될 지 결정할 수 있습니다.
37 -
38 -```js
39 -var loginButton;
40 -if (loggedIn) {
41 - loginButton = <LogoutButton />;
42 -} else {
43 - loginButton = <LoginButton />;
44 -}
45 -
46 -return (
47 - <nav>
48 - <Home />
49 - {loginButton}
50 - </nav>
51 -);
52 -```
53 -
54 -"inline"을 좀더 선호한다면, JSX _안에_ [즉시 평가되는 함수 표현식](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression)을 선언하세요.
55 -
56 -```js
57 -return (
58 - <section>
59 - <h1>Color</h1>
60 - <h3>Name</h3>
61 - <p>{this.state.color || "white"}</p>
62 - <h3>Hex</h3>
63 - <p>
64 - {(() => {
65 - switch (this.state.color) {
66 - case "red": return "#FF0000";
67 - case "green": return "#00FF00";
68 - case "blue": return "#0000FF";
69 - default: return "#FFFFFF";
70 - }
71 - })()}
72 - </p>
73 - </section>
74 -);
75 -```
76 -
77 -> 주의:
78 ->
79 -> 위의 예제에 있는 ES6 [화살표 함수](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)는 `this`의 값을 구문적으로 바인드하기위해 사용되었습니다.
80 -
81 -[Babel REPL](https://babeljs.io/repl/)로 지금 바로 사용해보세요.
docs/tips/03-if-else-in-JSX.md deleted
-81
@@ -1,81 +0,0 @@
1 ----
2 -id: if-else-in-JSX
3 -title: If-Else in JSX
4 -layout: tips
5 -permalink: tips/if-else-in-JSX.html
6 -prev: inline-styles.html
7 -next: self-closing-tag.html
8 ----
9 -
10 -`if-else` statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction. Take this basic example:
11 -
12 -```js
13 -// This JSX:
14 -ReactDOM.render(<div id="msg">Hello World!</div>, mountNode);
15 -
16 -// Is transformed to this JS:
17 -ReactDOM.render(React.createElement("div", {id:"msg"}, "Hello World!"), mountNode);
18 -```
19 -
20 -This means that `if` statements don't fit in. Take this example:
21 -
22 -```js
23 -// This JSX:
24 -<div id={if (condition) { 'msg' }}>Hello World!</div>
25 -
26 -// Is transformed to this JS:
27 -React.createElement("div", {id: if (condition) { 'msg' }}, "Hello World!");
28 -```
29 -
30 -That's not valid JS. You probably want to make use of a ternary expression:
31 -
32 -```js
33 -ReactDOM.render(<div id={condition ? 'msg' : null}>Hello World!</div>, mountNode);
34 -```
35 -
36 -If a ternary expression isn't robust enough, you can use `if` statements outside of your JSX to determine which components should be used:
37 -
38 -```js
39 -var loginButton;
40 -if (loggedIn) {
41 - loginButton = <LogoutButton />;
42 -} else {
43 - loginButton = <LoginButton />;
44 -}
45 -
46 -return (
47 - <nav>
48 - <Home />
49 - {loginButton}
50 - </nav>
51 -);
52 -```
53 -
54 -Or if you prefer a more "inline" aesthetic, define [immediately-invoked function expressions](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression) _inside_ your JSX:
55 -
56 -```js
57 -return (
58 - <section>
59 - <h1>Color</h1>
60 - <h3>Name</h3>
61 - <p>{this.state.color || "white"}</p>
62 - <h3>Hex</h3>
63 - <p>
64 - {(() => {
65 - switch (this.state.color) {
66 - case "red": return "#FF0000";
67 - case "green": return "#00FF00";
68 - case "blue": return "#0000FF";
69 - default: return "#FFFFFF";
70 - }
71 - })()}
72 - </p>
73 - </section>
74 -);
75 -```
76 -
77 -> Note:
78 ->
79 -> In the example above, an ES6 [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) is utilized to lexically bind the value of `this`.
80 -
81 -Try using it today with the [Babel REPL](https://babeljs.io/repl/).
docs/tips/03-if-else-in-JSX.ru-RU.md deleted
-81
@@ -1,81 +0,0 @@
1 ----
2 -id: if-else-in-JSX-ru-RU
3 -title: If-Else в JSX
4 -layout: tips
5 -permalink: tips/if-else-in-JSX-ru-RU.html
6 -prev: inline-styles-ru-RU.html
7 -next: self-closing-tag-ru-RU.html
8 ----
9 -
10 -Некоторые конструкции, такие как `if-else`, нельзя использовать внутри JSX, так как JSX в результате преобразуется в вызов функции JS, как показано в примере:
11 -
12 -```js
13 -// JSX:
14 -ReactDOM.render(<div id="msg">Hello World!</div>, mountNode);
15 -
16 -// Преобразованный в JS:
17 -ReactDOM.render(React.createElement("div", {id:"msg"}, "Hello World!"), mountNode);
18 -```
19 -
20 -Это означает что оператор `if` нельзя встроить таким образом:
21 -
22 -```js
23 -// JSX:
24 -<div id={if (condition) { 'msg' }}>Hello World!</div>
25 -
26 -// Преобразованный в JS:
27 -React.createElement("div", {id: if (condition) { 'msg' }}, "Hello World!");
28 -```
29 -
30 -В результате преобразования получается неверный JS код. В таких случаях используется тернарный условный оператор:
31 -
32 -```js
33 -ReactDOM.render(<div id={condition ? 'msg' : null}>Hello World!</div>, mountNode);
34 -```
35 -
36 -Если тернарного оператора недостаточно, вы можете вынести оператор `if`, определяющий выбор компонентов, вне JSX:
37 -
38 -```js
39 -var loginButton;
40 -if (loggedIn) {
41 - loginButton = <LogoutButton />;
42 -} else {
43 - loginButton = <LoginButton />;
44 -}
45 -
46 -return (
47 - <nav>
48 - <Home />
49 - {loginButton}
50 - </nav>
51 -);
52 -```
53 -
54 -Также вы можете обернуть код в [немедленно вызываемую функцию](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression) и расположить её _внутри_ JSX.
55 -
56 -```js
57 -return (
58 - <section>
59 - <h1>Color</h1>
60 - <h3>Name</h3>
61 - <p>{this.state.color || "white"}</p>
62 - <h3>Hex</h3>
63 - <p>
64 - {(() => {
65 - switch (this.state.color) {
66 - case "red": return "#FF0000";
67 - case "green": return "#00FF00";
68 - case "blue": return "#0000FF";
69 - default: return "#FFFFFF";
70 - }
71 - })()}
72 - </p>
73 - </section>
74 -);
75 -```
76 -
77 -> Примечание:
78 ->
79 -> В приведенном выше примере, используется [функция-стрелка](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) из ES6 для связи со значением `this`.
80 -
81 -Вы можете попробовать этот синтаксис внутри [Babel REPL](https://babeljs.io/repl/).
docs/tips/04-self-closing-tag.ja-JP.md deleted
-14
@@ -1,14 +0,0 @@
1 ----
2 -id: self-closing-tag-ja-JP
3 -title: 自己終了タグ
4 -layout: tips
5 -permalink: tips/self-closing-tag-ja-JP.html
6 -prev: if-else-in-JSX-ja-JP.html
7 -next: maximum-number-of-jsx-root-nodes-ja-JP.html
8 ----
9 -
10 -JSXでは、 `<MyComponent />` 単体は正しいですが、 `<MyComponent>` は正しくありません。 全てのタグは、自己終了の形式または対応する終了タグ( `</MyComponent>` )で閉じるべきです。
11 -
12 -> 注意:
13 ->
14 -> 全てのReactコンポーネントは `<div />` のように自己終了タグになり得ます。 `<div></div>` もまた同様です。
docs/tips/04-self-closing-tag.ko-KR.md deleted
-14
@@ -1,14 +0,0 @@
1 ----
2 -id: self-closing-tag-ko-KR
3 -title: 자기 자신을 닫는 태그
4 -layout: tips
5 -permalink: tips/self-closing-tag-ko-KR.html
6 -prev: if-else-in-JSX-ko-KR.html
7 -next: maximum-number-of-jsx-root-nodes-ko-KR.html
8 ----
9 -
10 -JSX에서 `<MyComponent>`는 유효하지 않고 `<MyComponent />`만 유효합니다. 모든 태그는 닫혀야 합니다. 자기 자신을 닫는 형식을 사용하거나 대응되는 닫는 태그(`</MyComponent>`)가 필요합니다.
11 -
12 -> 주의:
13 ->
14 -> 모든 React 컴포넌트는 자기 자신을 닫을 수 있습니다: `<div />`. `<div></div>`와 동일합니다.
docs/tips/04-self-closing-tag.md deleted
-14
@@ -1,14 +0,0 @@
1 ----
2 -id: self-closing-tag
3 -title: Self-Closing Tag
4 -layout: tips
5 -permalink: tips/self-closing-tag.html
6 -prev: if-else-in-JSX.html
7 -next: maximum-number-of-jsx-root-nodes.html
8 ----
9 -
10 -In JSX, `<MyComponent />` alone is valid while `<MyComponent>` isn't. All tags must be closed, either with the self-closing format or with a corresponding closing tag (`</MyComponent>`).
11 -
12 -> Note:
13 ->
14 -> Every React component can be self-closing: `<div />`. `<div></div>` is also an equivalent.
docs/tips/04-self-closing-tag.ru-RU.md deleted
-14
@@ -1,14 +0,0 @@
1 ----
2 -id: self-closing-tag-ru-RU
3 -title: Одиночный тег
4 -layout: tips
5 -permalink: tips/self-closing-tag-ru-RU.html
6 -prev: if-else-in-JSX-ru-RU.html
7 -next: maximum-number-of-jsx-root-nodes-ru-RU.html
8 ----
9 -
10 -В JSX все теги необходимо закрывать. Это можно сделать либо в открывающем теге `<MyComponent />`, либо отдельным закрывающим тегом `</MyComponent>`.
11 -
12 -> Примечание:
13 ->
14 -> Любой React компонент может быть одиночным: `<div />` это то же самое, что `<div></div>`.
docs/tips/05-maximum-number-of-jsx-root-nodes.ko-KR.md deleted
-12
@@ -1,12 +0,0 @@
1 ----
2 -id: maximum-number-of-jsx-root-nodes-ko-KR
3 -title: JSX 루트 노드의 최대 갯수
4 -layout: tips
5 -permalink: tips/maximum-number-of-jsx-root-nodes-ko-KR.html
6 -prev: self-closing-tag-ko-KR.html
7 -next: style-props-value-px-ko-KR.html
8 ----
9 -
10 -현재 컴포넌트의 `render`는 한 노드만 리턴할 수 있습니다. 만약 `div` 배열을 리턴하려면, `div`, `span`과 같은 다른 컴포넌트로 한 번 더 싸주어야 합니다.
11 -
12 -JSX는 일반 JS로 컴파일 함을 잊지말아야 합니다. 두개의 함수를 리턴하는 것은 문법적으로 맞지 않습니다. 이와 마찬가지로, 한 삼항 연산자 안에 한개 이상의 자식 컴포넌트를 넣으면 안됩니다.
docs/tips/05-maximum-number-of-jsx-root-nodes.md deleted
-12
@@ -1,12 +0,0 @@
1 ----
2 -id: maximum-number-of-jsx-root-nodes
3 -title: Maximum Number of JSX Root Nodes
4 -layout: tips
5 -permalink: tips/maximum-number-of-jsx-root-nodes.html
6 -prev: self-closing-tag.html
7 -next: style-props-value-px.html
8 ----
9 -
10 -Currently, in a component's `render`, you can only return one node; if you have, say, a list of `div`s to return, you must wrap your components within a `div`, `span` or any other component.
11 -
12 -Don't forget that JSX compiles into regular JS; returning two functions doesn't really make syntactic sense. Likewise, don't put more than one child in a ternary.
docs/tips/05-maximum-number-of-jsx-root-nodes.ru-RU.md deleted
-12
@@ -1,12 +0,0 @@
1 ----
2 -id: maximum-number-of-jsx-root-nodes-ru-RU
3 -title: Максимальное количество корневых JSX-узлов
4 -layout: tips
5 -permalink: tips/maximum-number-of-jsx-root-nodes-ru-RU.html
6 -prev: self-closing-tag-ru-RU.html
7 -next: style-props-value-px-ru-RU.html
8 ----
9 -
10 -Из метода `render` компонента пока что можно вернуть только один узел. Если нужно вернуть, например, несколько `div`, оберните их в `div`, `span` или любой другой компонент.
11 -
12 -Не забывайте, что JSX компилируется в обычный JS, и возвращение двух функций не имеет синтаксического смысла. Также не помещайте более одного дочернего элемента в тернарный оператор.
docs/tips/06-style-props-value-px.ko-KR.md deleted
-46
@@ -1,46 +0,0 @@
1 ----
2 -id: style-props-value-px-ko-KR
3 -title: 스타일 속성에서 특정 픽셀 값 넣는 간단한 방법
4 -layout: tips
5 -permalink: tips/style-props-value-px-ko-KR.html
6 -prev: maximum-number-of-jsx-root-nodes-ko-KR.html
7 -next: children-props-type-ko-KR.html
8 ----
9 -
10 -인라인 `style` prop에서 픽셀 값을 넣을때, React가 자동으로 숫자뒤에 "px"를 붙여줍니다. 다음과 같이 동작합니다:
11 -
12 -```js
13 -var divStyle = {height: 10}; // "height:10px" 로 렌더링 됩니다.
14 -ReactDOM.render(<div style={divStyle}>Hello World!</div>, mountNode);
15 -```
16 -
17 -더 자세한 이야기는 [Inline Styles](/react/tips/inline-styles-ko-KR.html)를 참고해 주시기 바랍니다.
18 -
19 -개발 하다보면 CSS 속성들이 단위 없이 그대로 유지되어야 할 때가 있을 겁니다. 아래의 프로퍼티들은 자동으로 "px"가 붙지 않는 속성 리스트 입니다:
20 -
21 -- `animationIterationCount`
22 -- `boxFlex`
23 -- `boxFlexGroup`
24 -- `boxOrdinalGroup`
25 -- `columnCount`
26 -- `fillOpacity`
27 -- `flex`
28 -- `flexGrow`
29 -- `flexPositive`
30 -- `flexShrink`
31 -- `flexNegative`
32 -- `flexOrder`
33 -- `fontWeight`
34 -- `lineClamp`
35 -- `lineHeight`
36 -- `opacity`
37 -- `order`
38 -- `orphans`
39 -- `stopOpacity`
40 -- `strokeDashoffset`
41 -- `strokeOpacity`
42 -- `strokeWidth`
43 -- `tabSize`
44 -- `widows`
45 -- `zIndex`
46 -- `zoom`
docs/tips/06-style-props-value-px.md deleted
-46
@@ -1,46 +0,0 @@
1 ----
2 -id: style-props-value-px
3 -title: Shorthand for Specifying Pixel Values in style props
4 -layout: tips
5 -permalink: tips/style-props-value-px.html
6 -prev: maximum-number-of-jsx-root-nodes.html
7 -next: children-props-type.html
8 ----
9 -
10 -When specifying a pixel value for your inline `style` prop, React automatically appends the string "px" for you after your number value, so this works:
11 -
12 -```js
13 -var divStyle = {height: 10}; // rendered as "height:10px"
14 -ReactDOM.render(<div style={divStyle}>Hello World!</div>, mountNode);
15 -```
16 -
17 -See [Inline Styles](/react/tips/inline-styles.html) for more info.
18 -
19 -Sometimes you _do_ want to keep the CSS properties unitless. Here's a list of properties that won't get the automatic "px" suffix:
20 -
21 -- `animationIterationCount`
22 -- `boxFlex`
23 -- `boxFlexGroup`
24 -- `boxOrdinalGroup`
25 -- `columnCount`
26 -- `fillOpacity`
27 -- `flex`
28 -- `flexGrow`
29 -- `flexPositive`
30 -- `flexShrink`
31 -- `flexNegative`
32 -- `flexOrder`
33 -- `fontWeight`
34 -- `lineClamp`
35 -- `lineHeight`
36 -- `opacity`
37 -- `order`
38 -- `orphans`
39 -- `stopOpacity`
40 -- `strokeDashoffset`
41 -- `strokeOpacity`
42 -- `strokeWidth`
43 -- `tabSize`
44 -- `widows`
45 -- `zIndex`
46 -- `zoom`
docs/tips/06-style-props-value-px.ru-RU.md deleted
-46
@@ -1,46 +0,0 @@
1 ----
2 -id: style-props-value-px-ru-RU
3 -title: Краткая форма значений в пикселях для атрибута style
4 -layout: tips
5 -permalink: tips/style-props-value-px-ru-RU.html
6 -prev: maximum-number-of-jsx-root-nodes-ru-RU.html
7 -next: children-props-type.html
8 ----
9 -
10 -React автоматически добавляет "px" для значений, которые указаны в числовом виде и находятся внутри встроенного стиля атрибута `style`, например:
11 -
12 -```js
13 -var divStyle = {height: 10}; // получится "height:10px"
14 -ReactDOM.render(<div style={divStyle}>Hello World!</div>, mountNode);
15 -```
16 -
17 -Подробная информация о [встроенных стилях](/react/tips/inline-styles-ru-RU.html).
18 -
19 -Иногда бывает нужно указать значение *без* единицы измерения. Для этих свойств "px" не добавляется автоматически:
20 -
21 -- `animationIterationCount`
22 -- `boxFlex`
23 -- `boxFlexGroup`
24 -- `boxOrdinalGroup`
25 -- `columnCount`
26 -- `fillOpacity`
27 -- `flex`
28 -- `flexGrow`
29 -- `flexPositive`
30 -- `flexShrink`
31 -- `flexNegative`
32 -- `flexOrder`
33 -- `fontWeight`
34 -- `lineClamp`
35 -- `lineHeight`
36 -- `opacity`
37 -- `order`
38 -- `orphans`
39 -- `stopOpacity`
40 -- `strokeDashoffset`
41 -- `strokeOpacity`
42 -- `strokeWidth`
43 -- `tabSize`
44 -- `widows`
45 -- `zIndex`
46 -- `zoom`
docs/tips/07-children-props-type.ko-KR.md deleted
-49
@@ -1,49 +0,0 @@
1 ----
2 -id: children-props-type-ko-KR
3 -title: 자식 속성들의 타입
4 -layout: tips
5 -permalink: tips/children-props-type-ko-KR.html
6 -prev: style-props-value-px-ko-KR.html
7 -next: controlled-input-null-value-ko-KR.html
8 ----
9 -
10 -컴포넌트의 자식들(`this.props.children`)은 대부분 컴포넌트의 배열로 들어갑니다:
11 -
12 -```js
13 -var GenericWrapper = React.createClass({
14 - componentDidMount: function() {
15 - console.log(Array.isArray(this.props.children)); // => true
16 - },
17 -
18 - render: function() {
19 - return <div />;
20 - }
21 -});
22 -
23 -ReactDOM.render(
24 - <GenericWrapper><span/><span/><span/></GenericWrapper>,
25 - mountNode
26 -);
27 -```
28 -
29 -하지만 자식이 하나만 있는 경우, `this.props.children`는 _배열 래퍼(wrapper)없이_ 싱글 자식 컴포넌트가 됩니다. 이렇게 함으로써 배열 할당을 줄일 수 있습니다.
30 -
31 -```js
32 -var GenericWrapper = React.createClass({
33 - componentDidMount: function() {
34 - console.log(Array.isArray(this.props.children)); // => false
35 -
36 - // 경고 : 산출된 5 값은 'hello' 스트링의 길이 입니다. 존재하지 않는 배열 래퍼의 길이인 1이 아닙니다!
37 -
38 - console.log(this.props.children.length);
39 - },
40 -
41 - render: function() {
42 - return <div />;
43 - }
44 -});
45 -
46 -ReactDOM.render(<GenericWrapper>hello</GenericWrapper>, mountNode);
47 -```
48 -
49 -`this.props.children`을 쉽게 다룰 수 있도록 [React.Children utilities](/react/docs/top-level-api-ko-KR.html#react.children)를 제공하고 있습니다.
docs/tips/07-children-props-type.md deleted
-49
@@ -1,49 +0,0 @@
1 ----
2 -id: children-props-type
3 -title: Type of the Children props
4 -layout: tips
5 -permalink: tips/children-props-type.html
6 -prev: style-props-value-px.html
7 -next: controlled-input-null-value.html
8 ----
9 -
10 -Usually, a component's children (`this.props.children`) is an array of components:
11 -
12 -```js
13 -var GenericWrapper = React.createClass({
14 - componentDidMount: function() {
15 - console.log(Array.isArray(this.props.children)); // => true
16 - },
17 -
18 - render: function() {
19 - return <div />;
20 - }
21 -});
22 -
23 -ReactDOM.render(
24 - <GenericWrapper><span/><span/><span/></GenericWrapper>,
25 - mountNode
26 -);
27 -```
28 -
29 -However, when there is only a single child, `this.props.children` will be the single child component itself _without the array wrapper_. This saves an array allocation.
30 -
31 -```js
32 -var GenericWrapper = React.createClass({
33 - componentDidMount: function() {
34 - console.log(Array.isArray(this.props.children)); // => false
35 -
36 - // warning: yields 5 for length of the string 'hello', not 1 for the
37 - // length of the non-existent array wrapper!
38 - console.log(this.props.children.length);
39 - },
40 -
41 - render: function() {
42 - return <div />;
43 - }
44 -});
45 -
46 -ReactDOM.render(<GenericWrapper>hello</GenericWrapper>, mountNode);
47 -```
48 -
49 -To make `this.props.children` easy to deal with, we've provided the [React.Children utilities](/react/docs/top-level-api.html#react.children).
docs/tips/08-controlled-input-null-value.ko-KR.md deleted
-22
@@ -1,22 +0,0 @@
1 ----
2 -id: controlled-input-null-value-ko-KR
3 -title: 제어되는 input 내의 null 값
4 -layout: tips
5 -permalink: tips/controlled-input-null-value-ko-KR.html
6 -prev: children-props-type-ko-KR.html
7 -next: componentWillReceiveProps-not-triggered-after-mounting-ko-KR.html
8 ----
9 -
10 -[제어되는 컴포넌트들](/react/docs/forms-ko-KR.html)의 `value` 속성 값을 지정하면 유저에 의해 입력값을 바꿀 수 없습니다.
11 -
12 -`value`가 정해져 있는데도 입력값을 변경할 수 있는 문제를 겪고 있다면 실수로 `value`를 `undefined`나 `null`로 설정한 것일 수 있습니다.
13 -
14 -아래 짧은 예제가 있습니다; 렌더링 후, 잠시 뒤에 텍스트를 고칠 수 있는 상태가 되는 것을 확인 하실 수 있습니다.
15 -
16 -```js
17 -ReactDOM.render(<input value="hi" />, mountNode);
18 -
19 -setTimeout(function() {
20 - ReactDOM.render(<input value={null} />, mountNode);
21 -}, 1000);
22 -```
docs/tips/08-controlled-input-null-value.md deleted
-22
@@ -1,22 +0,0 @@
1 ----
2 -id: controlled-input-null-value
3 -title: Value of null for Controlled Input
4 -layout: tips
5 -permalink: tips/controlled-input-null-value.html
6 -prev: children-props-type.html
7 -next: componentWillReceiveProps-not-triggered-after-mounting.html
8 ----
9 -
10 -Specifying the `value` prop on a [controlled component](/react/docs/forms.html) prevents the user from changing the input unless you desire so.
11 -
12 -You might have run into a problem where `value` is specified, but the input can still be changed without consent. In this case, you might have accidentally set `value` to `undefined` or `null`.
13 -
14 -The snippet below shows this phenomenon; after a second, the text becomes editable.
15 -
16 -```js
17 -ReactDOM.render(<input value="hi" />, mountNode);
18 -
19 -setTimeout(function() {
20 - ReactDOM.render(<input value={null} />, mountNode);
21 -}, 1000);
22 -```
docs/tips/09-componentWillReceiveProps-not-triggered-after-mounting.ko-KR.md deleted
-13
@@ -1,13 +0,0 @@
1 ----
2 -id: componentWillReceiveProps-not-triggered-after-mounting-ko-KR
3 -title: 마운트 후에는 componentWillReceiveProps가 실행되지 않음.
4 -layout: tips
5 -permalink: tips/componentWillReceiveProps-not-triggered-after-mounting-ko-KR.html
6 -prev: controlled-input-null-value-ko-KR.html
7 -next: props-in-getInitialState-as-anti-pattern-ko-KR.html
8 ----
9 -
10 -`componentWillReceiveProps`는 노드가 더해진 후엔 실행되지 않습니다. 이는 설계에 의한 것입니다. [다른 생명주기 메소드](/react/docs/component-specs-ko-KR.html)에서 요구사항에 적합한 것을 찾아보세요.
11 -
12 -이러한 이유는 `componentWillReceiveProps`에 종종 예전 props와 액션의 차이를 비교하는 로직이 들어가기 때문입니다. 마운트할 때 트리거되지 않으면, (예전 props가 없다고 해도) 메소드의 형태를 구별하는 데 도움이 됩니다.
13 -
docs/tips/09-componentWillReceiveProps-not-triggered-after-mounting.md deleted
-12
@@ -1,12 +0,0 @@
1 ----
2 -id: componentWillReceiveProps-not-triggered-after-mounting
3 -title: componentWillReceiveProps Not Triggered After Mounting
4 -layout: tips
5 -permalink: tips/componentWillReceiveProps-not-triggered-after-mounting.html
6 -prev: controlled-input-null-value.html
7 -next: props-in-getInitialState-as-anti-pattern.html
8 ----
9 -
10 -`componentWillReceiveProps` isn't triggered after the node is put on scene. This is by design. Check out [other lifecycle methods](/react/docs/component-specs.html) for the one that suits your needs.
11 -
12 -The reason for that is because `componentWillReceiveProps` often handles the logic of comparing with the old props and acting upon changes; not triggering it at mounting (where there are no old props) helps in defining what the method does.
docs/tips/10-props-in-getInitialState-as-anti-pattern.ko-KR.md deleted
-67
@@ -1,67 +0,0 @@
1 ----
2 -id: props-in-getInitialState-as-anti-pattern-ko-KR
3 -title: getInitialState의 Props는 안티패턴
4 -layout: tips
5 -permalink: tips/props-in-getInitialState-as-anti-pattern-ko-KR.html
6 -prev: componentWillReceiveProps-not-triggered-after-mounting-ko-KR.html
7 -next: dom-event-listeners-ko-KR.html
8 ----
9 -
10 -> 주의 :
11 ->
12 -> 이것은 React에만 국한된 팁이 아니고 안티패턴은 평범한 코드 속 에서도 종종 발생합니다. 이 글에서는 React로 간단하게 설명해 보겠습니다.
13 -
14 -부모로부터 받은 props를 이용하여 `getInitialState`에서 state를 생성할 때 종종 "진실의 소스", 예를 들어 진짜 데이터가 있는 곳을 중복으로 만들 때가 있습니다. 가능하던 안하던, 나중에 싱크되지 않는 확실한 값을 계산하고 또한 유지보수에도 문제를 야기합니다.
15 -
16 -**나쁜 예제:**
17 -
18 -```js
19 -var MessageBox = React.createClass({
20 - getInitialState: function() {
21 - return {nameWithQualifier: 'Mr. ' + this.props.name};
22 - },
23 -
24 - render: function() {
25 - return <div>{this.state.nameWithQualifier}</div>;
26 - }
27 -});
28 -
29 -ReactDOM.render(<MessageBox name="Rogers"/>, mountNode);
30 -```
31 -
32 -더 나은 코드:
33 -
34 -```js
35 -var MessageBox = React.createClass({
36 - render: function() {
37 - return <div>{'Mr. ' + this.props.name}</div>;
38 - }
39 -});
40 -
41 -ReactDOM.render(<MessageBox name="Rogers"/>, mountNode);
42 -```
43 -
44 -(복잡한 로직이라, 메소드에서 계산하는 부분만 떼어 왔습니다.)
45 -
46 -하지만 여기서 싱크를 맞출 목적이 아님을 명확히 할 수 있다면, 이것은 안티 패턴이 **아닙니다.**
47 -
48 -
49 -
50 -```js
51 -var Counter = React.createClass({
52 - getInitialState: function() {
53 - // initial로 시작하는 메소드는 내부에서 받은 어떠한 값을 초기화 할 목적이 있다는 것을 나타냅니다.
54 - return {count: this.props.initialCount};
55 - },
56 -
57 - handleClick: function() {
58 - this.setState({count: this.state.count + 1});
59 - },
60 -
61 - render: function() {
62 - return <div onClick={this.handleClick}>{this.state.count}</div>;
63 - }
64 -});
65 -
66 -ReactDOM.render(<Counter initialCount={7}/>, mountNode);
67 -```
docs/tips/10-props-in-getInitialState-as-anti-pattern.md deleted
-68
@@ -1,68 +0,0 @@
1 ----
2 -id: props-in-getInitialState-as-anti-pattern
3 -title: Props in getInitialState Is an Anti-Pattern
4 -layout: tips
5 -permalink: tips/props-in-getInitialState-as-anti-pattern.html
6 -prev: componentWillReceiveProps-not-triggered-after-mounting.html
7 -next: dom-event-listeners.html
8 ----
9 -
10 -> Note:
11 ->
12 -> This isn't really a React-specific tip, as such anti-patterns often occur in code in general; in this case, React simply points them out more clearly.
13 -
14 -Using props to generate state in `getInitialState` often leads to duplication of "source of truth", i.e. where the real data is. This is because `getInitialState` is only invoked when the component is first created.
15 -
16 -Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble.
17 -
18 -**Bad example:**
19 -
20 -```js
21 -var MessageBox = React.createClass({
22 - getInitialState: function() {
23 - return {nameWithQualifier: 'Mr. ' + this.props.name};
24 - },
25 -
26 - render: function() {
27 - return <div>{this.state.nameWithQualifier}</div>;
28 - }
29 -});
30 -
31 -ReactDOM.render(<MessageBox name="Rogers"/>, mountNode);
32 -```
33 -
34 -Better:
35 -
36 -```js
37 -var MessageBox = React.createClass({
38 - render: function() {
39 - return <div>{'Mr. ' + this.props.name}</div>;
40 - }
41 -});
42 -
43 -ReactDOM.render(<MessageBox name="Rogers"/>, mountNode);
44 -```
45 -
46 -(For more complex logic, simply isolate the computation in a method.)
47 -
48 -However, it's **not** an anti-pattern if you make it clear that the prop is only seed data for the component's internally-controlled state:
49 -
50 -```js
51 -var Counter = React.createClass({
52 - getInitialState: function() {
53 - // naming it initialX clearly indicates that the only purpose
54 - // of the passed down prop is to initialize something internally
55 - return {count: this.props.initialCount};
56 - },
57 -
58 - handleClick: function() {
59 - this.setState({count: this.state.count + 1});
60 - },
61 -
62 - render: function() {
63 - return <div onClick={this.handleClick}>{this.state.count}</div>;
64 - }
65 -});
66 -
67 -ReactDOM.render(<Counter initialCount={7}/>, mountNode);
68 -```
docs/tips/11-dom-event-listeners.ko-KR.md deleted
-45
@@ -1,45 +0,0 @@
1 ----
2 -id: dom-event-listeners-ko-KR
3 -title: 컴포넌트에서 DOM 이벤트 리스너
4 -layout: tips
5 -permalink: tips/dom-event-listeners-ko-KR.html
6 -prev: props-in-getInitialState-as-anti-pattern-ko-KR.html
7 -next: initial-ajax-ko-KR.html
8 ----
9 -
10 -> 주의:
11 ->
12 -> 이 글은 React에서 제공되지 않은 DOM 이벤트를 어떻게 붙이는지 설명합니다. ([더 자세한 정보는 여기에서 보세요.](/react/docs/events-ko-KR.html)). 이는 jQuery 같은 다른 라이브러리들을 통합할 때 좋습니다.
13 -
14 -윈도우 크기를 조절해봅시다.
15 -
16 -```js
17 -var Box = React.createClass({
18 - getInitialState: function() {
19 - return {windowWidth: window.innerWidth};
20 - },
21 -
22 - handleResize: function(e) {
23 - this.setState({windowWidth: window.innerWidth});
24 - },
25 -
26 - componentDidMount: function() {
27 - window.addEventListener('resize', this.handleResize);
28 - },
29 -
30 - componentWillUnmount: function() {
31 - window.removeEventListener('resize', this.handleResize);
32 - },
33 -
34 - render: function() {
35 - return <div>Current window width: {this.state.windowWidth}</div>;
36 - }
37 -});
38 -
39 -ReactDOM.render(<Box />, mountNode);
40 -```
41 -
42 -컴포넌트가 마운트 되고 DOM 표현을 가지게 되면 `componentDidMount`가 호출됩니다. 일반적인 DOM 이벤트를 붙이는 곳으로 여기를 종종 사용합니다.
43 -
44 -이벤트 콜백은 원래 엘리먼트 대신 React 컴포넌트에 바인드하는 걸 주의합시다. React는 [오토바인드](/react/docs/interactivity-and-dynamic-uis-ko-KR.html#under-the-hood-autobinding-and-event-delegation) 과정에서 메서드를 현재 컴포넌트 인스턴스로 바인드합니다.
45 -
docs/tips/11-dom-event-listeners.md deleted
-44
@@ -1,44 +0,0 @@
1 ----
2 -id: dom-event-listeners
3 -title: DOM Event Listeners in a Component
4 -layout: tips
5 -permalink: tips/dom-event-listeners.html
6 -prev: props-in-getInitialState-as-anti-pattern.html
7 -next: initial-ajax.html
8 ----
9 -
10 -> Note:
11 ->
12 -> This entry shows how to attach DOM events not provided by React ([check here for more info](/react/docs/events.html)). This is good for integrations with other libraries such as jQuery.
13 -
14 -Try to resize the window:
15 -
16 -```js
17 -var Box = React.createClass({
18 - getInitialState: function() {
19 - return {windowWidth: window.innerWidth};
20 - },
21 -
22 - handleResize: function(e) {
23 - this.setState({windowWidth: window.innerWidth});
24 - },
25 -
26 - componentDidMount: function() {
27 - window.addEventListener('resize', this.handleResize);
28 - },
29 -
30 - componentWillUnmount: function() {
31 - window.removeEventListener('resize', this.handleResize);
32 - },
33 -
34 - render: function() {
35 - return <div>Current window width: {this.state.windowWidth}</div>;
36 - }
37 -});
38 -
39 -ReactDOM.render(<Box />, mountNode);
40 -```
41 -
42 -`componentDidMount` is called after the component is mounted and has a DOM representation. This is often a place where you would attach generic DOM events.
43 -
44 -Notice that the event callback is bound to the react component and not the original element. React automatically binds methods to the current component instance for you through a process of [autobinding](/react/docs/interactivity-and-dynamic-uis.html#under-the-hood-autobinding-and-event-delegation).
docs/tips/12-initial-ajax.ko-KR.md deleted
-51
@@ -1,51 +0,0 @@
1 ----
2 -id: initial-ajax-ko-KR
3 -title: AJAX를 통해 초기 데이터 읽어오기
4 -layout: tips
5 -permalink: tips/initial-ajax-ko-KR.html
6 -prev: dom-event-listeners-ko-KR.html
7 -next: false-in-jsx-ko-KR.html
8 ----
9 -
10 -`componentDidMount`에서 데이터를 가져옵니다. 응답이 올 때 데이터가 state에 저장되고 렌더링을 시작하여 UI를 갱신합니다.
11 -
12 -비동기 요청의 응답을 처리하여 state를 변경하기 전에, 컴포넌트가 여전히 마운트되었는지를 확인하기 위해 `this.isMounted()`를 사용합니다.
13 -
14 -이 예제는 희망하는 Github 사용자의 최근 gist를 가져옵니다.
15 -
16 -```js
17 -var UserGist = React.createClass({
18 - getInitialState: function() {
19 - return {
20 - username: '',
21 - lastGistUrl: ''
22 - };
23 - },
24 -
25 - componentDidMount: function() {
26 - $.get(this.props.source, function(result) {
27 - var lastGist = result[0];
28 - if (this.isMounted()) {
29 - this.setState({
30 - username: lastGist.owner.login,
31 - lastGistUrl: lastGist.html_url
32 - });
33 - }
34 - }.bind(this));
35 - },
36 -
37 - render: function() {
38 - return (
39 - <div>
40 - {this.state.username}'s last gist is
41 - <a href={this.state.lastGistUrl}>here</a>.
42 - </div>
43 - );
44 - }
45 -});
46 -
47 -ReactDOM.render(
48 - <UserGist source="https://api.github.com/users/octocat/gists" />,
49 - mountNode
50 -);
51 -```
docs/tips/12-initial-ajax.md deleted
-53
@@ -1,53 +0,0 @@
1 ----
2 -id: initial-ajax
3 -title: Load Initial Data via AJAX
4 -layout: tips
5 -permalink: tips/initial-ajax.html
6 -prev: dom-event-listeners.html
7 -next: false-in-jsx.html
8 ----
9 -
10 -Fetch data in `componentDidMount`. When the response arrives, store the data in state, triggering a render to update your UI.
11 -
12 -When fetching data asynchronously, use `componentWillUnmount` to cancel any outstanding requests before the component is unmounted.
13 -
14 -This example fetches the desired Github user's latest gist:
15 -
16 -```js
17 -var UserGist = React.createClass({
18 - getInitialState: function() {
19 - return {
20 - username: '',
21 - lastGistUrl: ''
22 - };
23 - },
24 -
25 - componentDidMount: function() {
26 - this.serverRequest = $.get(this.props.source, function (result) {
27 - var lastGist = result[0];
28 - this.setState({
29 - username: lastGist.owner.login,
30 - lastGistUrl: lastGist.html_url
31 - });
32 - }.bind(this));
33 - },
34 -
35 - componentWillUnmount: function() {
36 - this.serverRequest.abort();
37 - },
38 -
39 - render: function() {
40 - return (
41 - <div>
42 - {this.state.username}'s last gist is
43 - <a href={this.state.lastGistUrl}>here</a>.
44 - </div>
45 - );
46 - }
47 -});
48 -
49 -ReactDOM.render(
50 - <UserGist source="https://api.github.com/users/octocat/gists" />,
51 - mountNode
52 -);
53 -```
docs/tips/13-false-in-jsx.ko-KR.md deleted
-30
@@ -1,30 +0,0 @@
1 ----
2 -id: false-in-jsx-ko-KR
3 -title: JSX에서 False
4 -layout: tips
5 -permalink: tips/false-in-jsx-ko-KR.html
6 -prev: initial-ajax-ko-KR.html
7 -next: communicate-between-components-ko-KR.html
8 ----
9 -
10 -`false` 렌더링이 여러 상황에서 어떻게 다뤄지는지 봅시다.
11 -
12 -`id="false"`로 렌더링
13 -
14 -```js
15 -ReactDOM.render(<div id={false} />, mountNode);
16 -```
17 -
18 -문자열 `"false"`를 입력값으로
19 -
20 -```js
21 -ReactDOM.render(<input value={false} />, mountNode);
22 -```
23 -
24 -자식 없음
25 -
26 -```js
27 -ReactDOM.render(<div>{false}</div>, mountNode);
28 -```
29 -
30 -`div` 자식으로 쓰인 문자열 `"false"`를 렌더링하지 않은 것은 더 일반적인 사용 사례를 허용하기 위함입니다. `<div>{x > 1 && '하나 이상의 아이템을 가졌습니다.'}</div>`
docs/tips/13-false-in-jsx.md deleted
-30
@@ -1,30 +0,0 @@
1 ----
2 -id: false-in-jsx
3 -title: False in JSX
4 -layout: tips
5 -permalink: tips/false-in-jsx.html
6 -prev: initial-ajax.html
7 -next: communicate-between-components.html
8 ----
9 -
10 -Here's how `false` renders in different situations:
11 -
12 -Renders as `id="false"`:
13 -
14 -```js
15 -ReactDOM.render(<div id={false} />, mountNode);
16 -```
17 -
18 -String `"false"` as input value:
19 -
20 -```js
21 -ReactDOM.render(<input value={false} />, mountNode);
22 -```
23 -
24 -No child:
25 -
26 -```js
27 -ReactDOM.render(<div>{false}</div>, mountNode);
28 -```
29 -
30 -The reason why this one doesn't render as the string `"false"` as a `div` child is to allow the more common use-case: `<div>{x > 1 && 'You have more than one item'}</div>`.
docs/tips/14-communicate-between-components.ko-KR.md deleted
-39
@@ -1,39 +0,0 @@
1 ----
2 -id: communicate-between-components-ko-KR
3 -title: 컴포넌트간의 통신
4 -layout: tips
5 -permalink: tips/communicate-between-components-ko-KR.html
6 -prev: false-in-jsx-ko-KR.html
7 -next: expose-component-functions-ko-KR.html
8 ----
9 -
10 -부모-자식 통신을 위해서는, 간단히 [props를 넘기면 됩니다](/react/docs/multiple-components-ko-KR.html).
11 -
12 -자식-부모 통신을 위해서는:
13 -`GroceryList` 컴포넌트가 배열로 생성된 아이템 목록을 가지고 있다고 해봅시다. 목록의 아이템이 클릭되면 아이템의 이름이 보이길 원할 겁니다:
14 -
15 -```js
16 -var handleClick = function(i, items) {
17 - console.log('클릭한 아이템: ' + items[i]);
18 -}
19 -
20 -function GroceryList(props) {
21 - return (
22 - <div>
23 - {props.items.map(function(item, i) {
24 - return (
25 - <div onClick={handleClick.bind(this, i, props.items)} key={i}>{item}</div>
26 - );
27 - })}
28 - </div>
29 - );
30 -}
31 -
32 -ReactDOM.render(
33 - <GroceryList items={['사과', '바나나', '크랜베리']} />, mountNode
34 -);
35 -```
36 -
37 -`bind(this, arg1, arg2, ...)`의 사용을 확인하세요: 간단히 `handleClick`에 인자를 더 넘겼습니다. 이는 React의 새로운 컨셉이 아닙니다; 그냥 JavaScript죠.
38 -
39 -부모-자식 관계가 없는 두 컴포넌트간의 통신을 위해, 별도로 전역(global) 이벤트 시스템을 사용할 수 있습니다. `componentDidMount()`에서 이벤트를 구독하고, `componentWillUnmount()`에서 해제합니다. 이벤트를 받으면 `setState()`를 호출합니다. [Flux](https://facebook.github.io/flux/) 패턴은 이를 정리하는 방법 중 하나입니다.
docs/tips/14-communicate-between-components.md deleted
-39
@@ -1,39 +0,0 @@
1 ----
2 -id: communicate-between-components
3 -title: Communicate Between Components
4 -layout: tips
5 -permalink: tips/communicate-between-components.html
6 -prev: false-in-jsx.html
7 -next: expose-component-functions.html
8 ----
9 -
10 -For parent-child communication, simply [pass props](/react/docs/multiple-components.html).
11 -
12 -For child-parent communication:
13 -Say your `GroceryList` component has a list of items generated through an array. When a list item is clicked, you want to display its name:
14 -
15 -```js
16 -var handleClick = function(i, items) {
17 - console.log('You clicked: ' + items[i]);
18 -}
19 -
20 -function GroceryList(props) {
21 - return (
22 - <div>
23 - {props.items.map(function(item, i) {
24 - return (
25 - <div onClick={handleClick.bind(this, i, props.items)} key={i}>{item}</div>
26 - );
27 - })}
28 - </div>
29 - );
30 -}
31 -
32 -ReactDOM.render(
33 - <GroceryList items={['Apple', 'Banana', 'Cranberry']} />, mountNode
34 -);
35 -```
36 -
37 -Notice the use of `bind(this, arg1, arg2, ...)`: we're simply passing more arguments to `handleClick`. This is not a new React concept; it's just JavaScript.
38 -
39 -For communication between two components that don't have a parent-child relationship, you can set up your own global event system. Subscribe to events in `componentDidMount()`, unsubscribe in `componentWillUnmount()`, and call `setState()` when you receive an event. [Flux](https://facebook.github.io/flux/) pattern is one of the possible ways to arrange this.
docs/tips/15-expose-component-functions.ko-KR.md deleted
-59
@@ -1,59 +0,0 @@
1 ----
2 -id: expose-component-functions-ko-KR
3 -title: 컴포넌트 함수 드러내기
4 -layout: tips
5 -permalink: tips/expose-component-functions-ko-KR.html
6 -prev: communicate-between-components-ko-KR.html
7 -next: children-undefined-ko-KR.html
8 ----
9 -
10 -[컴포넌트간의 통신](/react/tips/communicate-between-components-ko-KR.html)을 위한 (일반적이지 않은) 또다른 방법이 있습니다: 단순히 부모의 호출을 위해 자식 컴포넌트의 메소드를 노출하는 겁니다.
11 -
12 -할일 목록을 생각해보죠. 아이템을 클릭하면 제거되고, 하나가 남으면 애니메이션 효과를 줍니다:
13 -
14 -```js
15 -var Todo = React.createClass({
16 - render: function() {
17 - return <div onClick={this.props.onClick}>{this.props.title}</div>;
18 - },
19 -
20 - //이 컴포넌트는 `ref` 어트리뷰트를 통해 부모에게 다뤄질 것입니다
21 - animate: function() {
22 - console.log('%s이 애니메이팅하는것처럼 속입니다', this.props.title);
23 - }
24 -});
25 -
26 -var Todos = React.createClass({
27 - getInitialState: function() {
28 - return {items: ['사과', '바나나', '크랜베리']};
29 - },
30 -
31 - handleClick: function(index) {
32 - var items = this.state.items.filter(function(item, i) {
33 - return index !== i;
34 - });
35 - this.setState({items: items}, function() {
36 - if (items.length === 1) {
37 - this.refs.item0.animate();
38 - }
39 - }.bind(this));
40 - },
41 -
42 - render: function() {
43 - return (
44 - <div>
45 - {this.state.items.map(function(item, i) {
46 - var boundClick = this.handleClick.bind(this, i);
47 - return (
48 - <Todo onClick={boundClick} key={i} title={item} ref={'item' + i} />
49 - );
50 - }, this)}
51 - </div>
52 - );
53 - }
54 -});
55 -
56 -ReactDOM.render(<Todos />, mountNode);
57 -```
58 -
59 -다른 방법으로는, `isLastUnfinishedItem` prop을 `todo`에 넘기는 방식으로 원하는 바를 이룰수도 있습니다. `componentDidUpdate`에서 prop을 확인하고 스스로 애니메이션 효과를 주는겁니다; 하지만 애니메이션 제어를 위해 다른 prop들을 넘기게 되면 이는 금새 난잡해질 수 있습니다.
docs/tips/15-expose-component-functions.md deleted
-59
@@ -1,59 +0,0 @@
1 ----
2 -id: expose-component-functions
3 -title: Expose Component Functions
4 -layout: tips
5 -permalink: tips/expose-component-functions.html
6 -prev: communicate-between-components.html
7 -next: children-undefined.html
8 ----
9 -
10 -There's another (uncommon) way of [communicating between components](/react/tips/communicate-between-components.html): simply expose a method on the child component for the parent to call.
11 -
12 -Say a list of todos, which upon clicking get removed. If there's only one unfinished todo left, animate it:
13 -
14 -```js
15 -var Todo = React.createClass({
16 - render: function() {
17 - return <div onClick={this.props.onClick}>{this.props.title}</div>;
18 - },
19 -
20 - //this component will be accessed by the parent through the `ref` attribute
21 - animate: function() {
22 - console.log('Pretend %s is animating', this.props.title);
23 - }
24 -});
25 -
26 -var Todos = React.createClass({
27 - getInitialState: function() {
28 - return {items: ['Apple', 'Banana', 'Cranberry']};
29 - },
30 -
31 - handleClick: function(index) {
32 - var items = this.state.items.filter(function(item, i) {
33 - return index !== i;
34 - });
35 - this.setState({items: items}, function() {
36 - if (items.length === 1) {
37 - this.refs.item0.animate();
38 - }
39 - }.bind(this));
40 - },
41 -
42 - render: function() {
43 - return (
44 - <div>
45 - {this.state.items.map(function(item, i) {
46 - var boundClick = this.handleClick.bind(this, i);
47 - return (
48 - <Todo onClick={boundClick} key={i} title={item} ref={'item' + i} />
49 - );
50 - }, this)}
51 - </div>
52 - );
53 - }
54 -});
55 -
56 -ReactDOM.render(<Todos />, mountNode);
57 -```
58 -
59 -Alternatively, you could have achieved this by passing the `todo` an `isLastUnfinishedItem` prop, let it check this prop in `componentDidUpdate`, then animate itself; however, this quickly gets messy if you pass around different props to control animations.
docs/tips/15-expose-component-functions.zh-CN.md deleted
-60
@@ -1,60 +0,0 @@
1 ----
2 -id: expose-component-functions-zh-CN
3 -title: 暴露组件函数
4 -layout: tips
5 -permalink: tips/expose-component-functions-zh-CN.html
6 -prev: communicate-between-components-zh-CN.html
7 -next: children-undefined-zh-CN.html
8 ----
9 -
10 -
11 -这是另外一种组件[通信的方法](/react/tips/communicate-between-components.html):在子组件中暴露出一个方法,可以让父组件去调。
12 -
13 -让我们看看这个todos的列表,在点击的时候就会被移除。如果只剩下最后一个未完成的待办事项,就执行animate函数:
14 -
15 -```js
16 -var Todo = React.createClass({
17 - render: function() {
18 - return <div onClick={this.props.onClick}>{this.props.title}</div>;
19 - },
20 -
21 - //this component will be accessed by the parent through the `ref` attribute
22 - animate: function() {
23 - console.log('Pretend %s is animating', this.props.title);
24 - }
25 -});
26 -
27 -var Todos = React.createClass({
28 - getInitialState: function() {
29 - return {items: ['Apple', 'Banana', 'Cranberry']};
30 - },
31 -
32 - handleClick: function(index) {
33 - var items = this.state.items.filter(function(item, i) {
34 - return index !== i;
35 - });
36 - this.setState({items: items}, function() {
37 - if (items.length === 1) {
38 - this.refs.item0.animate();
39 - }
40 - }.bind(this));
41 - },
42 -
43 - render: function() {
44 - return (
45 - <div>
46 - {this.state.items.map(function(item, i) {
47 - var boundClick = this.handleClick.bind(this, i);
48 - return (
49 - <Todo onClick={boundClick} key={i} title={item} ref={'item' + i} />
50 - );
51 - }, this)}
52 - </div>
53 - );
54 - }
55 -});
56 -
57 -ReactDOM.render(<Todos />, mountNode);
58 -```
59 -
60 -当然,你也可以通过在`todo`组件中的prop传递`isLastUnfinishedItem`,来让子组件在 `componentDidUpdate`中判断是否它是最后一个,来执行animate函数;但是,如果你通过不同的props值来控制的不同的动画,到最后可能会变得很混乱。
\ No newline at end of file
docs/tips/16-references-to-components.ko-KR.md deleted
-10
@@ -1,10 +0,0 @@
1 ----
2 -id: references-to-components-ko-KR
3 -title: 컴포넌트 참조
4 -layout: tips
5 -permalink: tips/references-to-components-ko-KR.html
6 -prev: expose-component-functions-ko-KR.html
7 -next: children-undefined-ko-KR.html
8 ----
9 -
10 -이 페이지는 이동되었습니다. [refs](/react/docs/more-about-refs-ko-KR.html)
docs/tips/16-references-to-components.md deleted
-10
@@ -1,10 +0,0 @@
1 ----
2 -id: references-to-components
3 -title: References to Components
4 -layout: tips
5 -permalink: tips/references-to-components.html
6 -prev: expose-component-functions.html
7 -next: children-undefined.html
8 ----
9 -
10 -This page has moved to: [refs](/react/docs/more-about-refs.html).
docs/tips/17-children-undefined.ko-KR.md deleted
-28
@@ -1,28 +0,0 @@
1 ----
2 -id: children-undefined-ko-KR
3 -title: 정의되지 않은 this.props.children
4 -layout: tips
5 -permalink: tips/children-undefined-ko-KR.html
6 -prev: expose-component-functions-ko-KR.html
7 -next: use-react-with-other-libraries-ko-KR.html
8 ----
9 -
10 -`this.props.children`을 통해 자식 컴포넌트에 접근할 수 없습니다. `this.props.children`은 소유자에 의해 자식이 **전달**되도록 지정합니다:
11 -
12 -```js
13 -var App = React.createClass({
14 - componentDidMount: function() {
15 - // 이는 `span`을 참조하지 않습니다!
16 - // 마지막 줄의 `<App></App>` 사이의 정의되지 않은 자식을 참조합니다.
17 - console.log(this.props.children);
18 - },
19 -
20 - render: function() {
21 - return <div><span/><span/></div>;
22 - }
23 -});
24 -
25 -ReactDOM.render(<App></App>, mountNode);
26 -```
27 -
28 -서브 컴포넌트(`span`)에 억세스하려면, [refs](/react/docs/more-about-refs.html)를 넣으세요.
docs/tips/17-children-undefined.md deleted
-28
@@ -1,28 +0,0 @@
1 ----
2 -id: children-undefined
3 -title: this.props.children undefined
4 -layout: tips
5 -permalink: tips/children-undefined.html
6 -prev: expose-component-functions.html
7 -next: use-react-with-other-libraries.html
8 ----
9 -
10 -You can't access the children of your component through `this.props.children`. `this.props.children` designates the children being **passed onto you** by the owner:
11 -
12 -```js
13 -var App = React.createClass({
14 - componentDidMount: function() {
15 - // This doesn't refer to the `span`s! It refers to the children between
16 - // last line's `<App></App>`, which are undefined.
17 - console.log(this.props.children);
18 - },
19 -
20 - render: function() {
21 - return <div><span/><span/></div>;
22 - }
23 -});
24 -
25 -ReactDOM.render(<App></App>, mountNode);
26 -```
27 -
28 -To access your own subcomponents (the `span`s), place [refs](/react/docs/more-about-refs.html) on them.
docs/tips/18-use-react-with-other-libraries.ko-KR.md deleted
-39
@@ -1,39 +0,0 @@
1 ----
2 -id: use-react-with-other-libraries-ko-KR
3 -title: React와 다른 라이브러리를 함께 사용하기
4 -layout: tips
5 -permalink: tips/use-react-with-other-libraries-ko-KR.html
6 -prev: children-undefined-ko-KR.html
7 -next: dangerously-set-inner-html-ko-KR.html
8 ----
9 -
10 -React만으로 만들 필요는 없습니다. 컴포넌트의 [생명주기 이벤트](/react/docs/component-specs-ko-KR.html#lifecycle-methods), 특히 `componentDidMount`와 `componentDidUpdate`는 다른 라이브러리들의 로직을 넣기에 좋은 장소입니다.
11 -
12 -```js
13 -var App = React.createClass({
14 - getInitialState: function() {
15 - return {myModel: new myBackboneModel({items: [1, 2, 3]})};
16 - },
17 -
18 - componentDidMount: function() {
19 - $(this.refs.placeholder).append($('<span />'));
20 - },
21 -
22 - componentWillUnmount: function() {
23 - // 정리는 여기서 합니다
24 - },
25 -
26 - shouldComponentUpdate: function() {
27 - // 이 컴포넌트를 다시는 업데이트하지 않도록 하죠.
28 - return false;
29 - },
30 -
31 - render: function() {
32 - return <div ref="placeholder"/>;
33 - }
34 -});
35 -
36 -ReactDOM.render(<App />, mountNode);
37 -```
38 -
39 -이 방식으로 별도의 [이벤트 리스너](/react/tips/dom-event-listeners-ko-KR.html)나 [이벤트 스트림](https://baconjs.github.io) 같은 것들을 더할 수 있습니다.
docs/tips/18-use-react-with-other-libraries.md deleted
-39
@@ -1,39 +0,0 @@
1 ----
2 -id: use-react-with-other-libraries
3 -title: Use React with Other Libraries
4 -layout: tips
5 -permalink: tips/use-react-with-other-libraries.html
6 -prev: children-undefined.html
7 -next: dangerously-set-inner-html.html
8 ----
9 -
10 -You don't have to go full React. The component [lifecycle events](/react/docs/component-specs.html#lifecycle-methods), especially `componentDidMount` and `componentDidUpdate`, are good places to put your other libraries' logic.
11 -
12 -```js
13 -var App = React.createClass({
14 - getInitialState: function() {
15 - return {myModel: new myBackboneModel({items: [1, 2, 3]})};
16 - },
17 -
18 - componentDidMount: function() {
19 - $(this.refs.placeholder).append($('<span />'));
20 - },
21 -
22 - componentWillUnmount: function() {
23 - // Clean up work here.
24 - },
25 -
26 - shouldComponentUpdate: function() {
27 - // Let's just never update this component again.
28 - return false;
29 - },
30 -
31 - render: function() {
32 - return <div ref="placeholder"/>;
33 - }
34 -});
35 -
36 -ReactDOM.render(<App />, mountNode);
37 -```
38 -
39 -You can attach your own [event listeners](/react/tips/dom-event-listeners.html) and even [event streams](https://baconjs.github.io) this way.
docs/tips/19-dangerously-set-inner-html.ko-KR.md deleted
-24
@@ -1,24 +0,0 @@
1 ----
2 -id: dangerously-set-inner-html-ko-KR
3 -title: Dangerously Set innerHTML
4 -layout: tips
5 -permalink: tips/dangerously-set-inner-html-ko-KR.html
6 -prev: children-undefined-ko-KR.html
7 ----
8 -
9 -부적절히 `innerHTML`를 사용하면 [사이트 간 스크립팅 (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting) 공격에 노출됩니다. 화면의 사용자 입력을 정제하다(sanitize) 오류를 내기 쉬우며, 적절하게 사용자의 입력을 정제하지 못하면 인터넷 상 [웹 취약점의 원인](https://www.owasp.org/index.php/Top_10_2013-Top_10)이 됩니다.
10 -
11 -우리 설계철학은 안전을 "쉽게" 얻는 것입니다. 개발자는 그들의 의도를 명시적으로 알려야만 "안전하지 않는" 연산을 할 수 있습니다. `dangerouslySetInnerHTML` prop의 이름은 의도적으로 무섭게 만든 것인데, prop 값은 문자열이 아닌 객체이고 정제된 데이터를 지정하는데 쓸 수 있습니다.
12 -
13 -보안 영향을 완전히 이해했다면, 데이터에서 나쁜 부분을 완전히 제거하고 `__html` 키와 정제된 값을 담은 새로운 객체를 만듭시다. 여기에 JSX 문법을 쓴 예제가 있습니다.
14 -
15 -```js
16 -function createMarkup() { return {__html: 'First &middot; Second'}; };
17 -<div dangerouslySetInnerHTML={createMarkup()} />
18 -```
19 -
20 -부주의하게 `<div dangerouslySetInnerHTML={getUsername()} />`를 쓰면 `getUsername()`가 `{__html: ''}` 객체 대신 순수 `문자열`을 반환하기 때문에 렌더링이 안되는 것이 요점입니다. `{__html:...}` 문장 속의 의도는 "type/taint" 같이 숙고하는 것입니다. 함수는 이 래퍼 객체를 사용하여 정제된 객체를 반환할 수 있는 데 뒤 따라오는 `dangerouslySetInnerHTML`에 표시할 데이터를 전달합니다. 이런 이유로 `<div dangerouslySetInnerHTML={{'{{'}}__html: getMarkup()}} />`의 형태의 코드를 작성하는 것은 추천하지 않습니다.
21 -
22 -이 기능성은 주로 DOM 문자열을 다루는 라이브러리와 협동하기 위한 목적으로 제공하며, 포함할 HTML은 잘 정제되어야 합니다. (예: XML 검증을 통과)
23 -
24 -더 완벽한 사용 예제를 보려면 [대문](/react/)의 최신 예제를 참조하세요.
docs/tips/19-dangerously-set-inner-html.md deleted
-24
@@ -1,24 +0,0 @@
1 ----
2 -id: dangerously-set-inner-html
3 -title: Dangerously Set innerHTML
4 -layout: tips
5 -permalink: tips/dangerously-set-inner-html.html
6 -prev: children-undefined.html
7 ----
8 -
9 -Improper use of the `innerHTML` can open you up to a [cross-site scripting (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting) attack. Sanitizing user input for display is notoriously error-prone, and failure to properly sanitize is one of the [leading causes of web vulnerabilities](https://www.owasp.org/index.php/Top_10_2013-Top_10) on the internet.
10 -
11 -Our design philosophy is that it should be “easy” to make things safe, and developers should explicitly state their intent when performing “unsafe” operations. The prop name `dangerouslySetInnerHTML` is intentionally chosen to be frightening, and the prop value (an object instead of a string) can be used to indicate sanitized data.
12 -
13 -After fully understanding the security ramifications and properly sanitizing the data, create a new object containing only the key `__html` and your sanitized data as the value. Here is an example using the JSX syntax:
14 -
15 -```js
16 -function createMarkup() { return {__html: 'First &middot; Second'}; };
17 -<div dangerouslySetInnerHTML={createMarkup()} />
18 -```
19 -
20 -The point being that if you unintentionally do say `<div dangerouslySetInnerHTML={getUsername()} />` it will not be rendered because `getUsername()` would return a plain `string` and not a `{__html: ''}` object. The intent behind the `{__html:...}` syntax is that it be considered a "type/taint" of sorts. Sanitized data can be returned from a function using this wrapper object, and this marked data can subsequently be passed into `dangerouslySetInnerHTML`. For this reason, we recommend against writing code of the form `<div dangerouslySetInnerHTML={{'{{'}}__html: getMarkup()}} />`.
21 -
22 -This functionality is mainly provided for cooperation with DOM string manipulation libraries, so the HTML provided must be well-formed (ie., pass XML validation).
23 -
24 -For a more complete usage example, refer to the last example on the [front page](/react/).
docs/tutorial/tutorial.md new
+511
@@ -0,0 +1,511 @@
1 +---
2 +id: tutorial
3 +title: "Tutorial: Intro To React"
4 +layout: tutorial
5 +sectionid: tutorial
6 +permalink: /tutorial/tutorial.html
7 +redirect_from: "/docs/tutorial.html"
8 +redirect_from: "/docs/why-react.html"
9 +---
10 +
11 +## What We're Building
12 +
13 +Today, we're going to build an interactive tic-tac-toe game. We'll assume some familiarity with HTML and JavaScript but you should be able to follow along even if you haven't used them before.
14 +
15 +If you like, you can check out the final result here: <a href="https://s.codepen.io/ericnakagawa/debug/ALxakj" target="_blank">Final Result</a>. Try playing the game. You can also click on a link in the move list to go "back in time" and see what the board looked like just after that move was made.
16 +
17 +## What is React?
18 +
19 +React is a declarative, efficient, and flexible JavaScript library for building user interfaces.
20 +
21 +React has a few different kinds of components, but we'll start with React.Component subclasses:
22 +
23 +```javascript
24 +class ShoppingList extends React.Component {
25 + render() {
26 + return (
27 + <div className="shopping-list">
28 + <h1>Shopping List for {this.props.name}</h1>
29 + <ul>
30 + <li>Instagram</li>
31 + <li>WhatsApp</li>
32 + <li>Oculus</li>
33 + </ul>
34 + </div>
35 + );
36 + }
37 +}
38 +
39 +// Example usage: <ShoppingList name="Mark" />
40 +```
41 +
42 +We'll get to the funny XML-like tags in a second. Your components tell React what you want to render – then React will efficiently update and render just the right components when your data changes.
43 +
44 +Here, ShoppingList is a **React component class**, or **React component type**. A component takes in parameters, called `props`, and returns a hierarchy of views to display via the `render` method.
45 +
46 +The `render` method return a *description* of what you want to render, and then React takes that description and renders it to the screen. In particular, `render` returns a **React element**, which is a lightweight description of what to render. Most React developers use a special syntax called JSX which makes it easier to write these structures. The `<div />` syntax is transformed at build time to `React.createElement('div')`. The example above is equivalent to:
47 +
48 +```javascript
49 +return React.createElement('div', {className: 'shopping-list'},
50 + React.createElement('h1', ...),
51 + React.createElement('ul', ...)
52 +);
53 +```
54 +
55 +You can put any JavaScript expression within braces inside JSX. Each React element is a real JavaScript object that you can store in a variable or pass around your program.
56 +
57 +The `ShoppingList` component only renders built-in DOM components, but you can compose custom React components just as easily, by writing `<ShoppingList />`. Each component is encapsulated so it can operate independently, which allows you to build complex UIs out of simple components.
58 +
59 +## Getting Started
60 +
61 +Start with this example: <a href="https://codepen.io/ericnakagawa/pen/vXpjwZ?editors=0010" target="_blank">Starter Code</a>.
62 +
63 +It contains the shell of what we're building today. We've provided the styles so you only need to worry about the JavaScript.
64 +
65 +In particular, we have three components:
66 +
67 +* Square
68 +* Board
69 +* Game
70 +
71 +The Square component renders a single `<div>`, the Board renders 9 squares, and the Game component renders a board with some placeholders that we'll fill in later. None of the components are interactive at this point.
72 +
73 +(The end of the JS file also defines a helper function `calculateWinner` that we'll use later.)
74 +
75 +## Passing Data Through Props
76 +
77 +Just to get our feet wet, let's try passing some data from the Board component to the Square component. In Board's `renderSquare` method, change the code to return `<Square value={i} />` then change Square's render method to show that value by replacing `{/* TODO */}` with `{this.props.value}`.
78 +
79 +Before:
80 +
81 +![React Devtools](/react/img/tutorial/tictac-empty.png)
82 +
83 +After: You should see a number in each square in the rendered output.
84 +
85 +![React Devtools](/react/img/tutorial/tictac-numbers.png)
86 +
87 +##An Interactive Component
88 +
89 +Let's make the Square component fill in an "X" when you click it. Try changing the tag returned in the `render()` function of the `Square` class to:
90 +
91 +```html
92 +<button className="square" onClick={() => alert('click')}>
93 +```
94 +
95 +This uses the new JavaScript arrow function syntax. If you click on a square now, you should get an alert in your browser.
96 +
97 +React components can have state by setting `this.state` in the constructor, which should be considered private to the component. Let's store the current value of the square in state, and change it when the square is clicked. First, add a constructor to the class to initialize the state:
98 +
99 +```javascript
100 +class Square extends React.Component {
101 + constructor() {
102 + super();
103 + this.state = {
104 + value: null,
105 + };
106 + }
107 + ...
108 +}
109 +```
110 +
111 +In JavaScript classes, you need to explicitly call `super();` when defining the constructor of a subclass.
112 +
113 +Now change the `render` method to display `this.state.value` instead of `this.props.value`, and change the event handler to be `() => this.setState({value: 'X'})` instead of the alert:
114 +
115 +```javascript
116 +<button className="square" onClick={() => this.setState({value: 'X'})}>
117 + {this.state.value}
118 +</button>
119 +```
120 +
121 +Whenever `this.setState` is called, an update to the component is scheduled, causing React to merge in the passed state update and rerender the component along with its descendants. When the component rerenders, `this.state.value` will be `'X'` so you'll see an X in the grid.
122 +
123 +If you click on any square, an X should show up in it.
124 +
125 +## Developer Tools
126 +
127 +The React Devtools extension for [Chrome](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en) and [Firefox](https://addons.mozilla.org/en-US/firefox/addon/react-devtools/) lets you inspect a React component tree in your browser devtools.
128 +
129 +<img src="/react/img/tutorial/devtools.png" alt="React Devtools" style="max-width: 100%">
130 +
131 +It lets you inspect the props and state of any of the components in your tree.
132 +
133 +It doesn't work great on CodePen because of the multiple frames, but if you log in to CodePen and confirm your email (for spam prevention), you can go to Change View > Debug to open your code in a new tab, then the devtools will work. It's fine if you don't want to do this now, but it's good to know that it exists.
134 +
135 +## Lifting State Up
136 +
137 +We now have the basic building blocks for a tic-tac-toe game. But right now, the state is encapsulated in each Square component. To make a fully-working game, we now need to check if one player has won the game, and alternate placing X and O in the squares. To check if someone has won, we'll need to have the value of all 9 squares in one place, rather than split up across the Square components.
138 +
139 +You might think that Board should just inquire what the current state of each Square is. Although it is technically possible to do this in React, it is discouraged because it tends to make code difficult to understand, more brittle, and harder to refactor.
140 +
141 +Instead, the best solution here is to store this state in the Board component instead of in each Square – and the Board component can tell each Square what to display, like how we made each square display its index earlier.
142 +
143 +**When you want to aggregate data from multiple children or to have two child components communicate with each other, move the state upwards so that it lives in the parent component. The parent can then pass the state back down to the children via props, so that the child components are always in sync with each other and with the parent.**
144 +
145 +Pulling state upwards like this is common when refactoring React components, so let's take this opportunity to try it out. Add an initial state for Board containing an array with 9 nulls, corresponding to the 9 squares:
146 +
147 +```javascript
148 +class Board extends React.Component {
149 + constructor() {
150 + super();
151 + this.state = {
152 + squares: Array(9).fill(null),
153 + };
154 + }
155 +}
156 +```
157 +
158 +We'll fill it in later so that a board looks something like
159 +
160 +```javascript
161 +[
162 + 'O', null, 'X',
163 + 'X', 'X', 'O',
164 + 'O', null, null,
165 +]
166 +```
167 +
168 +Pass the value of each square down:
169 +
170 +```javascript
171 +renderSquare(i) {
172 + return <Square value={this.state.squares[i]} />;
173 +}
174 +```
175 +
176 +And change Square to use `this.props.value` again. Now we need to change what happens when a square is clicked. The Board component now stores which squares are filled, which means we need some way for Square to update the state of Board. Since component state is considered private, we can't update Board's state directly from Square. The usual pattern here is pass down a function from Board to Square that gets called when the square is clicked. Change `renderSquare` again so that it reads:
177 +
178 +```javascript
179 +return <Square value={this.state.squares[i]} onClick={() => this.handleClick(i)} />;
180 +```
181 +
182 +Now we're passing down two props from Board to Square: `value` and `onClick`. The latter is a function that Square can call. So let's do that by changing `render` in Square to have:
183 +
184 +```javascript
185 +<button className="square" onClick={() => this.props.onClick()}>
186 +```
187 +
188 +This means that when the square is clicked, it calls the onClick function that was passed by the parent. The `onClick` doesn't have any special meaning here, but it's popular to name handler props starting with `on` and their implementations with `handle`. Try clicking a square – you should get an error because we haven't defined `handleClick` yet. Add it to the Board class:
189 +
190 +```javascript
191 +handleClick(i) {
192 + const squares = this.state.squares.slice();
193 + squares[i] = 'X';
194 + this.setState({squares: squares});
195 +}
196 +```
197 +
198 +We call `.slice()` to copy the `squares` array instead of mutating the existing array. Jump ahead a [section](/react/tutorial/tutorial.html#why-immutability-is-important) to learn why immutability is important.
199 +
200 +Now you should be able to click in squares to fill them again, but the state is stored in the Board component instead of in each Square, which lets us continue building the game. Note how whenever Board's state changes, the Square components rerender automatically.
201 +
202 +Square no longer keeps its own state; it receives its value from its parent `Board` and informs its parent when it's clicked. We call components like this **controlled components**.
203 +
204 +## Why Immutability Is Important
205 +
206 +In the previous code example, I suggest using the `.slice()` operator to copy the `squares` array prior to making changges and to prevent mutating the existing array. Let's talk about what this means and why it an important concept to learn.
207 +
208 +There are generally two ways for changing data. The first, and most common method in past, has been to *mutate* the data by directly changing the values of a variable. The second method is to replace the data with a new copy of the object that also includes desired changes.
209 +
210 +#### Data change with mutation
211 +```javascript
212 +var player = {score: 1}
213 +player.score = 2 // same object mutated {score: 2}
214 +```
215 +
216 +#### Data change without mutation
217 +```javascript
218 +var player = {score: 1}
219 +player = {...player, score: 2} // new object not mutated {score: 2}
220 +```
221 +
222 +The end result is the same but by not mutating (or changing the underlying data) directly we now have an added benefit that can help us increase component and overall application performance.
223 +
224 +#### Tracking Changes
225 +
226 +Determining if a mutated object has changed is complex because changes are made directly to the object. This then requires comparing the current object to a previous copy, traversing the entire object tree, and comparing each variable and value. This process can become increasingly complex.
227 +
228 +Determining how a immutable object has changed is considerably easier. If the object being referenced is different from before, then the object has changed. That's it.
229 +
230 +### Determining When To Re-render in React
231 +
232 +The biggest benefit of immutability in React comes when you build simple _pure components_. Since immutable data can more easily determine if changes have been made it also helps to determine when a component requires being re-rendered.
233 +
234 +To learn how you can build *pure components* take a look at [shouldComponentUpdate()](https://facebook.github.io/react/docs/update.html). Also, take a look at the [immutability.js](https://facebook.github.io/immutable-js/) library to strictly enforce immutable data.
235 +
236 +## Functional Components
237 +
238 +Back to our project, you can now delete the `constructor` from `Square`; we won't need it any more. In fact, React supports a simpler syntax called **stateless functional components** for component types like Square that only consist of a `render` method. Rather than define a class extending React.Component, simply write a function that takes props and returns what should be rendered:
239 +
240 +```javascript
241 +function Square(props) {
242 + return (
243 + <button className="square" onClick={() => props.onClick()}>
244 + {props.value}
245 + </button>
246 + );
247 +}
248 +```
249 +
250 +You'll need to change `this.props` to `props` both times it appears. Many components in your apps will be able to written as functional components: these components tend to be easier to write and React will optimize them more in the future.
251 +
252 +## Taking Turns
253 +
254 +An obvious defect in our game is that only X can play. Let's fix that.
255 +
256 +Let's default the first move to be by 'X'. Modify our starting state in our `Game` constructor.
257 +
258 +```javascript
259 +class Board extends React.Component {
260 + constructor() {
261 + super();
262 + this.state = {
263 + ...
264 + xIsNext: true,
265 + };
266 + }
267 +```
268 +
269 +Each time we move we shall toggle `xIsNext` by flipping the boolean value and saving the state. Now update our `handleClick` function to flip the value of `xIsNext`.
270 +
271 +```javascript
272 +handleClick(i) {
273 + const squares = this.state.squares.slice();
274 + squares[i] = this.state.xIsNext ? 'X' : 'O';
275 + this.setState({
276 + squares: squares,
277 + xIsNext: !this.state.xIsNext,
278 + });
279 +}
280 +```
281 +
282 +Now X and O take turns. Next, change the "status" text in Board's `render` so that it also displays who is next.
283 +
284 +## Declaring a Winner
285 +
286 +Let's show when the game is won. A `calculateWinner(squares)` helper function that takes the list of 9 values has been provided for you at the bottom of the file. You can call it in Board's `render` function to check if anyone has won the game and make the status text show "Winner: [X/O]" when someone wins:
287 +
288 +```javascript
289 +render() {
290 + const winner = calculateWinner(this.state.squares);
291 + let status;
292 + if (winner) {
293 + status = 'Winner: ' + winner;
294 + } else {
295 + status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
296 + }
297 + ...
298 +}
299 +```
300 +
301 +You can now change `handleClick` to return early and ignore the click if someone has already won the game or if a square is already filled:
302 +
303 +```javascript
304 +handleClick(i) {
305 + const squares = this.state.squares.slice();
306 + if (calculateWinner(squares) || squares[i]) {
307 + return;
308 + }
309 + ...
310 +}
311 +```
312 +
313 +Congratulations! You now have a working tic-tac-toe game. And now you know the basics of React. So *you're* probably the real winner here.
314 +
315 +## Storing a History
316 +
317 +Let's make it possible to revisit old states of the board so we can see what it looked like after any of the previous moves. We're already creating a new `squares` array each time a move is made, which means we can easily store the past board states simultaneously.
318 +
319 +Let's plan to store an object like this in state:
320 +
321 +```javascript
322 +history = [
323 + {
324 + squares: [null x 9]
325 + },
326 + {
327 + squares: [... x 9]
328 + },
329 + ...
330 +]
331 +```
332 +
333 +We'll want the top-level `Game` component to be responsible for displaying the list of moves. So just as we pulled the state up before from `Square` into `Board`, let's now pull it up again from `Board` into `Game` – so that we have all the information we need at the top level.
334 +
335 +First, set up the initial state for `Game`:
336 +
337 +```javascript
338 +class Game extends React.Component {
339 + constructor() {
340 + super();
341 + this.state = {
342 + history: [{
343 + squares: Array(9).fill(null)
344 + }],
345 + xIsNext: true
346 + };
347 + }
348 + ...
349 +}
350 +```
351 +
352 +Then remove the constructor and change `Board` so that it takes `squares` via props and has its own `onClick` prop specified by `Game`, like the transformation we made for `Square` and `Board` earlier. You can pass the location of each square into the click handler so that we still know which square was clicked:
353 +
354 +```javascript
355 +return <Square value={this.props.squares[i]} onClick={() => this.props.onClick(i)} />;
356 +```
357 +
358 +`Game`'s `render` should look at the most recent history entry and can take over calculating the game status:
359 +
360 +```javascript
361 +const history = this.state.history;
362 +const current = history[history.length - 1];
363 +const winner = calculateWinner(current.squares);
364 +
365 +let status;
366 +if (winner) {
367 + status = 'Winner: ' + winner;
368 +} else {
369 + status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
370 +}
371 +...
372 +<div className="game-board">
373 + <Board
374 + squares={current.squares}
375 + onClick={() => this.handleClick(i)}
376 + />
377 +</div>
378 +<div className="game-info">
379 + <div>{status}</div>
380 + <ol>{/* TODO */}</ol>
381 +</div>
382 +```
383 +
384 +Its `handleClick` can push a new entry onto the stack by concatenating the new history entry to make a new history array:
385 +
386 +```javascript
387 +handleClick(i) {
388 + var history = this.state.history;
389 + var current = history[history.length - 1];
390 + const squares = current.squares.slice();
391 + if (calculateWinner(squares) || squares[i]) {
392 + return;
393 + }
394 + squares[i] = this.state.xIsNext(current.squares) ? 'X' : 'O';
395 + this.setState({
396 + history: history.concat([{
397 + squares: squares
398 + }]),
399 + xIsNext: !this.state.xIsNext,
400 + });
401 +}
402 +```
403 +
404 +At this point, Board only needs `renderStep` and `render`; the state initialization and click handler should both live in Game.
405 +
406 +## Showing the Moves
407 +
408 +Let's show the previous moves made in the game so far. We learned earlier that React elements are first-class JS objects and we can store them or pass them around. To render multiple items in React, we pass an array of React elements. The most common way to build that array is to map over your array of data. Let's do that in the `render` method of Game:
409 +
410 +```javascript
411 +const moves = history.map((step, move) => {
412 + const desc = move ?
413 + 'Move #' + move :
414 + 'Game start';
415 + return (
416 + <li key={move}>
417 + <a href="#" onClick={() => this.jumpTo(move)}>{desc}</a>
418 + </li>
419 + );
420 +});
421 +...
422 +<ol>{moves}</ol>
423 +```
424 +
425 +For each step in the history, we create a list item `<li>` with a link `<a>` inside it that goes nowhere (`href="#"`) but has a click handler which we'll implement shortly. With this code, you should see a list of the moves that have been made in the game, along with a warning that says
426 +
427 +> Warning:
428 +> Each child in an array or iterator should have a unique "key" prop. Check the render method of "Game".
429 +
430 +Let's talk about what that warning means.
431 +
432 +## Keys
433 +
434 +When you render a list of items, React always stores some info about each item in the list. If you render a component that has state, that state needs to be stored – and regardless of how you implement your components, React stores a reference to the backing native views.
435 +
436 +When you update that list, React needs to determine what has changed. You could've added, removed, rearranged, or updated items in the list.
437 +
438 +Imagine transitioning from
439 +
440 +```html
441 +<li>Alexa: 7 tasks left</li>
442 +<li>Ben: 5 tasks left</li>
443 +```
444 +
445 +to
446 +
447 +```html
448 +<li>Ben: 9 tasks left</li>
449 +<li>Claudia: 8 tasks left</li>
450 +<li>Alexa: 5 tasks left</li>
451 +```
452 +
453 +To a human eye, it looks likely that Alexa and Ben swapped places and Claudia was added – but React is just a computer program and doesn't know what you intended it to do. As a result, React asks you to specify a *key* property on each element in a list, a string to differentiate each component from its siblings. In this case, `alexa`, `ben`, `claudia` might be sensible keys; if the items correspond to objects in a database, the database ID is usually a good choice:
454 +
455 +```html
456 +<li key={user.id}>{user.name}: {user.taskCount} tasks left</li>
457 +```
458 +
459 +`key` is a special property that's reserved by React (along with `ref`, a more advanced feature). When an element is created, React pulls off the `key` property and stores the key directly on the returned element. Even though it may look like it is part of props, it cannot be referenced with `this.props.key`. React uses the key automatically while deciding which children to update; there is no way for a component to inquire about its own key.
460 +
461 +When a list is rerendered, React takes each element in the new version and looks for one with a matching key in the previous list. When a key is added to the set, a component is created; when a key is removed, a component is destroyed. Keys tell React about the identity of each component, so that it can maintain the state across rerenders. If you change the key of a component, it will be completely destroyed and recreated with a new state.
462 +
463 +**It's strongly recommended that you assign proper keys whenever you build dynamic lists.** If you don't have an appropriate key handy, you may want to consider restructuring your data so that you do.
464 +
465 +If you don't specify any key, React will warn you and fall back to using the array index as a key – which is not the correct choice if you ever reorder elements in the list or add/remove items anywhere but the bottom of the list. Explicitly passing `key={i}` silences the warning but has the same problem so isn't recommended in most cases.
466 +
467 +Component keys don't need to be globally unique, only unique relative to the immediate siblings.
468 +
469 +## Implementing Time Travel
470 +
471 +For our move list, we already have a unique ID for each step: the number of the move when it happened. Add the key as `<li key={move}>` and the key warning should disappear.
472 +
473 +Clicking any of the move links throws an error because `jumpTo` is undefined. Let's add a new key to Game's state to indicate which step we're currently viewing. First, add `stepNumber: 0` to the initial state, then have `jumpTo` update that state.
474 +
475 +We also want to update `xIsNext`. We set `xIsNext` to true if the index of the move number is an even number.
476 +
477 +```javascript
478 +jumpTo(step) {
479 + this.setState({
480 + stepNumber: step,
481 + xIsNext: (step % 2) ? false : true,
482 + });
483 +}
484 +```
485 +
486 +Then update `stepNumber` when a new move is made by adding `stepNumber: history.length` to the state update in `handleClick`. Now you can modify `render` to read from that step in the history:
487 +
488 +```javascript
489 +const current = history[this.state.stepNumber];
490 +```
491 +
492 +If you click any move link now, the board should immediately update to show what the game looked like at that time. You may also want to update `handleClick` to be aware of `stepNumber` when reading the current board state so that you can go back in time then click in the board to create a new entry. (Hint: It's easiest to `.slice()` off the extra elements from `history` at the very top of `handleClick`.)
493 +
494 +## Wrapping Up
495 +
496 +Now, you've made a tic-tac-toe game that:
497 +
498 +* lets you play tic-tac-toe,
499 +* indicates when one player has won the game,
500 +* stores the history of moves during the game,
501 +* allows players to jump back in time to see older versions of the game board.
502 +
503 +Nice work! We hope you now feel like you have a decent grasp on how React works.
504 +
505 +If you have extra time or want to practice your new skills, here are some ideas for improvements you could make, listed in order of increasing difficulty:
506 +
507 +1. Display the move locations in the format "(1, 3)" instead of "6".
508 +2. Bold the currently-selected item in the move list.
509 +3. Rewrite Board to use two loops to make the squares instead of hardcoding them.
510 +4. Add a toggle button that lets you sort the moves in either ascending or descending order.
511 +5. When someone wins, highlight the three squares that caused the win.