Compare commits

...

102 Commits

Author SHA1 Message Date
Paul O’Shannessy
c389c1def5 v0.14.3 2015-11-18 18:08:52 -08:00
Paul O’Shannessy
1cef6ebabf Update readme for 0.14.3 2015-11-18 18:03:41 -08:00
Paul O’Shannessy
f92a630737 v0.14.3 blog post 2015-11-18 18:01:07 -08:00
Paul O’Shannessy
55b6839684 Changelog for 0.14.3 2015-11-18 13:18:26 -08:00
Paul O’Shannessy
e6f8ad33cf Merge pull request #5501 from zpao/release-react-dom-server
Make sure react-dom-server is shipped in release process
(cherry picked from commit d1eba1f78c)
2015-11-18 13:18:26 -08:00
Paul O’Shannessy
c806ed1128 Merge pull request #5496 from zpao/reactdomserverfollowup
Followup to #5381
(cherry picked from commit 60cba8fcf7)
2015-11-18 13:18:26 -08:00
Paul O’Shannessy
294b50a695 Merge pull request #5381 from kevinrobinson/react-dom-server-package
Add additional secret property to build artifact for react-dom-server
(cherry picked from commit c07b304c76)
2015-11-18 13:18:26 -08:00
Ben Alpert
22c9562cd9 Merge pull request #5330 from laskos/fix-shallow-rendering-function-refs
Fix shallow renderer with ref as function
(cherry picked from commit 1a6d1e74e0)
2015-11-18 13:18:26 -08:00
Paul O’Shannessy
cde2de3ce7 Merge pull request #5431 from zpao/license-in-packages
Ensure license and patents files are packaged for npm
(cherry picked from commit fc245226f9)
2015-11-18 12:29:36 -08:00
Paul O’Shannessy
061725c9b6 Merge pull request #5417 from zpao/ol-reversed
Support reversed for <ol>s
(cherry picked from commit e7a5a98044)
2015-11-18 12:29:17 -08:00
Paul O’Shannessy
ed11bdc5bf Merge pull request #5442 from nickclaw/patch-1
Allow nonce attribute
(cherry picked from commit 575d1a5093)
2015-11-18 12:19:13 -08:00
Jim
319c5c4453 Merge pull request #5391 from zjjw/transition_timeouts
Clear transition timeouts when component unmounts. Fixes #4876
(cherry picked from commit 59dd7b33ee)
2015-11-18 12:17:38 -08:00
Paul O’Shannessy
19678baa1a Merge pull request #5396 from zpao/packagejsons
Improve npm packages' metadata
(cherry picked from commit 6d5fe44c86)
2015-11-18 12:16:42 -08:00
Paul O’Shannessy
a43dfdc33d Bump version for 0.14.3 dev 2015-11-18 12:08:51 -08:00
Paul O’Shannessy
9265032a12 Merge pull request #5445 from yangshun/controlled-components-in-tutorial
Use controlled components in tutorial
(cherry picked from commit 904e9e3ea6)
2015-11-17 23:01:09 -08:00
Jim
36db2aeeb0 Merge pull request #2774 from jimfb/webcomponents
Added info (example+doc) about react with webcomponents
(cherry picked from commit 80bcc519d7)
2015-11-17 23:00:58 -08:00
Paul O’Shannessy
ca8ad7ff8e [docs] Properly fix Korean docs
(cherry picked from commit 034cfc96c7)
2015-11-12 16:00:57 -08:00
Paul O’Shannessy
30ec56a027 [docs] Use updated Korean translation
See #5456 for details

(cherry picked from commit 72d9a8bc15)
2015-11-12 14:27:31 -08:00
Paul O’Shannessy
5e9f00a4b6 Merge pull request #5456 from hugo-agbonon/fix-classname-manipulation-doc
Revert class name manipulation doc to english
(cherry picked from commit 2d5612913f)
2015-11-12 14:27:26 -08:00
Paul O’Shannessy
a23bab0cf5 Merge pull request #5444 from zpao/tutorial-ids-for-data
[tutorial] Use ids in comments data
(cherry picked from commit 09b7ff1fc4)
2015-11-12 14:27:21 -08:00
Paul O’Shannessy
6bf6beb2d2 Merge pull request #5416 from bbrooks/undo-optimistic-update-on-error
Reset state if comment submit fails
(cherry picked from commit eecd2953cd)
2015-11-12 14:27:17 -08:00
Jim
c796629e66 Merge pull request #5412 from yangshun/document-next-context
Add more documentation to Context page
(cherry picked from commit 4cb210a9da)
2015-11-12 14:27:11 -08:00
Jim
3eed5deead Merge pull request #5403 from yuyokk/patch-1
Clarify note about stable keys
(cherry picked from commit d6a547f793)
2015-11-10 10:44:16 -08:00
Jim
3b97d5e30c Merge pull request #5424 from stowball/animation-docs-whitespace
Removed unnecessary whitespace before closing bracket
(cherry picked from commit a88c39be86)
2015-11-10 10:44:09 -08:00
Ben Alpert
fd05a6ee7d Merge pull request #5287 from benhalpern/patch-1
Updated conference page
(cherry picked from commit 99fbde54a1)
2015-11-10 10:44:05 -08:00
Jim
17761fae9b Merge pull request #5231 from davidkpiano/patch-1
Updating "JSX Gotchas" docs for Custom Attributes
(cherry picked from commit 22b8952fbf)
2015-11-10 10:43:58 -08:00
Jim
34bb99b07f Merge pull request #5385 from marocchino/update-korean
Update korean translation to 84af306
(cherry picked from commit 4fae036269)
2015-11-10 10:43:53 -08:00
Jim
4fda3eb9da Merge pull request #5372 from csbok/patch-1
Update getting-started.ko-KR.md
(cherry picked from commit 84af306044)
2015-11-10 10:43:48 -08:00
Ben Alpert
c6c3c0e255 Merge pull request #5356 from rpominov/patch-1
fix shallowRenderer.getRenderOutput() return type in docs
(cherry picked from commit 17289020f7)
2015-11-10 10:43:41 -08:00
Paul O’Shannessy
807c555c77 Merge pull request #5370 from zpao/babel6docs
Update docs for Babel 6
(cherry picked from commit b9371bc216)
2015-11-02 17:01:35 -08:00
Paul O’Shannessy
fdf6f6bbb0 Update website for 0.14.2 2015-11-02 11:50:20 -08:00
Paul O’Shannessy
5a2312c8e5 v0.14.2 2015-11-02 11:45:57 -08:00
Paul O’Shannessy
01622a4442 Update readme for 0.14.2 2015-11-02 11:38:29 -08:00
Paul O’Shannessy
a4fd08973b Blog post for 0.14.2 2015-11-02 11:34:37 -08:00
Paul O’Shannessy
c2dd57c6a6 Changelog for 0.14.2 2015-11-02 11:34:36 -08:00
Paul O’Shannessy
db23e49467 Update haste package version for branch 2015-11-02 11:27:53 -08:00
Paul O’Shannessy
3117584e0e Merge pull request #5367 from spicyj/haste-manifest
Add package.json for react-haste package
(cherry picked from commit 72a11421d2)
2015-11-02 11:27:53 -08:00
Paul O’Shannessy
26258313cd Merge pull request #5366 from zpao/react-dom-peer-dep
Make React a peerDep of react-dom
(cherry picked from commit a82400faa2)
2015-11-02 11:27:53 -08:00
Jim
d602f1d3fb Merge pull request #5093 from jimfb/avoid-children-to-string-coercion
Should not coerce children prop on custom elements to a string.  Fixes #5088
(cherry picked from commit a2d26c82ea)
2015-11-02 10:08:26 -08:00
Jim
c181b824ca Merge pull request #5341 from zpao/domprop-integrity
Add integrity to HTML property config
(cherry picked from commit 0c790baf31)
2015-11-02 10:04:44 -08:00
Paul O’Shannessy
d6100a703f Merge pull request #5328 from zpao/non-native-event-name-dispatch
Use a custom event type for our event dispatching in ReactErrorUtils
(cherry picked from commit 12c214a992)
2015-11-02 10:04:39 -08:00
Paul O’Shannessy
afef42e377 Merge pull request #5327 from zpao/definepropgetter
Use a getter for canDefineProperty check.
(cherry picked from commit 606aa61209)
2015-11-02 10:04:33 -08:00
Paul O’Shannessy
24059873ac Bump version for 0.14.2-alpha 2015-11-02 10:03:45 -08:00
Paul O’Shannessy
bac2462dd5 Merge pull request #5348 from hzoo/patch-2
add docs for babel 6
(cherry picked from commit 88bae3fb73)
2015-10-31 12:20:24 -07:00
Paul O’Shannessy
878482154e Merge pull request #5235 from wincent/update-blog-syntax
Update syntax in older Relay blog post that may be causing confusion
(cherry picked from commit c35b4384f7)
2015-10-31 12:20:18 -07:00
Jim
bfba064631 Merge pull request #5316 from Third9/master
update Korean docs to 0.14
(cherry picked from commit fbf4cbbae6)
2015-10-31 12:20:13 -07:00
Jim
0f6a151650 Merge pull request #5317 from nickbalestra/patch-1
Update 02.1-jsx-in-depth.md
(cherry picked from commit 01341480c2)
2015-10-31 12:20:03 -07:00
Paul O’Shannessy
f0782e2b2e Update website for 0.14.1 2015-10-28 14:24:49 -07:00
Paul O’Shannessy
b247f68b33 0.14.1 2015-10-28 14:21:05 -07:00
Paul O’Shannessy
6e2450e8f2 0.14.1 blog post 2015-10-28 14:03:59 -07:00
Paul O’Shannessy
c2dde8df0b Update readme for 0.14.1 2015-10-28 14:03:58 -07:00
Paul O’Shannessy
aaf8f870cb Update changelog for 0.14.1 2015-10-28 14:03:58 -07:00
Paul O’Shannessy
4952cd00d4 Merge pull request #5304 from evanvosberg/master
Add non-standard property for supporting Safari mask-icon.
(cherry picked from commit 2c176da7e8)
2015-10-28 12:44:30 -07:00
Ben Alpert
eadbf33296 Merge pull request #5237 from spicyj/gh-5125
Make sure top-level callback has correct context
(cherry picked from commit b0a7a00dba)
2015-10-28 12:44:27 -07:00
Paul O’Shannessy
12cafa7e00 Merge pull request #5297 from quadrupleslap/master
Mangle __html in prop validation.
(cherry picked from commit 517872817f)
2015-10-28 12:42:15 -07:00
Paul O’Shannessy
090c2dd833 Merge pull request #5250 from conorhastings/track-default-property
add default attribute for use with track element
(cherry picked from commit 4d41cf740a)
2015-10-28 12:42:15 -07:00
Ben Alpert
c469697ad7 Merge pull request #5263 from spicyj/npmreactreadme
Update addons paths in npm react README
(cherry picked from commit 8aaa66c292)
2015-10-28 12:42:15 -07:00
Paul O’Shannessy
d8a9cd365c Merge pull request #5174 from zpao/dom-attributes-track
Add srcLang and kind to better support track elements
(cherry picked from commit 8e9682c542)
2015-10-28 12:42:15 -07:00
Sebastian Markbåge
6323f03148 Merge pull request #5166 from spicyj/gh-5157
Add feature test for document.createEvent
(cherry picked from commit da1135618e)
2015-10-28 12:42:15 -07:00
Ben Alpert
6384e56d8d Merge pull request #5157 from spicyj/createevent
Use 'document.createEvent' not 'new Event'
(cherry picked from commit 194ab16d7b)
2015-10-28 12:42:15 -07:00
Paul O’Shannessy
84f6915315 Merge pull request #5164 from zpao/fix-csstransitiongroup-proptype
Correctly handle 0 in CSSTransitionGroup timeout props
(cherry picked from commit af99b2c2a3)
2015-10-28 12:42:15 -07:00
Ben Alpert
fdb2486b98 Merge pull request #5085 from spicyj/cdp
Extract defineProperty feature testing to one file
(cherry picked from commit 2253405dcc)
2015-10-28 12:42:15 -07:00
Ben Alpert
fb620be2b8 Merge pull request #5081 from spicyj/svg-tu
Don't break on SVG tags in scryRenderedDOMComponentsWithClass
(cherry picked from commit 4fb39ce984)
2015-10-28 12:42:15 -07:00
Paul O’Shannessy
0acdefb7cc Bump version for dev 2015-10-28 12:26:18 -07:00
Dean Shi
e0f74c6c6c Update README's example
According to current React version, when I use `React.render`, console shows `React.render is deprecated. Please use ReactDOM.render from require('react-dom') instead.`.

So this PR is a tiny update for the README example.
(cherry picked from commit 2b136a4f84)
2015-10-27 16:09:54 -07:00
Jim
8ab0651158 Added changelog for 0.14
(cherry picked from commit 72e70f345b)
2015-10-27 15:48:21 -07:00
Paul O’Shannessy
712c6cb1d8 Merge pull request #5289 from jonathanp/patch-1
Update 2015-05-01-graphql-introduction.md
(cherry picked from commit 0f76873ebb)
2015-10-27 15:45:49 -07:00
Paul O’Shannessy
e931e02a36 Merge pull request #5286 from translucens/add_reactdom_js
Add react-dom.js to tutorials
(cherry picked from commit 11919b6d90)
2015-10-27 15:45:44 -07:00
Paul O’Shannessy
6c84e3d410 Merge pull request #5089 from thomasp9/patch-1
Create 01-why-react.de-DE.md

(cherry picked from commit d17ad0f0c0)
2015-10-27 15:45:40 -07:00
Paul O’Shannessy
e8b5c75c0f Merge pull request #5274 from SpartaSixZero/master
Corrected highlighted line in tutorial example in tutorial7.js
(cherry picked from commit 56c91248fd)
2015-10-27 15:45:34 -07:00
Jim
b5524faa4b Merge pull request #5230 from kohashi/patch-1
Fix tutorial.ja-JP.md
(cherry picked from commit 1dafac9e0c)
2015-10-27 15:45:30 -07:00
Paul O’Shannessy
411726dcf1 Update blog posts linking to react-codemod
(cherry picked from commit 8848984c46)
2015-10-20 15:47:58 -07:00
Paul O’Shannessy
28f242d0b4 Merge pull request #5214 from benigeri/patch-1
small edit on reactiflux blog post
(cherry picked from commit 244dd5da4c)
2015-10-19 12:03:50 -07:00
Jim
5cc9abfe60 Merge pull request #5203 from WanderWang/docs-cn
update Chinese docs to 0.14
(cherry picked from commit 9cb01de1bc)
2015-10-19 10:30:36 -07:00
Paul O’Shannessy
348a37cc99 [docs] Don't make authors links on all posts page
(cherry picked from commit e12ee95e09)
2015-10-19 10:30:28 -07:00
Paul O’Shannessy
bed6aefc46 Merge pull request #5178 from jimfb/multiple-authors
Fix blog post authors
(cherry picked from commit ccfc2d8049)
2015-10-19 10:30:14 -07:00
Paul O’Shannessy
1e175d0858 Merge pull request #5176 from jimfb/tweak-props-change-wording
Tweak wording when talking about props changing
(cherry picked from commit ed7ab7b94a)
2015-10-19 10:29:12 -07:00
Paul O’Shannessy
193e4cf582 Fix up stray markdown in blog post
(cherry picked from commit 8f1ce99cc3)
2015-10-19 10:27:24 -07:00
Christopher Chedeau
b0aa296519 Reactiflux is moving to Discord blog post
Conflicts:
	docs/_data/authors.yml
2015-10-19 07:44:54 -07:00
Ben Alpert
b020e69edc Mention codemods more prominently in release blog
(cherry picked from commit 4a37796f88)
2015-10-13 10:50:48 -07:00
Jim
d69657bca4 Merge pull request #5142 from MaxPRafferty/add-selection-and-composition-events-on-reference-page
Add selection and composition events on reference page
(cherry picked from commit 37c71a6e1f)
2015-10-12 15:15:46 -07:00
Paul O’Shannessy
8812c6b678 Merge pull request #5124 from bhamodi/master
Documentation Cleanup Round 1.
(cherry picked from commit abaf0051de)
2015-10-12 15:15:40 -07:00
Paul O’Shannessy
60e30f1da4 Merge pull request #5126 from bhamodi/white-space
File Cleanup.
(cherry picked from commit 5dc2858bc9)
2015-10-12 15:15:35 -07:00
Paul O’Shannessy
e4300d951c Merge pull request #5123 from vipulnsward/fix-html-jsx-page
- Bring back JSX compiler styling still being used on HTML JSX page
(cherry picked from commit 0b21632f8e)
2015-10-10 19:26:52 -07:00
Jim
13f3cdeeb1 Merge pull request #5120 from abloomston/patch-1
Include react-dom
(cherry picked from commit 0b29035484)
2015-10-10 19:26:42 -07:00
Paul O’Shannessy
fe085c1cce Update Readme for 0.14 2015-10-09 17:54:03 -07:00
Jim
b71499e5f4 Added react-dom to individual downloads
(cherry picked from commit f6e09f1903)
2015-10-09 15:25:30 -07:00
Ben Alpert
df0dac72c2 Document context
Fixes #580.

(cherry picked from commit 28b10a9d6a)
2015-10-09 14:47:13 -07:00
Paul O’Shannessy
5f2a80c086 Revert "Merge pull request #5102 from TracyJordan/master"
This reverts commit 5039dad053.
2015-10-09 12:35:53 -07:00
Paul O’Shannessy
e21f1c7759 [docs] Fix line highlights for linked-state-mixin
(cherry picked from commit 09b688efce)
2015-10-09 12:33:54 -07:00
Ben Alpert
21588d900f Merge pull request #5107 from mbrookes/patch-1
Grammar
(cherry picked from commit 407e88d6c8)
2015-10-09 12:33:47 -07:00
Jim
5039dad053 Merge pull request #5102 from TracyJordan/master
Fixed some comment punctuation in ReactDOMComponent.js
(cherry picked from commit 1a7c0a4b16)
2015-10-09 12:33:40 -07:00
Paul O’Shannessy
b120cdafb2 Merge pull request #5101 from bcbcb/patch-1
[docs] fix forms Default Value example
(cherry picked from commit 3359e2f64c)
2015-10-09 12:33:35 -07:00
Jim
f93bb3aa6a Merge pull request #4981 from iamchenxin/zh_docs
[docs] Sync up tutorial.zh-CN with en(a440f40)
(cherry picked from commit e8be7013ba)
2015-10-09 12:33:30 -07:00
Paul O’Shannessy
ac2853b5d4 Merge pull request #5096 from songawee/docs_babel_fix
fix(docs): adjust babel release to match the babel.js changelog
(cherry picked from commit c511f161df)
2015-10-08 13:24:19 -07:00
Nick Presta
007cf55872 Add docs for React.Children.toArray in 0.14.0.
* Update the docs to change return type of `React.Children.map` from `object` to `array`.

(cherry picked from commit 319b374097)
2015-10-07 17:02:48 -07:00
Ben Alpert
ec7947979b Update downloads page for 0.14
(cherry picked from commit e1d4668fd5)
2015-10-07 13:04:48 -07:00
Paul O’Shannessy
24f7659b7c Merge pull request #5073 from mfunkie/patch-2
Update Pure Render Mixin docs to point to new npm package
(cherry picked from commit 926f372dc5)
2015-10-07 12:22:43 -07:00
Paul O’Shannessy
c2443c227c Final docs update for 0.14 2015-10-07 10:23:27 -07:00
Paul O’Shannessy
3603d45157 v0.14.0 2015-10-07 10:19:56 -07:00
Paul O’Shannessy
0811e63e22 [docs] Update acknowledgements for 0.14 2015-10-07 10:16:55 -07:00
Paul O’Shannessy
3917c04f16 npm shrinkwrap 2015-10-07 10:01:04 -07:00
164 changed files with 19692 additions and 1159 deletions

View File

@@ -16,4 +16,4 @@ packages/react-codemod/test/
packages/react-codemod/scripts/
packages/react-codemod/build/
packages/react-codemod/node_modules/
vendor/react-dom.js
vendor/*

View File

@@ -54,6 +54,8 @@ script:
-F "react-with-addons.min=@build/react-with-addons.min.js" \
-F "react-dom=@build/react-dom.js" \
-F "react-dom.min=@build/react-dom.min.js" \
-F "react-dom-server=@build/react-dom-server.js" \
-F "react-dom-server.min=@build/react-dom-server.min.js" \
-F "npm-react=@build/packages/react.tgz" \
-F "npm-react-dom=@build/packages/react-dom.tgz" \
-F "commit=$TRAVIS_COMMIT" \

View File

@@ -1,3 +1,122 @@
## 0.14.3 (November 18, 2015)
### React DOM
- Added support for `nonce` attribute for `<script>` and `<style>` elements
- Added support for `reversed` attribute for `<ol>` elements
### React TestUtils Add-on
- Fixed bug with shallow rendering and function refs
### React CSSTransitionGroup Add-on
- Fixed bug resulting in timeouts firing incorrectly when mounting and unmounting rapidly
### React on Bower
- Added `react-dom-server.js` to expose `renderToString` and `renderToStaticMarkup` for usage in the browser
## 0.14.2 (November 2, 2015)
### React DOM
- Fixed bug with development build preventing events from firing in some versions of Internet Explorer & Edge
- Fixed bug with development build when using es5-sham in older versions of Internet Explorer
- Added support for `integrity` attribute
- Fixed bug resulting in `children` prop being coerced to a string for custom elements, which was not the desired behavior
- Moved `react` from `dependencies` to `peerDependencies` to match expectations and align with `react-addons-*` packages
## 0.14.1 (October 28, 2015)
### React DOM
- Fixed bug where events wouldn't fire in old browsers when using React in development mode
- Fixed bug preventing use of `dangerouslySetInnerHTML` with Closure Compiler Advanced mode
- Added support for `srcLang`, `default`, and `kind` attributes for `<track>` elements
- Added support for `color` attribute
- Ensured legacy `.props` access on DOM nodes is updated on re-renders
### React TestUtils Add-on
- Fixed `scryRenderedDOMComponentsWithClass` so it works with SVG
### React CSSTransitionGroup Add-on
- Fix bug preventing `0` to be used as a timeout value
### React on Bower
- Added `react-dom.js` to `main` to improve compatibility with tooling
## 0.14.0 (October 7, 2015)
### Major changes
- Split the main `react` package into two: `react` and `react-dom`. This paves the way to writing components that can be shared between the web version of React and React Native. This means you will need to include both files and some functions have been moved from `React` to `ReactDOM`.
- Addons have been moved to seperate packages (`react-addons-clone-with-props`, `react-addons-create-fragment`, `react-addons-css-transition-group`, `react-addons-linked-state-mixin`, `react-addons-perf`, `react-addons-pure-render-mixin`, `react-addons-shallow-compare`, `react-addons-test-utils`, `react-addons-transition-group`, `react-addons-update`, `ReactDOM.unstable_batchedUpdates`).
- Stateless functional components - React components were previously created using React.createClass or using ES6 classes. This release adds a [new syntax](https://facebook.github.io/react/docs/reusable-components.html#stateless-functions) where a user defines a single [stateless render function](https://facebook.github.io/react/docs/reusable-components.html#stateless-functions) (with one parameter: `props`) which returns a JSX element, and this function may be used as a component.
- Refs to DOM components as the DOM node itself. Previously the only useful thing you can do with a DOM component is call `getDOMNode()` to get the underlying DOM node. Starting with this release, a ref to a DOM component _is_ the actual DOM node. **Note that refs to custom (user-defined) components work exactly as before; only the built-in DOM components are affected by this change.**
### Breaking changes
- `React.initializeTouchEvents` is no longer necessary and has been removed completely. Touch events now work automatically.
- Add-Ons: Due to the DOM node refs change mentioned above, `TestUtils.findAllInRenderedTree` and related helpers are no longer able to take a DOM component, only a custom component.
- The `props` object is now frozen, so mutating props after creating a component element is no longer supported. In most cases, [`React.cloneElement`](/react/docs/top-level-api.html#react.cloneelement) should be used instead. This change makes your components easier to reason about and enables the compiler optimizations mentioned above.
- Plain objects are no longer supported as React children; arrays should be used instead. You can use the [`createFragment`](/react/docs/create-fragment.html) helper to migrate, which now returns an array.
- Add-Ons: `classSet` has been removed. Use [classnames](https://github.com/JedWatson/classnames) instead.
- Web components (custom elements) now use native property names. Eg: `class` instead of `className`.
### Deprecations
- `this.getDOMNode()` is now deprecated and `ReactDOM.findDOMNode(this)` can be used instead. Note that in the common case, `findDOMNode` is now unnecessary since a ref to the DOM component is now the actual DOM node.
- `setProps` and `replaceProps` are now deprecated. Instead, call ReactDOM.render again at the top level with the new props.
- ES6 component classes must now extend `React.Component` in order to enable stateless function components. The [ES3 module pattern](/react/blog/2015/01/27/react-v0.13.0-beta-1.html#other-languages) will continue to work.
- Reusing and mutating a `style` object between renders has been deprecated. This mirrors our change to freeze the `props` object.
- Add-Ons: `cloneWithProps` is now deprecated. Use [`React.cloneElement`](/react/docs/top-level-api.html#react.cloneelement) instead (unlike `cloneWithProps`, `cloneElement` does not merge `className` or `style` automatically; you can merge them manually if needed).
- Add-Ons: To improve reliability, `CSSTransitionGroup` will no longer listen to transition events. Instead, you should specify transition durations manually using props such as `transitionEnterTimeout={500}`.
### Notable enhancements
- Added `React.Children.toArray` which takes a nested children object and returns a flat array with keys assigned to each child. This helper makes it easier to manipulate collections of children in your `render` methods, especially if you want to reorder or slice `this.props.children` before passing it down. In addition, `React.Children.map` now returns plain arrays too.
- React uses `console.error` instead of `console.warn` for warnings so that browsers show a full stack trace in the console. (Our warnings appear when you use patterns that will break in future releases and for code that is likely to behave unexpectedly, so we do consider our warnings to be “must-fix” errors.)
- Previously, including untrusted objects as React children [could result in an XSS security vulnerability](http://danlec.com/blog/xss-via-a-spoofed-react-element). This problem should be avoided by properly validating input at the application layer and by never passing untrusted objects around your application code. As an additional layer of protection, [React now tags elements](https://github.com/facebook/react/pull/4832) with a specific [ES2015 (ES6) `Symbol`](http://www.2ality.com/2014/12/es6-symbols.html) in browsers that support it, in order to ensure that React never considers untrusted JSON to be a valid element. If this extra security protection is important to you, you should add a `Symbol` polyfill for older browsers, such as the one included by [Babels polyfill](http://babeljs.io/docs/usage/polyfill/).
- When possible, React DOM now generates XHTML-compatible markup.
- React DOM now supports these standard HTML attributes: `capture`, `challenge`, `inputMode`, `is`, `keyParams`, `keyType`, `minLength`, `summary`, `wrap`. It also now supports these non-standard attributes: `autoSave`, `results`, `security`.
- React DOM now supports these SVG attributes, which render into namespaced attributes: `xlinkActuate`, `xlinkArcrole`, `xlinkHref`, `xlinkRole`, `xlinkShow`, `xlinkTitle`, `xlinkType`, `xmlBase`, `xmlLang`, `xmlSpace`.
- The `image` SVG tag is now supported by React DOM.
- In React DOM, arbitrary attributes are supported on custom elements (those with a hyphen in the tag name or an `is="..."` attribute).
- React DOM now supports these media events on `audio` and `video` tags: `onAbort`, `onCanPlay`, `onCanPlayThrough`, `onDurationChange`, `onEmptied`, `onEncrypted`, `onEnded`, `onError`, `onLoadedData`, `onLoadedMetadata`, `onLoadStart`, `onPause`, `onPlay`, `onPlaying`, `onProgress`, `onRateChange`, `onSeeked`, `onSeeking`, `onStalled`, `onSuspend`, `onTimeUpdate`, `onVolumeChange`, `onWaiting`.
- Many small performance improvements have been made.
- Many warnings show more context than before.
- Add-Ons: A [`shallowCompare`](https://github.com/facebook/react/pull/3355) add-on has been added as a migration path for `PureRenderMixin` in ES6 classes.
- Add-Ons: `CSSTransitionGroup` can now use [custom class names](https://github.com/facebook/react/blob/48942b85/docs/docs/10.1-animation.md#custom-classes) instead of appending `-enter-active` or similar to the transition name.
### New helpful warnings
- React DOM now warns you when nesting HTML elements invalidly, which helps you avoid surprising errors during updates.
- Passing `document.body` directly as the container to `ReactDOM.render` now gives a warning as doing so can cause problems with browser extensions that modify the DOM.
- Using multiple instances of React together is not supported, so we now warn when we detect this case to help you avoid running into the resulting problems.
### Notable bug fixes
- Click events are handled by React DOM more reliably in mobile browsers, particularly in Mobile Safari.
- SVG elements are created with the correct namespace in more cases.
- React DOM now renders `<option>` elements with multiple text children properly and renders `<select>` elements on the server with the correct option selected.
- When two separate copies of React add nodes to the same document (including when a browser extension uses React), React DOM tries harder not to throw exceptions during event handling.
- Using non-lowercase HTML tag names in React DOM (e.g., `React.createElement('DIV')`) no longer causes problems, though we continue to recommend lowercase for consistency with the JSX tag name convention (lowercase names refer to built-in components, capitalized names refer to custom components).
- React DOM understands that these CSS properties are unitless and does not append “px” to their values: `animationIterationCount`, `boxOrdinalGroup`, `flexOrder`, `tabSize`, `stopOpacity`.
- Add-Ons: When using the test utils, `Simulate.mouseEnter` and `Simulate.mouseLeave` now work.
- Add-Ons: ReactTransitionGroup now correctly handles multiple nodes being removed simultaneously.
### React Tools / Babel
#### Breaking Changes
- The `react-tools` package and `JSXTransformer.js` browser file [have been deprecated](/react/blog/2015/06/12/deprecating-jstransform-and-react-tools.html). You can continue using version `0.13.3` of both, but we no longer support them and recommend migrating to [Babel](http://babeljs.io/), which has built-in support for React and JSX.
#### New Features
- Babel 5.8.24 introduces **Inlining React elements:** The `optimisation.react.inlineElements` transform converts JSX elements to object literals like `{type: 'div', props: ...}` instead of calls to `React.createElement`. This should only be enabled in production, since it disables some development warnings/checks.
- Babel 5.8.24 introduces **Constant hoisting for React elements:** The `optimisation.react.constantElements` transform hoists element creation to the top level for subtrees that are fully static, which reduces calls to `React.createElement` and the resulting allocations. More importantly, it tells React that the subtree hasnt changed so React can completely skip it when reconciling. This should only be enabled in production, since it disables some development warnings/checks.
## 0.13.3 (May 8, 2015)
### React Core

View File

@@ -1,4 +1,4 @@
# [React](https://facebook.github.io/react/) [![Build Status](https://travis-ci.org/facebook/react.svg?branch=master)](https://travis-ci.org/facebook/react) [![npm version](https://badge.fury.io/js/react.svg)](http://badge.fury.io/js/react)
# [React](https://facebook.github.io/react/) [![Build Status](https://travis-ci.org/facebook/react.svg?branch=0.14-stable)](https://travis-ci.org/facebook/react) [![npm version](https://badge.fury.io/js/react.svg)](http://badge.fury.io/js/react)
React is a JavaScript library for building user interfaces.
@@ -21,7 +21,7 @@ var HelloMessage = React.createClass({
}
});
React.render(
ReactDOM.render(
<HelloMessage name="John" />,
document.getElementById('container')
);
@@ -37,12 +37,12 @@ The fastest way to get started is to serve JavaScript from the CDN (also availab
```html
<!-- The core React library -->
<script src="https://fb.me/react-0.13.3.js"></script>
<!-- In-browser JSX transformer, remove when pre-compiling JSX. -->
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
<script src="https://fb.me/react-0.14.3.js"></script>
<!-- The ReactDOM Library -->
<script src="https://fb.me/react-dom-0.14.3.js"></script>
```
We've also built a [starter kit](https://facebook.github.io/react/downloads/react-0.13.3.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
We've also built a [starter kit](https://facebook.github.io/react/downloads/react-0.14.3.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
If you'd like to use [bower](http://bower.io), it's as easy as:

View File

@@ -36,4 +36,4 @@ sass:
sass_dir: _css
gems:
- jekyll-redirect-from
react_version: 0.14.0-alpha
react_version: 0.14.2

View File

@@ -1,44 +1,75 @@
---
- - Aaron Franks
- - '839'
- Aaron Franks
- Aaron Gelter
- Adam Krebs
- Adam Mark
- Adam Solove
- Adam Timberlake
- Adam Zapletal
- Ahmad Wali Sidiqi
- Alan Souza
- Alan deLevie
- Alastair Hole
- Alex
- Alex Boyd
- Alex Lopatin
- Alex Mykyta
- Alex Pien
- Alex Smith
- Alex Zelenskiy
- Alexander Shtuchkin
- Alexander Solovyov
- Alexander Tseung
- Alexandre Gaudencio
- Alexey Raspopov
- Alexey Shamrin
- Andre Z Sanchez
- Andreas Savvides
- Andreas Svensson
- Andres Kalle
- Andres Suarez
- Andrew Cobby
- Andrew Davey
- Andrew Rasmussen
- Andrew Sokolov
- Andrew Zich
- Andrey Popp
- Anthony van der Hoorn
- Antonio Ruberto
- Antti Ahti
- Anuj Tomar
- AoDev
- Areeb Malik
- Aria Buckles
- Aria Stewart
- Arian Faurtosh
- Artem Nezvigin
- Austin Wright
- Ayman Osman
- Baraa Hamodi
- Bartosz Kaszubowski
- Basarat Ali Syed
- Battaile Fauber
- Beau Smith
- Ben Alpert
- Ben Anderson
- Ben Foxall
- Ben Jaffe
- Ben Moss
- Ben Newman
- Ben Ripkens
- Benjamin Keen
- Benjamin Leiken
- Benjamin Woodruff
- Bill Fisher
- Blaine Hatab
- Blaine Kasten
- Bob Eagan
- Bob Ralian
- Bob Renwick
- Bojan Mihelac
- Bradley Spaulding
- Brandon Bloom
- Brandon Tilley
- Brian Cooke
@@ -51,103 +82,166 @@
- Bruno Škvorc
- Cam Song
- Cam Spiers
- Carter Chung
- Cassus Adam Banko
- Cat Chen
- Cedric Sohrauer
- Charles Marsh
- Chase Adams
- Cheng Lou
- Chitharanjan Das
- Chris Grovers
- Chris Ha
- Chris Rebert
- Chris Sciolla
- Christian
- Christian Alfoni
- Christian Oliff
- Christian Roman
- Christoph Pojer
- Christopher Monsanto
- Clay Allsopp
- Connor McSheffrey
- Cory House
- Cotton Hou
- Cristovao Verstraeten
- Damien Pellier
- Dan Abramov
- Dan Fox
- Dan Schafer
- Daniel Carlsson
- Daniel Cousens
- Daniel Friesen
- Daniel Gasienica
- Daniel Hejl
- Daniel Lo Nigro
- Daniel Mané
- Daniel Miladinov
- Daniel Rodgers-Pryor
- Daniel Schonfeld
- Danny Ben-David
- Darcy
- Daryl Lau
- Darío Javier Cravero
- David Baker
- David Goldberg
- David Greenspan
- David Hellsing
- David Hu
- David Mininger
- David Neubauer
- David Percy
- Denis Sokolov
- Dennis Johnson
- Devon Blandin
- Devon Harvey
- Dmitrii Abramov
- Dmitry Blues
- Dmitry Mazuro
- Domenico Matteo
- Don Abrams
- Dustan Kasten
- Dustin Getz
- Dylan Harrington
- Eduardo Garcia
- Edvin Erikson
- Elaine Fang
- Enguerran
- Eric Clemmons
- Eric Eastwood
- Eric Florenzano
- Eric O'Connell
- Eric Schoffstall
- Erik Harper
- Espen Hovlandsdal
- Evan Coonrod
- Fabio M. Costa
- Federico Rampazzo
- Felipe Oliveira Carvalho
- Felix Gnass
- Felix Kling
- Fernando Correia
- Frankie Bagnardi
- François-Xavier Bois
- Fred Zhao
- G Scott Olson
- G. Kay Lee
- Gabe Levi
- Gareth Nicholson
- Garren Smith
- Geert Pasteels
- Geert-Jan Brits
- George A Sisco III
- Georgii Dolzhykov
- Gilbert
- Glen Mailer
- Grant Timmerman
- Greg Hurrell
- Greg Perkins
- Greg Roodt
- Gregory
- Guangqiang Dong
- Guido Bouman
- Harry Hull
- Harry Marr
- - Harry Moreno
- Harshad Sabne
- Hekar Khani
- Hendrik Swanepoel
- Henrik Nyh
- Henry Zhu
- Hou Chia
- Hugo Jobling
- Héliton Nordt
- Ian Obermiller
- Ignacio Carbajo
- Igor Scekic
- Ilya Shuklin
- Ilyá Belsky
- Ingvar Stepanyan
- Irae Carvalho
- Isaac Salier-Hellendag
- Ivan Kozik
- Ivan Krechetov
- Ivan Vergiliev
- J. Andrew Brassington
- J. Renée Beach
- JD Isaacks
- JW
- Jack Zhang
- Jacob Gable
- Jacob Greenleaf
- Jae Hun Ro
- Jaime Mingo
- Jakub Malinowski
- James
- James Brantly
- James Burnett
- James Ide
- James Long
- James Pearce
- James Seppi
- James South
- Jamie Wong
- Jamis Charles
- Jamison Dance
- Jan Hancic
- Jan Kassens
- Jan Raasch
- Jared Forsyth
- Jason
- Jason Bonta
- Jason Ly
- Jason Miller
- Jason Quense
- Jason Trill
- Jason Webster
- Jay Jaeho Lee
- Jean Lauliac
- Jed Watson
- Jeff Barczewski
- Jeff Carpenter
- Jeff Chan
- Jeff Hicken
- Jeff Kolesky
- Jeff Morrison
- Jeff Welch
@@ -158,50 +252,81 @@
- Jim Sproch
- Jimmy Jea
- Jing Chen
- Jinwoo Oh
- Jiyeon Seo
- Joe Stein
- Joel Auterson
- Johannes Baiter
- Johannes Emerich
- Johannes Lumpe
- John Heroy
- John Watson
- Jon Beebe
- Jon Chester
- Jon Hester
- Jon Madison
- Jon Scott Clark
- Jon Tewksbury
- Jonas Enlund
- Jonas Gebhardt
- Jonathan Hsu
- Jordan Harband
- Jordan Walke
- Jorrit Schippers
- Joseph Nudell
- Joseph Savona
- Josh Bassett
- Josh Duck
- Josh Yudaken
- Joshua Go
- Joshua Goldberg
- Joshua Ma
- João Valente
- Juan Serrano
- Julen Ruiz Aizpuru
- Julian Viereck
- Julien Bordellier
- Jun Wu
- Juraj Dudak
- Justin Jaffray
- Justin Robison
- Justin Woo
- Kamron Batman
- Karl Mikkelsen
- Karpich Dmitry
- Keito Uchiyama
- Kevin Coughlin
- Kevin Huang
- Kevin Old
- KimCoding
- Kirk Steven Hansen
- Kit Randel
- Kohei TAKATA
- Koo Youngmin
- Kunal Mehta
- Kurt Ruppel
- Kyle Kelley
- Kyle Mathews
- Laurence Rowe
- Laurent Etiemble
- Lee Byron
- Lee Jaeyoung
- Lei
- Leon Fedotov
- Leon Yip
- Leonardo YongUk Kim
- Levi Buzolic
- Levi McCallum
- Lily
- Logan Allen
- Luigy Leon
- Luke Horvat
- MIKAMI Yoshiyuki
- Marcin K.
- Marcin Kwiatkowski
- Marcin Szczepanski
- Mariano Desanze
- Marjan
- Mark Anderson
- Mark Funk
- Mark Hintz
@@ -212,28 +337,49 @@
- Martin Andert
- Martin Jul
- Martin Konicek
- Martin Mihaylov
- Masaki KOBAYASHI
- Mathieu M-Gosselin
- Matias Singers
- Matsunoki
- Matt Brookes
- Matt Dunn-Rankin
- Matt Harrison
- Matt Huggins
- Matt Zabriskie
- Matthew Dapena-Tretter
- Matthew Johnston
- Matthew King
- Matthew Miner
- Matthias Le Brun
- Matti Nelimarkka
- Max F. Albrecht
- Max Heiber
- Maxi Ferreira
- Maxim Abramchuk
- Merrick Christensen
- Mert Kahyaoğlu
- Michael Chan
- Michael Randers-Pehrson
- Michael Ridgway
- Michael Warner
- Michal Srb
- Michelle Todd
- Mihai Parparita
- Mike D Pilsbury
- - Mike Groseclose
- Mikolaj Dadela
- Minwe LUO
- Miorel Palii
- - Mouad Debbar
- Morhaus
- Mouad Debbar
- Murad
- Murray M. Moss
- Nadeesha Cabral
- Naman Goel
- Nate Hunzaker
- Nathan White
- Neri Marschik
- Nicholas Bergson-Shilcock
- Nick Fitzgerald
- Nick Gavalas
@@ -242,14 +388,20 @@
- Nick Thompson
- Nick Williams
- Niklas Boström
- Ning Xia
- Niole Nelson
- Oiva Eskola
- Oleg
- Oleksii Markhovskyi
- Oliver Zeigermann
- Olivier Tassinari
- Owen Coutts
- Pablo Lacerda de Miranda
- Paolo Moretti
- Pascal Hartig
- Patrick Laughlin
- Patrick Stapleton
- Paul Harper
- Paul OShannessy
- Paul Seiffert
- Paul Shen
@@ -262,6 +414,7 @@
- Petri Lievonen
- Pieter Vanderwerff
- Pouja Nikray
- Prathamesh Sonpatki
- Preston Parry
- Rafael
- Rafal Dittwald
@@ -269,76 +422,131 @@
- Randall Randall
- Ray
- Raymond Ha
- Reed Loden
- Richard D. Worth
- Richard Feldman
- Richard Kho
- Richard Littauer
- Richard Livesey
- Richard Wood
- Rick Beerendonk
- Riley Tomasek
- Rob Arnold
- Robert Knight
- Robert Sedovsek
- Robin Berjon
- Roman Vanesyan
- Russ
- Ryan Seddon
- Sahat Yalkabov
- Saif Hakim
- Sam Saccone
- Sam Selikoff
- Samy Al Zahrani
- Sander Spies
- Scott Burch
- Scott Feeney
- Sean Kinsey
- Sebastian Markbåge
- Seoh Char
- Serg
- Sergey Generalov
- Sergey Rubanov
- Seyi Adebajo
- Shane O'Sullivan
- Shaun Trennery
- Sheraz
- ShihChi Huang
- Shim Won
- Shota Kubota
- Shripad K
- Sibi
- Simon Højberg
- Simon Welsh
- Sophia Westwood
- Spencer Handley
- Stefan Dombrowski
- Stephen Murphy
- Sterling Cobb
- Steve Baker
- Steven Luscher
- Stoyan Stefanov
- Sundeep Malladi
- Sunny Juneja
- Sven Helmberger
- Sverre Johansen
- Sébastien Lorber
- Sławomir Laskowski
- Taeho Kim
- Tay Yang Shun
- Ted Kim
- Teodor Szente
- Thomas Aylott
- Thomas Boyt
- Thomas Reggi
- Thomas Röggla
- Thomas Shaddox
- Thomas Shafer
- ThomasCrvsr
- Tienchai Wirojsaksaree
- Tim Routowicz
- Tim Schaub
- Timothy Yung
- Tobias Reiss
- Tom Haggie
- Tom Hauburger
- Tom MacWright
- Tom Occhino
- Tomasz Kołodziejski
- Tony Spiro
- Toru Kobayashi
- Trinh Hoang Nhu
- Tsung Hung
- Tyler Brock
- Ustin Zarubin
- Vadim Chernysh
- Varun Rau
- Vasiliy Loginevskiy
- Victor Alvarez
- Victor Koenders
- Ville Immonen
- Vincent Riemer
- Vincent Siao
- Vipul A M
- Vitaly Kramskikh
- Vjeux
- Volkan Unsal
- Wayne Larsen
- WickyNilliams
- Wincent Colaiuta
- Wout Mertens
- Xavier Morel
- XuefengWu
- Yakov Dalinchuk
- Yasar icli
- YouBao Nong
- Yuichi Hagio
- Yuriy Dybskiy
- Yuval Dekel
- Zach Bruggeman
- Zacharias
- arush
- brafdlog
- chen
- clariroid
- claudiopro
- cutbko
- davidxi
- dongmeng.ldm
- iamchenxin
- iamdoron
- imagentleman
- "Árni Hermann Reynisson"
- "张敏"
- laiso
- li.li
- sugarshin
- wali-s
- yiminghe
- youmoo
- zhangjg
- Árni Hermann Reynisson
- 凌恒
- 张敏

View File

@@ -1,8 +1,9 @@
# Map of short name to more information. `name` will be used but if you don't
# want to use your real name, just use whatever. If url is included, your name
# will be a link to the provided url.
billandjing:
name: Bill Fisher and Jing Chen
benigeri:
name: Paul Benigeri
url: https://github.com/benigeri
chenglou:
name: Cheng Lou
url: https://twitter.com/_chenglou
@@ -18,8 +19,12 @@ jaredly:
jgebhardt:
name: Jonas Gebhardt
url: https://twitter.com/jonasgebhardt
jimandsebastian:
name: Jim Sproch and Sebastian Markbåge
jimfb:
name: Jim Sproch
url: http://www.jimsproch.com
jingc:
name: Jing Chen
url: https://twitter.com/jingc
josephsavona:
name: Joseph Savona
url: https://twitter.com/en_JS

View File

@@ -67,6 +67,8 @@
title: Performance Tools
- id: advanced-performance
title: Advanced Performance
- id: context
title: Context
- title: Reference
items:
- id: top-level-api
@@ -85,6 +87,8 @@
title: Special Non-DOM Attributes
- id: reconciliation
title: Reconciliation
- id: webcomponents
title: Web Components
- id: glossary
title: React (Virtual) DOM Terminology
- title: Flux

View File

@@ -11,11 +11,14 @@
<p class="meta">
{{ page.date | date: "%B %e, %Y" }}
by
{% if page.author.url %}
<a href="{{page.author.url}}">{{ page.author.name }}</a>
{% else %}
{{ page.author.name }}
{% endif %}
{% for author in page.authors %}
{% if author.url %}
<a href="{{author.url}}">{{ author.name }}</a>
{% else %}
{{ author.name }}
{% endif %}
{% if forloop.last == false %} and {% endif %}
{% endfor %}
</p>
<hr>

View File

@@ -7,7 +7,15 @@ module Authors
class Generator < Jekyll::Generator
def generate(site)
site.posts.each do |post|
post.data['author'] = site.data['authors'][post['author']]
authors = []
if post['author'].kind_of?(Array)
for author in post['author']
authors.push(site.data['authors'][author])
end
else
authors.push(site.data['authors'][post['author']])
end
post.data['authors'] = authors
end
end
end

View File

@@ -1,6 +1,6 @@
---
title: "Flux: An Application Architecture for React"
author: fisherwebdevandjing
author: [fisherwebdev, jingc]
---
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:

View File

@@ -40,20 +40,18 @@ The first step is a React `<Story>` component that accepts a `story` prop with t
```javascript
// Story.react.js
class Story extends React.Component {
export default class Story extends React.Component {
render() {
var story = this.props.story;
return (
<View>
<Image uri={story.author.profile_picture.uri} />
<Image uri={story.author.profilePicture.uri} />
<Text>{story.author.name}</Text>
<Text>{story.text}</Text>
</View>
);
}
}
module.exports = Story;
```
<br/>
@@ -66,41 +64,41 @@ Relay automates the process of fetching data for components by wrapping existing
// Story.react.js
class Story extends React.Component { ... }
module.exports = Relay.createContainer(Story, {
queries: {
export default Relay.createContainer(Story, {
fragments: {
story: /* TODO */
}
});
```
Before adding the GraphQL query, let's look at the component hierarchy this creates:
Before adding the GraphQL fragment, let's look at the component hierarchy this creates:
<img src="/react/img/blog/relay-components/relay-containers.png" width="397" alt="React Container Data Flow" />
Most props will be passed through from the container to the original component. However, Relay will return the query results for a prop whenever a query is defined. In this case we'll add a GraphQL query for `story`:
Most props will be passed through from the container to the original component. However, Relay will return the query results for a prop whenever a fragment is defined. In this case we'll add a GraphQL fragment for `story`:
```javascript
// Story.react.js
class Story extends React.Component { ... }
module.exports = Relay.createContainer(Story, {
queries: {
story: graphql`
Story {
export default Relay.createContainer(Story, {
fragments: {
story: () => Relay.QL`
fragment on Story {
author {
name,
profile_picture {
name
profilePicture {
uri
}
},
}
text
}
`
}
`,
},
});
```
Queries use ES6 template literals tagged with the `graphql` function. Similar to how JSX transpiles to plain JavaScript objects and function calls, these template literals transpile to plain objects that describe queries. Note that the query's structure closely matches the object structure that we expected in `<Story>`'s render function.
Queries use ES6 template literals tagged with the `Relay.QL` function. Similar to how JSX transpiles to plain JavaScript objects and function calls, these template literals transpile to plain objects that describe fragments. Note that the fragment's structure closely matches the object structure that we expected in `<Story>`'s render function.
<br/>
@@ -112,7 +110,7 @@ We can render a Relay component by providing Relay with the component (`<Story>`
{
author: {
name: "Greg",
profile_picture: {
profilePicture: {
uri: "https://…"
}
},
@@ -159,35 +157,35 @@ module.exports = NewsFeed;
`<NewsFeed>` has two new requirements: it composes `<Story>` and requests more data at runtime.
Just as React views can be nested, Relay queries can compose queries from child components. Composition in GraphQL uses ES6 template literal substitution: `${Component.getQuery('prop')}`. Pagination can be accomplished with a query parameter, specified with `<param>` (as in `stories(first: <count>)`):
Just as React views can be nested, Relay components can compose query fragments from child components. Composition in GraphQL uses ES6 template literal substitution: `${Component.getFragment('prop')}`. Pagination can be accomplished with a variable, specified with `$variable` (as in `stories(first: $count)`):
```javascript
// NewsFeed.react.js
class NewsFeed extends React.Component { ... }
module.exports = Relay.createContainer(NewsFeed, {
queryParams: {
count: 3 /* default to 3 stories */
export default Relay.createContainer(NewsFeed, {
initialVariables: {
count: 3 /* default to 3 stories */
},
queries: {
viewer: graphql`
Viewer {
stories(first: <count>) { /* fetch viewer's stories */
edges { /* traverse the graph */
fragments: {
viewer: () => Relay.QL`
fragment on Viewer {
stories(first: $count) { /* fetch viewer's stories */
edges { /* traverse the graph */
node {
${Story.getQuery('story')} /* compose child query */
${Story.getFragment('story')} /* compose child fragment */
}
}
}
}
`
}
`,
},
});
```
Whenever `<NewsFeed>` is rendered, Relay will recursively expand all the composed queries and fetch them in a single trip to the server. In this case, the `text` and `author` data will be fetched for each of the 3 story nodes.
Whenever `<NewsFeed>` is rendered, Relay will recursively expand all the composed fragments and fetch the queries in a single trip to the server. In this case, the `text` and `author` data will be fetched for each of the 3 story nodes.
Query parameters are available to components as `props.queryParams` and can be modified with `props.setQueryParams(nextParams)`. We can use these to implement pagination:
Query variables are available to components as `props.relay.variables` and can be modified with `props.relay.setVariables(nextVariables)`. We can use these to implement pagination:
```javascript
// NewsFeed.react.js
@@ -196,16 +194,16 @@ class NewsFeed extends React.Component {
loadMore() {
// read current params
var count = this.props.queryParams.count;
var count = this.props.relay.variables.count;
// update params
this.props.setQueryParams({
count: count + 5
this.props.relay.setVariables({
count: count + 5,
});
}
}
```
Now when `loadMore()` is called, Relay will send a GraphQL request for the additional five stories. When these stories are fetched, the component will re-render with the new stories available in `props.viewer.stories` and the updated count reflected in `props.queryParams.count`.
Now when `loadMore()` is called, Relay will send a GraphQL request for the additional five stories. When these stories are fetched, the component will re-render with the new stories available in `props.viewer.stories` and the updated count reflected in `props.relay.variables.count`.
<br/>

View File

@@ -77,7 +77,7 @@ We believe there are a number of weakness in typical REST systems, ones that are
* Fetching complicated object graphs require multiple round trips between the client and server to render single views. For mobile applications operating in variable network conditions, these multiple roundtrips are highly undesirable.
* Invariably fields and additional data are added to REST endpoints as the system requirements change. However, old clients also receive this additional data as well, because the data fetching specification is encoded on the server rather than the client. As result, these payloads tend to grow over time for all clients. When this becomes a problem for a system, one solution is to overlay a versioning system onto the REST endpoints. Versioning also complicates a server, and results in code duplication, spaghetti code, or a sophisticated, hand-rolled infrastructure to manage it. Another solution to limit over-fetching is to provide multiple views such as “compact” vs “full” of the same REST endpoint, however this coarse granularity often does not offer adequate flexibility.
* REST endpoints are usually weakly-typed and lack machine-readable metadata. While there is much debate about the merits of strong- versus weak-typing in distributed systems, we believe in strong typing because of the correctness guarantees and tooling opportunities it provides. Developer deal with systems that lack this metadata by inspecting frequently out-of-date documentation and then writing code against the documentation.
* REST endpoints are usually weakly-typed and lack machine-readable metadata. While there is much debate about the merits of strong- versus weak-typing in distributed systems, we believe in strong typing because of the correctness guarantees and tooling opportunities it provides. Developers deal with systems that lack this metadata by inspecting frequently out-of-date documentation and then writing code against the documentation.
* Many of these attributes are linked to the fact that “REST is intended for long-lived network-based applications that span multiple organizations” [according to its inventor](http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven). This is not a requirement for APIs that serve a client app built within the same organization.
Nearly all externally facing REST APIs we know of trend or end up in these non-ideal states, as well as nearly all *internal* REST APIs. The consequences of opaqueness and over-fetching are more severe in internal APIs since their velocity of change and level of usage is almost always higher.
@@ -90,7 +90,7 @@ Because of multiple round-trips and over-fetching, applications built in the RES
Many applications have no formalized client-server contract. Product developers access server capabilities through *ad hoc* endpoints and write custom code to fetch the data they need. Servers define procedures, and they return data. This approach has the virtue of simplicity, but can often become untenable as systems age.
* These systems typically define a custom endpoint per view. For systems with a wide surface area this can quickly grow into a maintenance nightmare of orphaned endpoints, inconsistent tooling, and massive server code duplication. Disciplined engineering organizations can mitigate these issues with great engineering practices, high quality abstractions, and custom tooling. However, given our experience we believe that custom endpoints tend to lead to entropic server codebases.
* Much like REST, the payloads of custom endpoints grow monotonically (even with mitigation from versioning systems) as the server evolves. Deployed clients cannot break, and, with rapid release cycles and backwards compatibility guarantees, distributed applications will have large numbers of extant versions. Under these constraints it is difficult remove data from a custom endpoint.
* Much like REST, the payloads of custom endpoints grow monotonically (even with mitigation from versioning systems) as the server evolves. Deployed clients cannot break, and, with rapid release cycles and backwards compatibility guarantees, distributed applications will have large numbers of extant versions. Under these constraints it is difficult to remove data from a custom endpoint.
* Custom endpoints tend to for a client developer create a clunky, multi-language, multi-environment development process. No matter if the data has been accessed before in a different view, they are required to first change the custom endpoint, then deploy that code to a server accessible from a mobile device, and only then change the client to utilize that data. In GraphQL unless the data in the view is completely new to the entire system a product developer adds a field to a GraphQL query and the work on the client continues unabated.
* Much like REST, most systems with custom endpoints do not have a formalized type system, which eliminates the possibility for the tools and guarantees that introspective type systems can provide. Some custom-endpoint-driven systems do use a strongly typed serialization scheme, such as Protocol Buffers, Thrift, or XML. Those do allow for direct parsing of responses into typed classes and eliminating boilerplate shuffling from JSON into handwritten classes. These systems are as not as expressive and flexible as GraphQL, and the other downsides of *ad hoc* endpoints remain.

View File

@@ -57,7 +57,7 @@ These builds are also available in the `react` package on bower.
ReactDOM.render(<MyComponent />, node);
```
Weve published the [automated codemod script](https://github.com/facebook/react/blob/master/packages/react-codemod/README.md) we used at Facebook to help you with this transition.
Weve published the [automated codemod script](https://github.com/reactjs/react-codemod/blob/master/README.md) we used at Facebook to help you with this transition.
The add-ons have moved to separate packages as well: `react-addons-clone-with-props`, `react-addons-create-fragment`, `react-addons-css-transition-group`, `react-addons-linked-state-mixin`, `react-addons-perf`, `react-addons-pure-render-mixin`, `react-addons-shallow-compare`, `react-addons-test-utils`, `react-addons-transition-group`, and `react-addons-update`, plus `ReactDOM.unstable_batchedUpdates` in `react-dom`.

View File

@@ -1,6 +1,6 @@
---
title: "ReactDOM.render and the Top Level React API"
author: jimandsebastian
author: ["jimfb", "sebmarkbage"]
---

View File

@@ -15,6 +15,8 @@ Like always, we have a few breaking changes in this release. We know changes can
If your code is free of warnings when running under React 0.13, upgrading should be easy. We have two new small breaking changes that didn't give a warning in 0.13 (see below). Every new change in 0.14, including the major changes below, is introduced with a runtime warning and will work as before until 0.15, so you don't have to worry about your app breaking with this upgrade.
For the two major changes which require significant code changes, we've included [codemod scripts](https://github.com/reactjs/react-codemod/blob/master/README.md) to help you upgrade your code automatically.
See the changelog below for more details.
## Installation
@@ -64,7 +66,7 @@ If you cant use `npm` yet, we provide pre-built browser builds for your conve
ReactDOM.render(<MyComponent />, node);
```
The old names will continue to work with a warning until 0.15 is released, and weve published the [automated codemod script](https://github.com/facebook/react/blob/master/packages/react-codemod/README.md) we used at Facebook to help you with this transition.
The old names will continue to work with a warning until 0.15 is released, and weve published the [automated codemod script](https://github.com/reactjs/react-codemod/blob/master/README.md) we used at Facebook to help you with this transition.
The add-ons have moved to separate packages as well:
- `react-addons-clone-with-props`
@@ -99,7 +101,7 @@ If you cant use `npm` yet, we provide pre-built browser builds for your conve
```
This change also applies to the return result of `ReactDOM.render` when passing a DOM node as the top component. As with refs, this change does not affect custom components.
With this change, were deprecating `.getDOMNode()` and replacing it with `ReactDOM.findDOMNode` (see below). If your components are currently using `.getDOMNode()`, they will continue to work with a warning until 0.15.
- #### Stateless functional components
@@ -124,7 +126,7 @@ If you cant use `npm` yet, we provide pre-built browser builds for your conve
```
These components behave just like a React class with only a `render` method defined. Since no component instance is created for a functional component, any `ref` added to one will evaluate to `null`. Functional components do not have lifecycle methods, but you can set `.propTypes` and `.defaultProps` as properties on the function.
This pattern is designed to encourage the creation of these simple components that should comprise large portions of your apps. In the future, well also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations.
- #### Deprecation of react-tools
@@ -133,7 +135,7 @@ If you cant use `npm` yet, we provide pre-built browser builds for your conve
- #### Compiler optimizations
React now supports two compiler optimizations that can be enabled in Babel 5.8.23 and newer. Both of these transforms **should be enabled only in production** (e.g., just before minifying your code) because although they improve runtime performance, they make warning messages more cryptic and skip important checks that happen in development mode, including propTypes.
React now supports two compiler optimizations that can be enabled in Babel 5.8.24 and newer. Both of these transforms **should be enabled only in production** (e.g., just before minifying your code) because although they improve runtime performance, they make warning messages more cryptic and skip important checks that happen in development mode, including propTypes.
**Inlining React elements:** The `optimisation.react.inlineElements` transform converts JSX elements to object literals like `{type: 'div', props: ...}` instead of calls to `React.createElement`.
@@ -159,7 +161,7 @@ Each of these changes will continue to work as before with a new warning until t
- Due to the DOM node refs change mentioned above, `this.getDOMNode()` is now deprecated and `ReactDOM.findDOMNode(this)` can be used instead. Note that in most cases, calling `findDOMNode` is now unnecessary see the example above in the “DOM node refs” section.
With each returned DOM node, we've added a `getDOMNode` method for backwards compatibility that will work with a warning until 0.15. If you have a large codebase, you can use our [automated codemod script](https://github.com/facebook/react/blob/master/packages/react-codemod/README.md) to change your code automatically.
With each returned DOM node, we've added a `getDOMNode` method for backwards compatibility that will work with a warning until 0.15. If you have a large codebase, you can use our [automated codemod script](https://github.com/reactjs/react-codemod/blob/master/README.md) to change your code automatically.
- `setProps` and `replaceProps` are now deprecated. Instead, call ReactDOM.render again at the top level with the new props.
- ES6 component classes must now extend `React.Component` in order to enable stateless function components. The [ES3 module pattern](/react/blog/2015/01/27/react-v0.13.0-beta-1.html#other-languages) will continue to work.

View File

@@ -0,0 +1,86 @@
---
title: "Reactiflux is moving to Discord"
author: benigeri
---
TL;DR: Slack decided that Reactiflux had too many members and disabled new invites. Reactiflux is moving to Discord. Join us: [http://join.reactiflux.com](http://join.reactiflux.com/)
## What happened with Slack?
A few weeks ago, Reactiflux reached 7,500 members on Slack. Shortly after, Slack decided we were too big and disabled invites. There was no way for new users to join. Many of us were sad and upset. We loved Slack. Our community was built around it.
We reached out to Slack several times, but their decision was firm. Our large community caused performance issues. Slack wants to focus on building a great product for teams, not necessarily large open communities. Losing focus and building for too many use cases always leads to product bloat, and eventually a decrease in quality.
## So… why Discord?
After a [long and thorough debate](https://github.com/reactiflux/volunteers/issues/25), Discord quickly emerged as the most promising service. After just a few days, 400 members had joined the Discord server, and many already loved it.
### Easiest to join
Discord is the easiest platform to join. New users can immediately join our conversations without having to create an account. All they need to do is provide a name. No permission granting, no password, no email confirmation.
This is critically useful for us, and will make Reactiflux even more open and accessible.
### Great apps
Out of all of the services weve tried, Discords apps are by far the most polished. They are well designed, easy to use, and surprisingly fast. In addition to the web app, they have mobile apps on both iOS and Android as well as desktop apps for OS X and Windows, with Linux support coming soon.
Their desktop apps are built with React and Electron, and their iOS app is built with React Native.
### Moderation tools
So far, weve been fortunate not to have to deal with spammers and trolls. As our community continues to grow, that might change. Unsurprisingly, Discord is the only app weve seen with legitimate moderation tools. It was built for gaming communities, after all.
### Great multiple Server support
Your Discord account works with every Discord server, which is the equivalent of a Slack team. You dont need to create a new account every time you join a new team. You can join new servers in one click, and its very easy to switch between them. Discord messages also work across servers, so your personal conversations are not scoped to a single server.
Instead of having one huge, crowded Reactiflux server, we can branch off closely related channels into sub-servers. Communities will start overlapping, and it will be easy to interact with non-Reactiflux channels.
### Its hosted
Self-hosted apps require maintenance. Were all busy, and we can barely find the time to keep our landing page up to date and running smoothly. More than anything, we need a stable platform, and we dont have the resources to guarantee that right now.
Its a much safer bet to offload the hosting to Discord, who is already keeping the lights on for all their users.
### We like the team
And they seem to like us back. They are excited for us to join them, and theyve been very responsive to our feedback and suggestions.
They implemented code syntax highlighting just a few days after we told them we needed it.
Discords team has already built a solid suite of apps, and they have shown us how much they care about their users. Were excited to see how they will continue to improve their product.
## And whats the catch?
Choosing the best chat service is subjective. There are a million reasons why Discord *might be* a terrible idea. Here are the ones that were most worried about:
### Difficult channel management
Channel management seems to be the biggest issue. There is no way to opt out of channels; you can only mute them. And you can only mute channels one by one. There is no way to star channels, and channels can only be sorted on the server level. Each user will see the list of channels in the same order.
As the number of channels grow, it will be challenging to keep things in order. Branching off sub-servers will help, and we will keep an easily accessible directory of channels across our main server and all of the sub-servers.
We can build simple tools to make channel lookup easier, and the Discord team is working on improvements that should make this more manageable.
### No Search
Lack of search is clearly a bummer, but Discord is working on it. Search is coming!
### Firewall
A couple of users arent able to access Discord at work since other corporate filters classify it as a gaming application. This sucks, but it seems to be a rare case. So far, it seems only to affect 0.6% of our current community (3/500).
We hope that these users can get Discord's domains whitelisted, and well try to find a solution if this is a widespread issue. The Discord team is aware of the issue as well.
## Is Discord going to disappear tomorrow?
Probably not tomorrow. They have 14 people [full time](https://discordapp.com/company), and theyve raised money from some of the best investors in Silicon Valley, including [Benchmark](http://www.benchmark.com/) and [Accel](http://www.accel.com/companies/).
By focusing on gaming communities, Discord has differentiated itself from the many other communication apps. Discord is well received and has a rapidly growing user base. They plan to keep their basic offerings free for unlimited users and hope to make money with premium offerings (themes, add-ons, content, and more).
## Join us!
More than 500 of us have already migrated to the new Reactiflux. Join us, we're one click away: [http://join.reactiflux.com](http://join.reactiflux.com/)
*Note: Jordan Hawkers thorough [research](http://jhawk.co/team-chat-comparison) made our decision a lot easier.*

View File

@@ -0,0 +1,40 @@
---
title: "React v0.14.1"
author: zpao
---
After a couple weeks of having more people use v0.14, we're ready to ship a patch release addressing a few issues. Thanks to everybody who has reported issues and written patches!
The release is now available for download:
* **React**
Dev build with warnings: <https://fb.me/react-0.14.1.js>
Minified build for production: <https://fb.me/react-0.14.1.min.js>
* **React with Add-Ons**
Dev build with warnings: <https://fb.me/react-with-addons-0.14.1.js>
Minified build for production: <https://fb.me/react-with-addons-0.14.1.min.js>
* **React DOM** (include React in the page before React DOM)
Dev build with warnings: <https://fb.me/react-dom-0.14.1.js>
Minified build for production: <https://fb.me/react-dom-0.14.1.min.js>
We've also published version `0.14.1` of the `react`, `react-dom`, and addons packages on npm and the `react` package on bower.
- - -
## Changelog
### React DOM
- Fixed bug where events wouldn't fire in old browsers when using React in development mode
- Fixed bug preventing use of `dangerouslySetInnerHTML` with Closure Compiler Advanced mode
- Added support for `srcLang`, `default`, and `kind` attributes for `<track>` elements
- Added support for `color` attribute
- Ensured legacy `.props` access on DOM nodes is updated on re-renders
### React TestUtils Add-on
- Fixed `scryRenderedDOMComponentsWithClass` so it works with SVG
### React CSSTransitionGroup Add-on
- Fix bug preventing `0` to be used as a timeout value
### React on Bower
- Added `react-dom.js` to `main` to improve compatibility with tooling

View File

@@ -0,0 +1,31 @@
---
title: "React v0.14.2"
author: zpao
---
We have a quick update following the release of 0.14.1 last week. It turns out we broke a couple things in the development build of React when using Internet Explorer. Luckily it was only the development build, so your production applications were unaffected. This release is mostly to address those issues. There is one notable change if consuming React from npm. For the `react-dom` package, we moved `react` from a regular dependency to a peer dependency. This will impact very few people as these two are typically installed together at the top level, but it will fix some issues with dependencies of installed components also using `react` as a peer dependency.
The release is now available for download:
* **React**
Dev build with warnings: <https://fb.me/react-0.14.2.js>
Minified build for production: <https://fb.me/react-0.14.2.min.js>
* **React with Add-Ons**
Dev build with warnings: <https://fb.me/react-with-addons-0.14.2.js>
Minified build for production: <https://fb.me/react-with-addons-0.14.2.min.js>
* **React DOM** (include React in the page before React DOM)
Dev build with warnings: <https://fb.me/react-dom-0.14.2.js>
Minified build for production: <https://fb.me/react-dom-0.14.2.min.js>
We've also published version `0.14.2` of the `react`, `react-dom`, and addons packages on npm and the `react` package on bower.
- - -
## Changelog
### React DOM
- Fixed bug with development build preventing events from firing in some versions of Internet Explorer & Edge
- Fixed bug with development build when using es5-sham in older versions of Internet Explorer
- Added support for `integrity` attribute
- Fixed bug resulting in `children` prop being coerced to a string for custom elements, which was not the desired behavior.
- Moved `react` from `dependencies` to `peerDependencies` to match expectations and align with `react-addons-*` packages

View File

@@ -0,0 +1,40 @@
---
title: "React v0.14.3"
author: zpao
---
It's time for another installment of React patch releases! We didn't break anything in v0.14.2 but we do have a couple of other bugs we're fixing. The biggest change in this release is actually an addition of a new built file. We heard from a number of people that they still need the ability to use React to render to a string on the client. While the use cases are not common and there are other ways to achieve this, we decided that it's still valuable to support. So we're now building `react-dom-server.js`, which will be shipped to Bower and in the `dist/` directory of the `react-dom` package on npm. This file works the same was as `react-dom.js` and therefore requires that the primary React build has already been included on the page.
The release is now available for download:
* **React**
Dev build with warnings: <https://fb.me/react-0.14.3.js>
Minified build for production: <https://fb.me/react-0.14.3.min.js>
* **React with Add-Ons**
Dev build with warnings: <https://fb.me/react-with-addons-0.14.3.js>
Minified build for production: <https://fb.me/react-with-addons-0.14.3.min.js>
* **React DOM** (include React in the page before React DOM)
Dev build with warnings: <https://fb.me/react-dom-0.14.3.js>
Minified build for production: <https://fb.me/react-dom-0.14.3.min.js>
* **React DOM Server** (include React in the page before React DOM Server)
Dev build with warnings: <https://fb.me/react-dom-server-0.14.3.js>
Minified build for production: <https://fb.me/react-dom-server-0.14.3.min.js>
We've also published version `0.14.3` of the `react`, `react-dom`, and addons packages on npm and the `react` package on bower.
- - -
## Changelog
### React DOM
- Added support for `nonce` attribute for `<script>` and `<style>` elements
- Added support for `reversed` attribute for `<ol>` elements
### React TestUtils Add-on
- Fixed bug with shallow rendering and function refs
### React CSSTransitionGroup Add-on
- Fixed bug resulting in timeouts firing incorrectly when mounting and unmounting rapidly
### React on Bower
- Added `react-dom-server.js` to expose `renderToString` and `renderToStaticMarkup` for usage in the browser

View File

@@ -9,7 +9,12 @@ id: all-posts
<div class="inner-content">
<h1>All Posts</h1>
{% for page in site.posts %}
<p><strong><a href="/react{{ page.url }}">{{ page.title }}</a></strong> on {{ page.date | date: "%B %e, %Y" }} by {{ page.author.name }}</p>
<p><strong><a href="/react{{ page.url }}">{{ page.title }}</a></strong> on {{ page.date | date: "%B %e, %Y" }} by
{% for author in page.authors %}
{{ author.name }}
{% if forloop.last == false %} and {% endif %}
{% endfor %}
</p>
{% endfor %}
</div>
</section>

View File

@@ -390,6 +390,38 @@ h1, h2, h3, h4, h5, h6 {
@include clearfix;
}
/* JSX Compiler */
.jsxCompiler {
margin: 0 auto;
padding-top: 20px;
width: 1220px;
label.compiler-option {
display: block;
margin-top: 5px;
}
#jsxCompiler {
margin-top: 20px;
}
.playgroundPreview {
padding: 0;
width: 600px;
pre {
@include code-typography;
}
}
.playgroundError {
// The compiler view kills padding in order to render the CodeMirror code
// more nicely. For the error view, put a padding back
padding: 15px 20px;
}
}
.docs-prev {
float: left;
}

View File

@@ -0,0 +1,28 @@
---
id: why-react-de-DE
title: Warum React?
permalink: why-react-de-DE.html
---
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.
Wir haben React für folgende Aufgabe entwickelt: **umfangreiche Anwendungen zu bauen, deren Daten sich zeitlich ändern**.
## Einfach
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.
## Deklarativ
Bei Datenveränderungen drückt React bildlich die "Aktualisieren"-Taste und versteht sich darauf, nur die veränderten Elemente zu erneuern.
## Baue zusammensetzbare Komponenten
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.
## Gib' ihnen fünf Minuten
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.
## Erfahre mehr
Erfahre mehr über unsere Motivation zur Entwicklung von React in [diesem Blogeintrag](/react/blog/2013/06/05/why-react.html).

View File

@@ -5,13 +5,13 @@ permalink: why-react-zh-CN.html
next: displaying-data-zh-CN.html
---
React 是一个 Facebook 和 Instagram 用来创建用户界面的 JavaScript 库。很人多认为 React 是 **[MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)** 中的 **V**(视图)。
React 是一个 Facebook 和 Instagram 用来创建用户界面的 JavaScript 库。很多人选择将 React 认为**[MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)** 中的 **V**(视图)。
我们创造 React 是为了解决一个问题:**构建随着时间数据不断变化的大规模应用程序**。
### 简单
仅仅只要表达出你的应用程序在任一个时间点应该的样子然后当底层的数据变了React 会自动处理所有用户界面的更新。
仅仅只要表达出你的应用程序在任一个时间点应该呈现的样子然后当底层的数据变了React 会自动处理所有用户界面的更新。
### 声明式 (Declarative)

View File

@@ -19,6 +19,7 @@ UI를 가지고 할 수 있는 가장 기초적인 것은 데이터를 표시하
<meta charset="UTF-8" />
<title>Hello React</title>
<script src="https://fb.me/react-{{site.react_version}}.js"></script>
<script src="https://fb.me/react-dom-{{site.react_version}}.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
</head>
<body>
@@ -54,7 +55,6 @@ setInterval(function() {
}, 500);
```
## 반응 적(Reactive) 업데이트
`hello-react.html` 파일을 웹 브라우저에서 열어 당신의 이름을 텍스트 필드에 써 보세요. React는 단지 시간을 표시하는 부분만을 바꿉니다 — 텍스트 필드 안에 입력한 것은 그대로 남아 있구요, 당신이 이 동작을 관리하는 그 어떤 코드도 쓰지 않았음에도 불구하고 말이죠. React는 그걸 올바른 방법으로 알아서 해줍니다.
@@ -63,7 +63,6 @@ setInterval(function() {
이 컴포넌트에 대한 입력은 `props` 라고 불립니다 — "properties" 를 줄인 것이죠. 그들은 JSX 문법에서는 어트리뷰트로서 전달됩니다. 당신은 `props` 를 컴포넌트 안에서 불변의(immutable) 엘리먼트로서 생각해야 하고, `this.props` 를 덮어씌우려고 해서는 안됩니다.
## 컴포넌트들은 함수와 같습니다
React 컴포넌트들은 매우 단순합니다. 당신은 그것들을 `props``state` (이것들은 나중에 언급할 것입니다) 를 받고 HTML을 렌더링하는 단순한 함수들로 생각해도 됩니다. 이걸 염두하면, 컴포넌트의 작동을 이해하는 것도 쉽습니다.
@@ -72,7 +71,6 @@ React 컴포넌트들은 매우 단순합니다. 당신은 그것들을 `props`
>
> **한가지 제약이 있습니다**: React 컴포넌트들은 단 하나의 루트 노드(root node)만을 렌더할 수 있습니다. 만약 여러개의 노드들을 리턴하고 싶다면, 그것들은 단 하나의 루트 노드로 싸여져 있어야만 합니다.
## JSX 문법
우리는 컴포넌트를 사용하는 것이 "템플릿"과 "디스플레이 로직(display logic)"을 이용하는 것보다 관심을 분리(separate concerns)하는 데에 올바른 방법이라고 강하게 믿고 있습니다. 우리는 마크업과 그것을 만들어내는 코드는 친밀하게 함께 결합되어있다고 생각합니다. 또한, 디스플레이 로직은 종종 매우 복잡하고, 그것을 템플릿 언어를 이용해 표현하는 것은 점점 사용하기 어렵게 됩니다.
@@ -91,12 +89,11 @@ JSX를 이용하면:
우리는 이것이 React 앱들을 만들기 쉽게 하고, 디자이너들이 이 문법을 더 선호하는 것을 발견했습니다, 하지만 모든 사람은 그들만의 선호하는 워크플로우가 있기 마련이므로, **JSX는 React를 사용하기 위해 필수적이지는 않습니다.**
JSX는 매우 작은 언어입니다. 그것을 배우고 싶다면, [JSX 깊게 살펴보기](/react/docs/jsx-in-depth-ko-KR.html). 를 살펴 보시기 바랍니다. 또는, [우리의 온라인 JSX 컴파일러](/react/jsx-compiler.html)를 통해 문법이 변환되는 것을 살펴 보시기 바랍니다.
JSX는 매우 작은 언어입니다. 그것을 배우고 싶다면, [JSX 깊게 살펴보기](/react/docs/jsx-in-depth-ko-KR.html)를 살펴 보시기 바랍니다. 또는, [바벨 REPL](https://babeljs.io/repl/)를 통해 문법이 변환되는 것을 살펴 보시기 바랍니다.
JSX는 HTML과 비슷하지만, 완전히 똑같지는 않습니다. [JSX의 실수하기 쉬운 부분들](/react/docs/jsx-gotchas-ko-KR.html)에 중요한 차이점들에 대해 설명되어 있습니다.
JSX를 사용하기 시작하기 위한 가장 쉬운 방법은 브라우저에서 작동하는 `JSXTransformer`를 사용하는 것입니다. 우리는 이것을 프로덕션에서는 사용하지 않기를 강하게 권장하는 바입니다. 당신은 우리의 커맨드 라인 [react-tools](https://www.npmjs.com/package/react-tools) 패키지를 이용하여 미리 컴파일(precompile)해 사용할 수 있습니다.
[바벨에서 JSX를 시작하는 여러 방법을 제공합니다](http://babeljs.io/docs/setup/). 여기에는 커맨드 라인 툴부터 루비 온 레일스 연동까지 다양한 방법이 있습니다. 가장 편한 툴을 사용하세요.
## JSX 없이 React 사용하기

View File

@@ -8,7 +8,6 @@ next: jsx-in-depth.html
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.
## Getting Started
Let's look at a really simple example. Create a `hello-react.html` file with the following code:
@@ -20,6 +19,7 @@ Let's look at a really simple example. Create a `hello-react.html` file with the
<meta charset="UTF-8" />
<title>Hello React</title>
<script src="https://fb.me/react-{{site.react_version}}.js"></script>
<script src="https://fb.me/react-dom-{{site.react_version}}.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
</head>
<body>
@@ -55,7 +55,6 @@ setInterval(function() {
}, 500);
```
## Reactive Updates
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.
@@ -64,7 +63,6 @@ The way we are able to figure this out is that React does not manipulate the DOM
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`**.
## Components are Just Like Functions
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.
@@ -73,7 +71,6 @@ React components are very simple. You can think of them as simple functions that
>
> **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.
## JSX Syntax
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.
@@ -98,7 +95,6 @@ JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/
[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.
## React without JSX
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.

View File

@@ -21,6 +21,7 @@ next: jsx-in-depth-zh-CN.html
<meta charset="UTF-8" />
<title>Hello React</title>
<script src="https://fb.me/react-{{site.react_version}}.js"></script>
<script src="https://fb.me/react-dom-{{site.react_version}}.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
</head>
<body>
@@ -95,16 +96,16 @@ JSX 非常小上面“hello, world”的例子使用了 JSX 所有的特性
JSX 类似于 HTML但不是完全一样。参考 [JSX 陷阱](/react/docs/jsx-gotchas-zh-CN.html) 学习关键区别。
最简单开始学习 JSX 的方法就是使用浏览器端的 `JSXTransformer`。我们强烈建议你不要在生产环境中使用它。你可以通过我们的命令行工具 [react-tools](https://www.npmjs.com/package/react-tools) 包来预编译你的代码
[Babel 公开了一些使用 JSX 的方式],从命令行工具到 Ruby on Rails 集成。选择一个对你来说最合适的工具
## 没有 JSX 的 React
你完全可以选择是否使用 JSX并不是 React 必须。你可以通过 `React.createElement` 来创建一个树。第一个参数是标签,第二个参数是一个属性对象,每三个是子节点。
JSX完全是可选的你无需在 React 必须使用 JSX。你可以通过 `React.createElement` 来创建一个树。第一个参数是标签,第二个参数是一个属性对象,每三个是子节点。
```javascript
var child = React.createElement('li', null, 'Text Content');
var root = React.createElement('ul', { className: 'my-list' }, child);
var child1 = React.createElement('li', null, 'First Text Content');
var child2 = React.createElement('li', null, 'Second Text Content');
var root = React.createElement('ul', { className: 'my-list' }, child1, child2);
ReactDOM.render(root, document.getElementById('example'));
```
@@ -121,6 +122,7 @@ React 已经为 HTML 标签提供内置工厂方法。
```javascript
var root = React.DOM.ul({ className: 'my-list' },
React.DOM.li(null, 'Text Content')
);
React.DOM.li(null, 'Text Content')
);
```

View File

@@ -216,4 +216,4 @@ var content = (
```
> 注意:
> JSXはHTMLに似ていますが、全く同じではありません。いくつかのキーの違いについては[JSXの理解](/react/docs/jsx-gotchas.html) をご覧ください。
> JSXはHTMLに似ていますが、全く同じではありません。いくつかのキーの違いについては[JSXの理解](/react/docs/jsx-gotchas.html) をご覧ください。

View File

@@ -83,7 +83,7 @@ var Nav = React.createClass({ });
var Nav = React.createClass({displayName: "Nav", });
```
[JSX 컴파일러](/react/jsx-compiler.html)를 보면 JSX에서 어떻게 네이티브 JavaScript로 변환(desugars)하는지 볼 수 있고, [HTML-JSX 변환기](/react/html-jsx.html)는 이미 있는 HTML을 JSX로 변환해 줍니다.
[바벨 REPL](https://babeljs.io/repl/)를 보면 JSX에서 어떻게 네이티브 JavaScript로 변환(desugars)하는지 볼 수 있고, [HTML-JSX 변환기](/react/html-jsx.html)는 이미 있는 HTML을 JSX로 변환해 줍니다.
JSX를 사용 하시려면, [시작하기](/react/docs/getting-started-ko-KR.html) 가이드에서 어떻게 컴파일을 하기 위해 설정하는지 보실 수 있습니다.

View File

@@ -22,7 +22,7 @@ It doesn't alter the semantics of JavaScript.
React can either render HTML tags (strings) or React components (classes).
To render a HTML tag, just use lower-case tag names in JSX:
To render an HTML tag, just use lower-case tag names in JSX:
```javascript
var myDivElement = <div className="foo" />;

View File

@@ -99,7 +99,7 @@ var Nav = React.createClass({displayName: "Nav", });
如果你正在构建一个有很多子组件的组件,比如表单,你也许会最终得到许多的变量声明。
```javascript
// 尴尬的变量声明块
// 尴尬的变量声明块
var Form = MyFormComponent;
var FormRow = Form.Row;
var FormLabel = Form.Label;
@@ -221,5 +221,5 @@ var content = (
```
> 注意:
>
>
> JSX 类似于 HTML但不完全一样。参考 [JSX 陷阱](/react/docs/jsx-gotchas-zh-CN.html) 了解主要不同。

View File

@@ -12,7 +12,7 @@ next: jsx-gotchas-ko-KR.html
var component = <Component foo={x} bar={y} />;
```
## Props의 변경은 나빠요.[^1]
## Props의 변경은 나빠요
하지만 어떤 프로퍼티를 설정하고 싶은지 모른다면, 객체 레이어에 넣고 싶어질 수도 있습니다.
@@ -50,7 +50,3 @@ props는 변하지 않는 것으로 간주해야 합니다. props 객체를 변
## 이상한 `...` 표기법은 무엇인가요?
`...` 연산자(스프레드 연산자)는 이미 [ES6의 배열](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)에서 지원합니다. [객체 rest와 스프레드 프로퍼티](https://github.com/sebmarkbage/ecmascript-rest-spread)에 대한 ES7의 제안도 있습니다. JSX의 구문을 더 깔끔하게 하기 위해 지원되고 개발중인 표준을 활용하고 있습니다.
[^1]: 아무래도 좋지만, 이 제목의 원문 "Mutating Props is Bad, mkay"는 사우스 파크에
나온 대사 "[Drug is bad, mkay](https://www.youtube-nocookie.com/watch?v=Uh7l8dx-h8M)"의
패러디입니다.

View File

@@ -12,7 +12,7 @@ If you know all the properties that you want to place on a component ahead of ti
var component = <Component foo={x} bar={y} />;
```
## Mutating Props is Bad, mkay
## Mutating Props is Bad
If you don't know which properties you want to set, you might be tempted to add them onto the object later:

View File

@@ -27,7 +27,7 @@ If you want to display an HTML entity within dynamic content, you will run into
<div>{'First &middot; Second'}</div>
```
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.
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.
```javascript
<div>{'First · Second'}</div>
@@ -61,6 +61,12 @@ If you pass properties to native HTML elements that do not exist in the HTML spe
<div data-custom-attribute="foo" />
```
However, arbitrary attributes are supported on custom elements (those with a hyphen in the tag name or an `is="..."` attribute).
```javascript
<x-my-component custom-attribute="foo" />
```
[Web Accessibility](http://www.w3.org/WAI/intro/aria) attributes starting with `aria-` will be rendered properly.
```javascript

View File

@@ -78,7 +78,7 @@ Reactがデータの変更を通知する共通な方法は `setState(data, call
`this.state` UIのstateを表す必要がある最小限の量のデータだけを保持するべきです。このような点で以下のようなものは保持するべきではありません。
* **計算されたデータ:**
* **計算されたデータ:**
stateに基づく事前に計算された値について心配は要りません。 `render()` を用いて、全ての計算を行って、UIの一貫性を保証するよりも簡単です。例えば、stateにリスト化されたアイテムの配列を持っていて、文字列としてその数をレンダリングしたいとして、それらをstateに保持するよりも `render()` メソッドに `this.state.listItems.length + ' list items'` を単純にレンダリングすれば良いのです。
* **Reactのコンポーネント:** 隠れたpropsとstateに基づいて `render()` でそれらをビルドしてください。
* **propsからコピーしたデータ:** 可能であれば、propsを真のソースとして使ってみてください。propsは時とともに変化し得るので、正しくstateにpropsを保持する使い方は、以前の値を知っていることになり得ます。
* **propsからコピーしたデータ:** 可能であれば、propsを真のソースとして使ってみてください。propsは時とともに変化し得るので、正しくstateにpropsを保持する使い方は、以前の値を知っていることになり得ます。

View File

@@ -8,7 +8,6 @@ next: multiple-components-ko-KR.html
이미 React에서 [어떻게 데이터를 표시](/react/docs/displaying-data-ko-KR.html)하는지를 배웠습니다. 이제 UI와의 상호작용을 어떻게 만드는지 살펴보죠.
## 간단한 예제
```javascript
@@ -35,34 +34,29 @@ ReactDOM.render(
);
```
## 이벤트 핸들링과 통합적인(Synthetic) 이벤트
React에서의 이벤트 핸들러는 HTML에서 그러던 것처럼 간단히 카멜케이스 프로퍼티(camelCased prop)로 넘기면 됩니다. React의 모든 이벤트는 통합적인 이벤트 시스템의 구현으로 IE8 이상에서는 같은 행동이 보장됩니다. 즉, React는 사양에 따라 어떻게 이벤트를 일으키고(bubble) 잡는지 알고 있고, 당신이 사용하는 브라우저와 관계없이 이벤트 핸들러에 전달되는 이벤트는 [W3C 사양](http://www.w3.org/TR/DOM-Level-3-Events/)과 같도록 보장됩니다.
## 기본 구현: 오토바인딩과 이벤트 델리게이션
<a name="under-the-hood-autobinding-and-event-delegation"></a>
코드를 고성능으로 유지하고 이해하기 쉽게 하기 위해, React는 보이지 않는 곳에서 몇 가지 일을 수행합니다.
**오토바인딩:** JavaScript에서 콜백을 만들 때, 보통은 `this`의 값이 정확하도록 명시적으로 메소드를 인스턴스에 바인드해야 합니다. React에서는 모든 메소드가 자동으로 React의 컴포넌트 인스턴스에 바인드됩니다. React가 바인드 메소드를 캐시하기 때문에 매우 CPU와 메모리에 효율적입니다. 타이핑해야 할 것도 줄어들죠!
**오토바인딩:** JavaScript에서 콜백을 만들 때, 보통은 `this`의 값이 정확하도록 명시적으로 메소드를 인스턴스에 바인드해야 합니다. React에서는 모든 메소드가 자동으로 React의 컴포넌트 인스턴스에 바인드됩니다.(ES6 클래스 문법을 사용할 때는 재외하고) React가 바인드 메소드를 캐시하기 때문에 매우 CPU와 메모리에 효율적입니다. 타이핑해야 할 것도 줄어들죠!
**이벤트 델리게이션:** React는 실제로는 노드자신에게 이벤트 핸들러를 붙이지 않습니다. React가 시작되면 React는 탑 레벨의 단일 이벤트 리스너로 모든 이벤트를 리스닝하기 시작합니다. 컴포넌트가 마운트되거나 언마운트 될 때, 이벤트 핸들러는 그냥 내부 매핑에서 넣거나 뺄 뿐입니다. 이벤트가 발생하면, React는 이 매핑을 사용해서 어떻게 디스패치할 지를 알게 됩니다. 매핑에 이벤트 핸들러가 남아있지 않으면, React의 이벤트 핸들러는 그냥 아무것도 하지 않습니다. 왜 이 방식이 빠른지 더 알고 싶으시면, [David Walsh의 멋진 블로그 글](http://davidwalsh.name/event-delegate)을 읽어 보세요.
## 컴포넌트는 그냥 state 머신일 뿐
React는 UI를 간단한 state 머신이라 생각합니다. UI를 다양한 state와 그 state의 렌더링으로 생각함으로써 UI를 일관성 있게 관리하기 쉬워집니다.
React에서는, 간단히 컴포넌트의 state를 업데이트하고, 이 새로운 state의 UI를 렌더링합니다. React는 DOM의 변경을 가장 효율적인 방법으로 관리해줍니다.
## state의 동작 원리
React에게 데이터의 변경을 알리는 일반적인 방법은 `setState(data, callback)`을 호출하는 것입니다. 이 메소드는 `this.state``data`를 머지하고 컴포넌트를 다시 렌더링 합니다. 컴포넌트의 재-렌더링이 끝나면, 생략가능한 `callback`이 호출됩니다. 대부분의 경우 React가 UI를 최신상태로 유지해주기 때문에 `callback`을 사용할 필요가 없습니다.
## 어떤 컴포넌트가 state를 가져야 할까요?
대부분의 컴포넌트는 `props`로부터 데이터를 받아 렌더할 뿐입니다만, 가끔 유저 인풋, 서버 요청, 시간의 경과에 반응해야 할 필요가 있습니다. 이럴 때 state를 사용합니다.
@@ -71,7 +65,6 @@ React에게 데이터의 변경을 알리는 일반적인 방법은 `setState(da
일반적인 패턴은 데이터만 렌더하는 여러 상태를 가지지 않은 컴포넌트를 만들고, 그 위에 상태기반(stateful) 컴포넌트를 만들어 계층 안의 자식 컴포넌트에게 `props`를 통해 state를 전달하는 것입니다. state를 가지지 않은 컴포넌트가 선언적인 방법으로 데이터를 렌더링 하는 동안, 상태기반 컴포넌트는 모든 상호작용 로직을 캡슐화합니다.
## state를 어떻게 *써야* 할까요?
**state는 컴포넌트의 이벤트 핸들러에 의해 UI 업데이트를 트리거할때 변경될 가능성이 있어, 그때 사용할 데이터를 가져야 합니다.** 실제 앱에서는 이 데이터는 매우 작고 JSON 직렬화 가능한 경향이 있습니다. 상태기반 컴포넌트를 만들때, 가능한 작게 state를 서술하고 `this.state`에만 저장하도록 해보세요. 그냥 `render()` 안에서 이 state를 기반으로 다른 모든 정보를 계산합니다. 이 방식으로 애플리케이션을 작성하고 생각하면 가장 최적의 애플리케이션으로 발전해가는 경향이 있다는 것을 발견하게 될 것입니다. 꼭 필요하지 않은 값이나 계산된 값을 state에 추가하는 것은 render가 그것을 계산하는 대신에 명시적으로 그것들을 맞춰줘야 하는 것을 의미하기 때문이죠.
@@ -82,4 +75,4 @@ React에게 데이터의 변경을 알리는 일반적인 방법은 `setState(da
* **계산된 데이터:** state에 따라 값을 미리 계산하는 것에 대해 염려하지 마세요. 계산은 모두 `render()`에서 하는 것이 UI의 일관성을 유지하기 쉽습니다. 예를 들어, state에서 list items 배열을 가지고 있고 문자열으로 카운트를 렌더링 할 경우, state에 저장하기보다는 그냥 `render()` 메소드안에서 `this.state.listItems.length + ' list items'`를 렌더하세요.
* **React 컴포넌트:** 가지고 있는 props와 state로 `render()`안에서 만드세요.
* **props에서 복사한 데이터:** 가능한 한 원래의 소스로 props를 사용하도록 해보세요. props를 state에 저장하는 단 하나의 올바른 사용법은 이전 값을 알고 싶을 때입니다. props는 시간이 지나면 변경될 수도 있기 때문이죠.
* **props에서 복사한 데이터:** 가능한 한 원래의 소스로 props를 사용하도록 해보세요. props를 state에 저장하는 단 하나의 올바른 사용법은 이전 값을 알고 싶을 때입니다. props는 부모 컴포넌트의 재 렌더링의 결과 변경될 수도 있기 때문이죠.

View File

@@ -8,7 +8,6 @@ next: multiple-components.html
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.
## A Simple Example
```javascript
@@ -35,12 +34,10 @@ ReactDOM.render(
);
```
## Event Handling and Synthetic Events
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 identically in IE8 and above 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.
## Under the Hood: Autobinding and Event Delegation
Under the hood, React does a few things to keep your code performant and easy to understand.
@@ -49,19 +46,16 @@ Under the hood, React does a few things to keep your code performant and easy to
**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).
## Components are Just State Machines
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.
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.
## How State Works
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.
## What Components Should Have State?
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.
@@ -70,15 +64,14 @@ Most of your components should simply take some data from `props` and render it.
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.
## What *Should* Go in State?
**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.
## What *Shouldnt* Go in State?
## What *Shouldn't* Go in State?
`this.state` should only contain the minimal amount of data needed to represent your UI's state. As such, it should not contain:
* **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.
* **React components:** Build them in `render()` based on underlying props and state.
* **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 can change over time.
* **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.

View File

@@ -8,12 +8,10 @@ next: reusable-components-ko-KR.html
지금까지, 단일 컴포넌트에서 데이터를 표시하고 유저 입력을 다루는 것을 살펴보았습니다. 다음엔 React의 최고의 기능 중 하나인 조합가능성(composability)을 살펴봅시다.
## 동기: 관심의 분리
명확히 정의된 인터페이스와 다른 컴포넌트를 재사용해 모듈러 컴포넌트를 구축하면, 함수와 클래스를 이용했을 때 얻을 수 있는 이점 대부분을 얻을 수 있습니다. 특히 앱에서 *다른 관심을 분리*할 수 있습니다.아무리 간단히 새 컴포넌트를 만들었다고 해도 말이죠. 당신의 애플리케이션에서 쓸 커스텀 컴포넌트 라이브러리를 만들어서, 당신의 도메인에 최적화된 방법으로 UI를 표현할 수 있게 됩니다.
## 조합(Composition) 예제
간단히 페이스북 그래프 API를 사용해 프로필 사진과 유저이름을 보여주는 아바타 컴포넌트를 만든다고 합시다.
@@ -54,14 +52,12 @@ ReactDOM.render(
);
```
## 소유권(Ownership)
위의 예제에서, `Avatar` 인스턴스는 `ProfilePic``ProfileLink`인스턴스를 *가지고* 있습니다. React에서 **소유자는 다른 컴포넌트의 `props`를 설정하는 컴포넌트입니다**. 더 정식으로 말하면, `X` 컴포넌트가 `Y` 컴포넌트의 `render()` 메소드 안에서 만들어졌다면, `Y``X`*소유하고* 있다고 합니다. 앞에서 설명한 바와 같이, 컴포넌트는 자신의 `props`를 변경할 수 없습니다. `props`는 언제나 소유자가 설정한 것과 일치합니다. 이와 같은 중요한 성질은 UI가 일관성 있도록 해줍니다.
위의 예제에서, `Avatar` 인스턴스는 `ProfilePic``ProfileLink`인스턴스를 *가지고* 있습니다. React에서 **소유자는 다른 컴포넌트의 `props`를 설정하는 컴포넌트입니다**. 더 정식으로 말하면, `X` 컴포넌트가 `Y` 컴포넌트의 `render()` 메소드 안에서 만들어졌다면, `Y``X`*소유하고* 있다고 합니다. 앞에서 설명한 바와 같이, 컴포넌트는 자신의 `props`를 변경할 수 없습니다. `props`는 언제나 소유자가 설정한 것과 일치합니다. 이와 같은 근본적인 불변성은 UI가 일관성 있도록 해줍니다.
소유(owner-ownee)관계와 부모·자식 관계를 구별하는 것은 중요합니다. 부모·자식 관계가 DOM에서부터 쓰던 익숙하고 이미 알고있던 단순한 것인 한편, 소유관계는 React 고유의 것입니다. 위의 예제에서, `Avatar``div`, `ProfilePic`, `ProfileLink`인스턴스를 소유하고, `div``ProfilePic``ProfileLink`인스턴스의 (소유자가 아닌) **부모**입니다.
## 자식
React 컴포넌트 인스턴스를 만들 때, 추가적인 React 컴포넌트나 JavaScript 표현식을 시작과 끝 태그 사이에 넣을 수 있습니다. 이렇게 말이죠.
@@ -72,7 +68,6 @@ React 컴포넌트 인스턴스를 만들 때, 추가적인 React 컴포넌트
`Parent``this.props.children`라는 특수 prop으로 자식들을 읽을 수 있습니다. **`this.props.children` 는 불투명한 데이터 구조이며,** [React.Children 유틸리티](/react/docs/top-level-api-ko-KR.html#react.children)를 사용해 자식들을 관리합니다.
### 자식 Reconciliation (비교조정)
**Reconciliation은 React가 DOM을 각각 새로운 렌더 패스에 업데이트하는 과정입니다.** 일반적으로, 자식은 렌더하는 순서에 따라 비교조정됩니다. 예를 들어, 각각의 마크업을 생성하는 두 개의 렌더 패스가 있다고 해봅시다.
@@ -91,7 +86,6 @@ React 컴포넌트 인스턴스를 만들 때, 추가적인 React 컴포넌트
직관적으로 보면, `<p>Paragraph 1</p>`가 없어졌습니다만 그러는 대신에, React는 첫 번째 자식의 텍스트를 비교조정하고 마지막 자식을 파괴하도록 DOM을 비교조정할 것입니다. React는 자식들의 *순서*에 따라 비교조정합니다.
### 상태기반(Stateful) 자식
대부분의 컴포넌트에서는, 이것은 큰 문제가 아닙니다. 하지만 렌더 패스 간에 `this.state`를 유지하는 상태기반의 컴포넌트에서는 매우 문제가 될 수 있습니다.
@@ -111,7 +105,6 @@ React 컴포넌트 인스턴스를 만들 때, 추가적인 React 컴포넌트
</Card>
```
<a name="dynamic-children"></a>
### 동적 자식
@@ -179,7 +172,6 @@ ReactFragment 객체를 넘기는 것으로 자식에 키를 할당할 수도
React에서 데이터는 위에서 말한 것처럼 `props`를 통해 소유자로부터 소유한 컴포넌트로 흐릅니다. 이것은 사실상 단방향 데이터 바인딩입니다. 소유자는 `props``state`를 기준으로 계산한 어떤 값으로 소유한 컴포넌트의 props를 바인드합니다. 이 과정은 재귀적으로 발생하므로, 데이터의 변경은 자동으로 모든 곳에 반영됩니다.
## 성능의 주의점
소유자가 가지고 있는 노드의 수가 많아지면 데이터가 변화하는 비용이 증가할 것으로 생각할 수도 있습니다. 좋은 소식은 JavaScript의 속도는 빠르고 `render()` 메소드는 꽤 간단한 경향이 있어, 대부분 애플리케이션에서 매우 빠르다는 점입니다. 덧붙여, 대부분의 병목 현상은 JS 실행이 아닌 DOM 변경에서 일어나고, React는 배치와 탐지 변경을 이용해 최적화해 줍니다.

View File

@@ -8,12 +8,10 @@ next: reusable-components.html
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.
## Motivation: Separation of Concerns
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.
## Composition Example
Let's create a simple Avatar component which shows a profile picture and username using the Facebook Graph API.
@@ -54,14 +52,12 @@ ReactDOM.render(
);
```
## Ownership
In the above example, instances of `Avatar` *own* instances of `ProfilePic` and `ProfileLink`. 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.
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`, `ProfilePic` and `ProfileLink` instances, and `div` is the **parent** (but not owner) of the `ProfilePic` and `ProfileLink` instances.
## Children
When you create a React component instance, you can include additional React components or JavaScript expressions between the opening and closing tags like this:
@@ -72,7 +68,6 @@ When you create a React component instance, you can include additional React com
`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.
### Child Reconciliation
**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:
@@ -91,7 +86,6 @@ When you create a React component instance, you can include additional React com
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.
### Stateful Children
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.
@@ -111,7 +105,6 @@ In most cases, this can be sidestepped by hiding elements instead of destroying
</Card>
```
### Dynamic Children
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`:
@@ -178,7 +171,6 @@ You can also key children by passing a ReactFragment object. See [Keyed Fragment
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.
## A Note on Performance
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.

View File

@@ -168,7 +168,7 @@ var MyComponent = React.createClass({
});
```
也可以传递ReactFragment 对象 来做有 key 的子级。详见[Keyed Fragments](create-fragment.html)
也可以传递ReactFragment 对象 来做有 key 的子级。详见[Keyed Fragments](create-fragment.html)
## 数据流
@@ -182,5 +182,5 @@ React 里,数据通过上面介绍过的 `props` 从拥有者流向归属者
但是,有时候需要做细粒度的性能控制。这种情况下,可以重写 `shouldComponentUpdate()` 方法返回 false 来让 React 跳过对子树的处理。参考 [React reference docs](/react/docs/component-specs.html) 了解更多。
> 注意:
>
>
> 如果在数据变化时让 `shouldComponentUpdate()` 返回 falseReact 就不能保证用户界面同步。当使用它的时候一定确保你清楚到底做了什么,并且只在遇到明显性能问题的时候才使用它。不要低估 JavaScript 的速度DOM 操作通常才是慢的原因。

View File

@@ -227,4 +227,4 @@ Counter.defaultProps = { initialCount: 0 };
### ミックスインはありません
不幸なことに、ES6はミックスインのサポートを行いません。それゆえ、ReactをES6のクラスと一緒に使う際にはミックスインのサポートはありません。代わりに、ミックスインに頼ることなくそれらのユースケースをサポートするのが簡単になるよう努力しています。
不幸なことに、ES6はミックスインのサポートを行いません。それゆえ、ReactをES6のクラスと一緒に使う際にはミックスインのサポートはありません。代わりに、ミックスインに頼ることなくそれらのユースケースをサポートするのが簡単になるよう努力しています。

View File

@@ -8,7 +8,6 @@ next: transferring-props-ko-KR.html
인터페이스를 설계할 때, 공통적으로 사용되는 디자인 요소들(버튼, 폼 필드, 레이아웃 컴포넌트 등.)을 잘 정의된 인터페이스의 재사용 가능한 컴포넌트로 분해합니다. 이런 방법으로 다음에 UI를 구축할 때에는 훨씬 적은 코드로 만들 수 있습니다. 이 말은 더 빠른 개발 시간, 더 적은 버그, 더 적은 용량으로 할 수 있다는 뜻이죠.
## Prop 검증
앱의 규모가 커지면 컴포넌트들이 바르게 사용되었는지 확인하는게 도움이 됩니다. 확인은 `propTypes`를 명시해서 할 수 있습니다. `React.PropTypes`는 받은 데이터가 적절한지(valid) 확인하는데 사용할 수 있는 다양한 검증자(validator)를 제공합니다. prop에 부적절한 값을 명시한다면 JavaScript 콘솔에 경고가 보일 것입니다. 성능상의 문제로 `propTypes`는 개발 모드에서만 검사됩니다. 다음은 제공되는 검증자를 설명하는 예제입니다.
@@ -78,7 +77,6 @@ React.createClass({
});
```
## 기본 Prop 값
React는 매우 선언적(declarative)인 방법으로 `props`의 기본값을 정의할 수 있게 해줍니다.
@@ -230,3 +228,30 @@ Counter.defaultProps = { initialCount: 0 };
### 믹스인 안됨
불행하게도 ES6는 믹스인에 대한 지원이 없이 출시되었기 때문에, React에서 ES6 클래스를 사용한다면 믹스인을 사용할 방법이 없습니다. 대신, 우리는 믹스인에 의존하지 않고도 동작하도록 만들기 위해 열심히 노력하고 있습니다.
<a name="stateless-functions"></a>
## 상태를 가지지 않는 함수
React 클래스를 일반 JavaScript 함수로 작성할 수도 있습니다. 상태를 가지지 않는 함수 문법을 사용하는 예제입니다.
```javascript
function HelloMessage(props) {
return <div>Hello {props.name}</div>;
}
ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
```
아니면 ES6의 화살표 문법을 사용할 수 있습니다.
```javascript
var HelloMessage = (props) => <div>Hello {props.name}</div>;
ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
```
이 단순화된 컴포넌트 API는 prop의 순수 함수인 컴포넌트를 나타냅니다. 이 컴포넌트는 내부 상태가 없어야 하고, 내부 인스턴스가 없어야 하고, 컴포넌트 생명주기 메소드가 없어야 합니다. 아무런 준비 과정없이 입력에 대한 순수한 기능적 변환이어야 합니다.
> 주의:
>
> 상태를 가지지 않는 함수는 내부 인스턴스가 없기 때문에, ref를 상태를 가지지않는 함수에 넣을 수 없습니다. 상태를 가지지 않는 함수는 명령형(imperative) API를 제공하지 않기 때문에 일반적으로 이것은 문제가 되지 않습니다. 명령형 API없이 인스턴스에 할 수 있는 것이 많지 않기도 하죠. 하지만 상태를 가지지 않는 컴포넌트의 DOM 노드를 검색하길 원한다면, 반드시 상태 기반 컴포넌트(예. ES6 클래스 컴포넌트)로 컴포넌트를 감싸고 상태 기반 래퍼 컴포넌트에 ref를 붙여야 합니다.
이상적으로는, 대부분의 컴포넌트는 상태를 가지지 않는 함수여야 합니다. 왜냐 하면 이런 상태를 가지지 않는 컴포넌트는 React 코어 안에서 더 빠른 코드 경로를 거치기 때문입니다. 이는 가능한 한 추천하는 패턴입니다.

View File

@@ -8,7 +8,6 @@ next: transferring-props.html
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.
## Prop Validation
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. Here is an example documenting the different validators provided:
@@ -79,7 +78,6 @@ React.createClass({
});
```
## Default Prop Values
React lets you define default values for your `props` in a very declarative way:
@@ -97,10 +95,9 @@ var ComponentWithDefaultProps = React.createClass({
The result of `getDefaultProps()` will be cached and used to ensure that `this.props.value` 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.
## Transferring Props: A Shortcut
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:
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:
```javascript
var CheckLink = React.createClass({
@@ -233,8 +230,6 @@ Methods follow the same semantics as regular ES6 classes, meaning that they don'
Unfortunately ES6 launched without any mixin support. Therefore, there is no support for mixins when you use React with ES6 classes. Instead, we're working on making it easier to support such use cases without resorting to mixins.
## Stateless Functions
You may also define your React classes as a plain JavaScript function. For example using the stateless function syntax:
@@ -253,12 +248,10 @@ var HelloMessage = (props) => <div>Hello {props.name}</div>;
ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
```
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.
> NOTE:
>
>
> 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.
In an ideal world, most of your components would be stateless functions because these stateless components can follow a faster code path within the React core. This is the recommended pattern, when possible.

View File

@@ -50,8 +50,9 @@ ReactDOM.render(
## JSX에서 `...`를 사용해 전달하기
> 주의:
>
> 아래의 예제에서는 실험적인 ES7 문법이 사용되었기 때문에 `--harmony ` 플래그가 필요합니다. 브라우저에서 JSX 변환기를 사용 중이라면, `<script type="text/jsx;harmony=true">`를 사용해 스크립트를 작성하세요. 자세히 알아보려면 아래의 [잔여 프로퍼티와 스프레드 프로퍼티 ...](/react/docs/transferring-props-ko-KR.html#rest-and-spread-properties-...)를 확인하세요.
>
> `...` 구문은 객체 잔여 스프레드 제안의 일부입니다. 이 제안은 표준화 과정에 있습니다. 더 자세한 내용은 밑의 [잔여 프로퍼티와 스프레드 프로퍼티 ...](/react/docs/transferring-props.html#rest-and-spread-properties-...) 부분을 참고하세요.
때로는 모든 프로퍼티를 일일이 전달 하는것은 지루하고 덧없는 작업입니다. 이 경우 [구조 해체 할당(destructuring assignment)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)을 다른 프로퍼티를 함께 사용해 미상의 프로퍼티를 추출할 수 있습니다.
@@ -133,7 +134,7 @@ var FancyCheckbox = React.createClass({
잔여(Rest, `...`) 프로퍼티는 객체에서 소비되지 않은 나머지 프로퍼티를 추출해 새로운 객체로 만들 수 있게 해 줍니다. 구조 해체 패턴에서 열거된 다른 프로퍼티들은 모두 제외됩니다.
는 [ES7 제안](https://github.com/sebmarkbage/ecmascript-rest-spread)의 실험적인 구현체입니다.
제안은 2 단계에 돌입해 이제 바벨에서 기본값으로 활성화되어있습니다. 바벨의 이전 버전은 `babel --optional es7.objectRestSpread`로 명시적으로 활성화 할 필요가 있을 수도 있습니다.
```javascript
var { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };

View File

@@ -83,7 +83,7 @@ ReactDOM.render(
```
> 注意:
>
>
> 上面例子中,`checked` 属性也是一个有效的 DOM 属性。如果你没有使用解构赋值,那么可能无意中把它传下去。
在传递这些未知的 `other` 属性时,要经常使用解构赋值模式。
@@ -126,7 +126,7 @@ var FancyCheckbox = React.createClass({
```
> 注意:
>
>
> 顺序很重要,把 `{...other}` 放到 JSX props 前面会使它不被覆盖。上面例子中我们可以保证 input 的 type 是 `"checkbox"`。

View File

@@ -68,6 +68,9 @@ HTML에서는 `<textarea>` 태그의 값을 설정할 때 `<textarea>` 태그의
이것은 사용자 입력을 받아들이지만, 시작에서부터 140자로 값을 자릅니다.
### 체크박스와 라디오 버튼의 잠제적인 문제
변경 핸들링을 일반화하기 위해 React는 `change` 이벤트 대신에 `click` 이벤트를 사용하는 것에 주의하세요. `change` 핸들러 안에서 `preventDefault`를 호출하는 경우를 재외하고 이 동작은 예상대로 동작합니다. 이런 경우 `preventDefault`를 제거하거나, `setTimeout``checked`의 전환을 넣어서 해결 가능합니다.
## 제어되지 않는(Uncontrolled) 컴포넌트
@@ -91,7 +94,7 @@ HTML에서는 `<textarea>` 태그의 값을 설정할 때 `<textarea>` 태그의
}
```
이 예제는 위에있는 **제어되는 컴포넌트**에 더 가깝게 동작할 것입니다.
이 예제는 위에있는 **제어되지 않는 컴포넌트**에 더 가깝게 동작할 것입니다.
마찬가지로, `<input>``defaultChecked`를 지원하고 `<select>``defaultValue`를 지원합니다.
@@ -99,10 +102,8 @@ HTML에서는 `<textarea>` 태그의 값을 설정할 때 `<textarea>` 태그의
>
> `defaultValue`, `defaultChecked` prop은 최초 렌더에서만 사용됩니다. 뒤에 일어나는 렌더에서 값을 업데이트할 필요가 있다면, [제어되는(controlled) 컴포넌트](#controlled-components)를 사용하셔야 합니다.
## 심화 주제
### 왜 제어되는 컴포넌트인가요?
React에서 `<input>`같은 폼 컴포넌트를 사용하면, 전통적인 폼 HTML을 쓸 때에는 없던 어려운 문제가 있습니다. 예를 들어 HTML에서
@@ -123,7 +124,6 @@ HTML과 다르게, React 컴포넌트는 초기화 시점 뿐만 아니라, 어
이 메소드가 어떤 시점에도 뷰를 기술하기 때문에, 텍스트 input의 값은 *언제나* `Untitled`입니다.
### 왜 Textarea에 value를 사용하나요?
HTML에서, `<textarea>`의 값은 보통 그것의 자식들로 설정됩니다.
@@ -141,7 +141,6 @@ HTML에서는 이렇게 하면 여러 줄의 값을 쉽게 개발자가 넣을
자식들을 사용하기로 *했다면*, 자식들은 `defaultValue`처럼 동작할 것입니다.
### 왜 Select에 value를 사용하나요?
HTML `<select>`에서 선택된 `<option>`은 보통 option의 `selected` 어트리뷰트로 기술됩니다. React에서는 컴포넌트를 관리하기 쉽게 하기 위해, 다음 형식이 대신 채용됐습니다.

View File

@@ -32,7 +32,6 @@ Like all DOM events, the `onChange` prop is supported on all native components a
>
> 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.
## Controlled Components
An `<input>` with `value` set is a *controlled* component. In a controlled `<input>`, the value of the rendered element will always reflect the `value` prop. For example:
@@ -70,8 +69,7 @@ This would accept user input but truncate the value to the first 140 characters.
### Potential Issues With Checkboxes and Radio Buttons
Be aware that, in an attempt to normalise 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`.
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`.
## Uncontrolled Components
@@ -95,7 +93,7 @@ If you want to initialize the component with a non-empty value, you can supply a
}
```
This example will function much like the **Controlled Components** example above.
This example will function much like the **Uncontrolled Components** example above.
Likewise, `<input>` supports `defaultChecked` and `<select>` supports `defaultValue`.
@@ -103,10 +101,8 @@ Likewise, `<input>` supports `defaultChecked` and `<select>` supports `defaultVa
>
> 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).
## Advanced Topics
### Why Controlled Components?
Using form components such as `<input>` in React presents a challenge that is absent when writing traditional form HTML. For example, in HTML:
@@ -127,7 +123,6 @@ Unlike HTML, React components must represent the state of the view at any point
Since this method describes the view at any point in time, the value of the text input should *always* be `Untitled`.
### Why Textarea Value?
In HTML, the value of `<textarea>` is usually set using its children:
@@ -145,7 +140,6 @@ For HTML, this easily allows developers to supply multiline values. However, sin
If you *do* decide to use children, they will behave like `defaultValue`.
### Why Select Value?
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:

View File

@@ -7,33 +7,33 @@ next: working-with-the-browser-zh-CN.html
---
诸如 `<input>``<textarea>``<option>` 这样的表单组件不同于其他组件,因为他们可以通过用户交互发生变化。这些组件提供的界面使响应用户交互的表单数据处理更加容易。
关于 `<form>` 事件详情请查看 [表单事件](/react/docs/events-zh-CN.html#form-events)。
## 交互属性
## 交互属性
表单组件支持几个受用户交互影响的属性:
* `value`,用于 `<input>``<textarea>` 组件。
* `checked`,用于类型为 `checkbox` 或者 `radio``<input>` 组件。
* `selected`,用于 `<option>` 组件。
在 HTML 中,`<textarea>` 的值通过子节点设置;在 React 中则应该使用 `value` 代替。
在 HTML 中,`<textarea>` 的值通过子节点设置;在 React 中则应该使用 `value` 代替。
表单组件可以通过 `onChange` 回调函数来监听组件变化。当用户做出以下交互时,`onChange` 执行并通过浏览器做出响应:
* `<input>``<textarea>``value` 发生变化时。
* `<input>``checked` 状态改变时。
* `<option>``selected` 状态改变时。
和所有 DOM 事件一样,所有的 HTML 原生组件都支持 `onChange` 属性,而且可以用来监听冒泡的 `change` 事件。
和所有 DOM 事件一样,所有的 HTML 原生组件都支持 `onChange` 属性,而且可以用来监听冒泡的 `change` 事件。
> 注意:
>
> 对于 `<input>` and `<textarea>` `onChange` 替代 — 一般应该用来替代 — the DOM's 内建的 [`oninput`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput) 事件处理。
## 受限组件
## 受限组件
设置了 `value``<input>` 是一个*受限*组件。 对于受限的 `<input>`,渲染出来的 HTML 元素始终保持 `value` 属性的值。例如:
@@ -42,7 +42,7 @@ next: working-with-the-browser-zh-CN.html
return <input type="text" value="Hello!" />;
}
```
上面的代码将渲染出一个值为 `Hello!` 的 input 元素。用户在渲染出来的元素里输入任何值都不起作用,因为 React 已经赋值为 `Hello!`。如果想响应更新用户输入的值,就得使用 `onChange` 事件:
```javascript
@@ -72,7 +72,7 @@ next: working-with-the-browser-zh-CN.html
当心在力图标准化复选框与单选按钮的变换处理中React使用`click` 事件代替 `change` 事件。在大多数情况下它们表现的如同预期,除了在`change` handler中调用`preventDefault``preventDefault` 阻止了浏览器视觉上更新输入,即使`checked`被触发。变通的方式是要么移除`preventDefault`的调用,要么把`checked` 的触发放在一个`setTimeout`里。
## 不受限组件
没有设置 `value`(或者设为 `null`) 的 `<input>` 组件是一个*不受限*组件。对于不受限的 `<input>` 组件,渲染出来的元素直接反应用户输入。例如:
@@ -102,14 +102,14 @@ next: working-with-the-browser-zh-CN.html
> 注意:
>
> `defaultValue` 和 `defaultChecked` props 只能在内部渲染时被使用。 如果你需要在随后的渲染更新值, 你需要使用 [受限组件](#受限组件).
## 高级主题
### 为什么使用受限组件?
在 React 中使用诸如 `<input>` 的表单组件时,遇到了一个在传统 HTML 中没有的挑战。比如下面的代码:
在 React 中使用诸如 `<input>` 的表单组件时,遇到了一个在传统 HTML 中没有的挑战。比如下面的代码:
```html
<input type="text" name="title" value="Untitled" />
@@ -136,7 +136,7 @@ next: working-with-the-browser-zh-CN.html
<!-- 反例:在 React 中不要这样使用! -->
<textarea name="description">This is the description.</textarea>
```
对 HTML 而言让开发者设置多行的值很容易。但是React 是 JavaScript没有字符限制可以使用 `\n` 实现换行。简言之React 已经有 `value``defaultValue` 属性,`</textarea>` 组件的子节点扮演什么角色就有点模棱两可了。基于此, 设置 `<textarea>` 值时不应该使用子节点:
```javascript
@@ -146,7 +146,7 @@ next: working-with-the-browser-zh-CN.html
如果 *非要* 使用子节点,效果和使用 `defaultValue` 一样。
### 为什么 `<select>` 使用 `value` 属性
### 为什么 `<select>` 使用 `value` 属性
HTML 中 `<select>` 通常使用 `<option>``selected` 属性设置选中状态React 为了更方面的控制组件,采用以下方式代替:

View File

@@ -32,7 +32,7 @@ var MyComponent = React.createClass({
ReactDOM.findDOMNode(this.refs.myTextInput).focus();
},
render: function() {
// この参照属性はコンポーネントがマウントされた時に、
// この参照属性はコンポーネントがマウントされた時に、
// this.refs のコンポーネントへの参照を追加します。
return (
<div>

View File

@@ -11,7 +11,7 @@ React는 대부분의 경우 직접 DOM을 다루지 않아도 될만큼 강력
## 가상의 DOM
React는 DOM을 직접 다루지 않기 때문에 굉장히 빠릅니다. React는 메모리에(in-memory) DOM의 표상(representation)을 관리합니다. `render()` 메소드는 DOM의 *서술*를 반환하고, React는 이를 메모리에 있는 DOM의 표상과 비교(diff)해 가장 빠른 방식으로 계산해서 브라우저를 업데이트해 줍니다.
React는 DOM을 직접 다루지 않기 때문에 매우 빠릅니다. React는 메모리에(in-memory) DOM의 표상(representation)을 관리합니다. `render()` 메소드는 사실은 DOM의 *서술*를 반환하고, React는 이를 메모리에 있는 DOM의 표상과 비교해 가장 빠른 방식으로 계산해서 브라우저를 업데이트해 줍니다.
게다가 React는 브라우저의 괴악함(quirks)에도 불구하고 모든 이벤트 객체가 W3C 명세를 보장하도록 통합적인 이벤트 시스템을 구현했습니다. 모든 것이 일관된 방식으로 일어나고(bubbles) 효율적으로 크로스 브라우징을 수행합니다. 심지어 IE8에서도 HTML5 이벤트를 사용할 수 있습니다!
@@ -20,45 +20,7 @@ React는 DOM을 직접 다루지 않기 때문에 굉장히 빠릅니다. React
## Refs와 findDOMNode()
브라우저와 상호 작용하려면 DOM 노드에 대한 참조가 필요합니다. React는 `ReactDOM.findDOMNode(component)` 함수를 갖고 있으며, 이를 통해서 컴포넌트의 DOM 노드의 참조를 얻을 수 있습니다.
> 주의:
>
> `findDOMNode()`는 마운트 된 컴포넌트에서만 동작합니다 (DOM에 배치된 컴포넌트를 말합니다). 아직 마운트 되지 않은 컴포넌트에서 이를 호출하려고 하면 (컴포넌트가 아직 생성되기 이전인 `render()` 시점에 `findDOMNode()`를 호출한다든가) 예외가 발생합니다.
React 컴포넌트에 대한 참조는 현재의 React 컴포넌트를 위해 `this`를, 소유한 컴포넌트의 참조를 얻기 위해 refs를 사용해 얻을 수 있습니다. 다음과 같이 동작합니다:
```javascript
var MyComponent = React.createClass({
handleClick: function() {
// raw DOM API를 사용해 명시적으로 텍스트 인풋을 포커스 합니다.
ReactDOM.findDOMNode(this.refs.myTextInput).focus();
},
render: function() {
// ref 어트리뷰트는 컴포넌트가 마운트되면 그에 대한 참조를 this.refs에 추가합니다.
return (
<div>
<input type="text" ref="myTextInput" />
<input
type="button"
value="Focus the text input"
onClick={this.handleClick}
/>
</div>
);
}
});
ReactDOM.render(
<MyComponent />,
document.getElementById('example')
);
```
## Refs 심화
[refs 심화](/react/docs/more-about-refs-ko-KR.html) 문서에서 refs를 효율적으로 사용하는 법을 포함해 더 많은 내용을 익혀보세요.
브라우저와 상호 작용하려면 DOM 노드에 대한 참조가 필요합니다. `ref`를 어떤 엘리먼트에도 붙일 수 있으며, 이를 통해 컴포넌트 **지원 인스턴스**를 참조 할 수 있습니다. 이는 컴포넌트에 필수 적인 기능을 호출할 때나 기저의 DOM 노드에 접근하고 싶을 때 유용합니다. [refs에서 컴포넌트로](/react/docs/more-about-refs-ko-KR.html) 문서에서 refs를 효율적으로 사용하는 법을 포함해 더 많은 내용을 익혀보세요.
<a name="component-lifecycle"></a>
@@ -72,14 +34,12 @@ ReactDOM.render(
React는 이 프로세스에 훅을 지정할 수 있는 생명주기 메소드를 제공합니다. 발생 직전 시점을 위한 **will** 메소드, 발생 직후 시점을 위한 **did** 메소드가 있습니다.
### Mounting
* `getInitialState(): object`는 컴포넌트가 마운트되기 전에 호출됩니다. 상태기반 컴포넌트는 이를 구현하고 초기 상태 데이터를 리턴합니다.
* `componentWillMount()`는 마운팅되기 직전에 호출됩니다.
* `componentDidMount()`는 마운팅 직후 호출됩니다. 초기화에 필요한 DOM 노드는 이곳에 있어야 합니다.
### Updating
* `componentWillReceiveProps(object nextProps)`는 마운트된 컴포넌트가 새로운 props을 받을 때 호출됩니다. 이 메소드는 `this.props``nextProps`을 비교하여 `this.setState()`를 사용해 상태 변환을 수행하는데 사용되야 합니다.
@@ -87,19 +47,15 @@ React는 이 프로세스에 훅을 지정할 수 있는 생명주기 메소드
* `componentWillUpdate(object nextProps, object nextState)`는 업데이트가 발생하기 직전에 호출됩니다. 이 시점에는 `this.setState()`를 호출할 수 없습니다.
* `componentDidUpdate(object prevProps, object prevState)`는 업데이트가 발생한 후 즉시 호출됩니다.
### Unmounting
* `componentWillUnmount()`는 컴포넌트가 언마운트되어 파괴되기 직전에 호출됩니다. 정리(Cleanup)는 여기서 처리해야 합니다.
### Mounted 메소드
_마운트된_ 합성 컴포넌트들은 다음과 같은 메소드를 지원합니다:
* `findDOMNode(): DOMElement`는 렌더링 된 DOM 노드에 대한 참조를 얻기 위해 모든 마운트된 컴포넌트에서 호출할 수 있습니다.
* `forceUpdate()``this.setState`를 사용하지 않고 컴포넌트 state의 더 깊은 측면(deeper aspect)의 변경된 것을 알고 있을 때 모든 마운트된 컴포넌트에서 호출할 수 있습니다.
* `component.forceUpdate()``this.setState()`를 사용하지 않고 변경된 컴포넌트의 상태의 변경을 적용하고 싶을 때 마운트된 컴포넌트에서 사용할 수 있습니다.
## 브라우저 지원과 Polyfill
@@ -107,7 +63,6 @@ _마운트된_ 합성 컴포넌트들은 다음과 같은 메소드를 지원합
그 철학에 더하여, 우리는 또한 JS 라이브러리의 저자로서 polyfill을 라이브러리에 포함해서 배포하지 않습니다. 만약 모든 라이브러리가 이런 짓을 하면, 같은 polyfill을 여러 번 내리게 되어 쓸모없이 크기만 차지하는 죽은 코드들을 만들 것 입니다. 당신의 제품이 구식 브라우저를 지원해야한다면, [es5-shim](https://github.com/es-shims/es5-shim) 같은 녀석을 사용할 기회가 있었을 겁니다.
### Polyfill은 구식 브라우저를 지원하기 위해 필요하다
[kriskowal's es5-shim](https://github.com/es-shims/es5-shim)의 `es5-shim.js`는 React에 필요한 다음의 기능을 제공합니다:
@@ -134,11 +89,9 @@ _마운트된_ 합성 컴포넌트들은 다음과 같은 메소드를 지원합
`<section>`, `<article>`, `<nav>`, `<header>`, `<footer>`등 HTML5 엘리먼트를 IE8에서 이용하려면 [html5shiv](https://github.com/aFarkas/html5shiv)같은 스크립트가 추가로 필요합니다.
### 크로스 브라우징 이슈
React가 브라우저별 차이점을 썩 잘 추상화하긴 했지만 일부는 한정적이거나 우리가 발견하지 못한 이상한(quirky) 동작을 보여주기도 합니다.
React가 브라우저별 차이점을 썩 잘 추상화하긴 했지만 일부는 한정적이거나 우리가 발견하지 못한 이상한(quirky) 동작을 보여주기도 합니다.
#### IE8에서의 onScroll 이벤트

View File

@@ -8,21 +8,18 @@ next: more-about-refs.html
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.
## The Virtual DOM
React is so fast because it never talks to the DOM directly. React maintains a fast in-memory representation of the DOM. `render()` methods return a *description* of the DOM, and React can diff this description with the in-memory representation to compute the fastest way to update the browser.
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.
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 IE8!
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.
## Refs and findDOMNode()
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.
## Component Lifecycle
Components have three main parts of their lifecycle:
@@ -33,14 +30,12 @@ Components have three main parts of their lifecycle:
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.
### Mounting
* `getInitialState(): object` is invoked before a component is mounted. Stateful components should implement this and return the initial state data.
* `componentWillMount()` is invoked immediately before mounting occurs.
* `componentDidMount()` is invoked immediately after mounting occurs. Initialization that requires DOM nodes should go here.
### Updating
* `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()`.
@@ -48,26 +43,22 @@ React provides lifecycle methods that you can specify to hook into this process.
* `componentWillUpdate(object nextProps, object nextState)` is invoked immediately before updating occurs. You cannot call `this.setState()` here.
* `componentDidUpdate(object prevProps, object prevState)` is invoked immediately after updating occurs.
### Unmounting
* `componentWillUnmount()` is invoked immediately before a component is unmounted and destroyed. Cleanup should go here.
### Mounted Methods
_Mounted_ composite components also support the following method:
* `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()`.
## Browser Support and Polyfills
At Facebook, we support older browsers, including IE8. We've had polyfills in place for a long time to allow us to write forward-thinking JS. This means we don't have a bunch of hacks scattered throughout our codebase and we can still expect our code to "just work". For example, instead of seeing `+new Date()`, we can just write `Date.now()`. Since the open source React is the same as what we use internally, we've carried over this philosophy of using forward thinking JS.
In addition to that philosophy, we've also taken the stance that we, as authors of a JS library, should not be shipping polyfills as a part of our library. If every library did this, there's a good chance you'd be sending down the same polyfill multiple times, which could be a sizable chunk of dead code. If your product needs to support older browsers, chances are you're already using something like [es5-shim](https://github.com/es-shims/es5-shim).
### Polyfills Needed to Support Older Browsers
`es5-shim.js` from [kriskowal's es5-shim](https://github.com/es-shims/es5-shim) provides the following that React needs:
@@ -94,12 +85,10 @@ The unminified build of React needs the following from [paulmillr's console-poly
When using HTML5 elements in IE8 including `<section>`, `<article>`, `<nav>`, `<header>`, and `<footer>`, it's also necessary to include [html5shiv](https://github.com/aFarkas/html5shiv) or a similar script.
### Cross-browser Issues
Although React is pretty good at abstracting browser differences, some browsers are limited or present quirky behaviors that we couldn't find a workaround for.
#### onScroll event on IE8
On IE8 the `onScroll` event doesn't bubble and IE8 doesn't have an API to define handlers to the capturing phase of an event, meaning there is no way for React to listen to these events.

View File

@@ -9,7 +9,7 @@ next: more-about-refs-zh-CN.html
React提供了强大的抽象机制使你在大多数情况下免于直接接触DOM但有时你仅仅只需要访问底层API也许是为了与第三方库或者已有的代码协作。
## 虚拟DOM
## 虚拟DOM
React如此快速是因为它从不直接操作DOM。React维持了一个快速的内存中的DOM表示。`render()` 方法返回一个DOM的*描述*然后React能根据内存中的描述diff此描述来计算出最快速的方法更新浏览器。
@@ -76,14 +76,14 @@ React提供生命周期方法以便你可以指定钩挂到这个过程上。
### 挂载
* `getInitialState(): object` 在组件挂载前被调用. 有状态组件(Stateful components) 应该实现此函数并返回初始state的数据。
* `componentWillMount()` 在挂载发生前被立即调用。
* `componentDidMount()` 在挂载发生后被立即调用。 需要DOM node的初始化应该放在这里。
* `componentWillMount()` 在挂载发生前被立即调用。
* `componentDidMount()` 在挂载发生后被立即调用。 需要DOM node的初始化应该放在这里。
### 更新
* `componentWillReceiveProps(object nextProps)` 当挂载的组件接收到新的props时被调用。此方法应该被用于比较`this.props``nextProps`以用于使用`this.setState()`执行状态转换。
* `shouldComponentUpdate(object nextProps, object nextState): boolean` 当组件决定任何改变是否要更新到DOM时被调用。作为一个优化实现比较`this.props``nextProps``this.state``nextState` 如果React应该跳过更新返回`false`
* `shouldComponentUpdate(object nextProps, object nextState): boolean` 当组件决定任何改变是否要更新到DOM时被调用。作为一个优化实现比较`this.props``nextProps``this.state``nextState` 如果React应该跳过更新返回`false`
* `componentWillUpdate(object nextProps, object nextState)` 在更新发生前被立即调用。你不能在此调用`this.setState()`
* `componentDidUpdate(object prevProps, object prevState)` 在更新发生后被立即调用。
@@ -108,7 +108,7 @@ _Mounted_ 复合组件同样支持以下方法:
除了这种哲学外我们也采用了这样的立场我们作为一个JS库的作者不应该把polyfills作为我们库的一部分。如果所有的库这样做就有很大的机会发送同样的polyfill多次这可能是一个相当大的无用代码。如果你的产品需要支援老的浏览器你很有可能已经在使用某些东西比如[es5-shim](https://github.com/es-shims/es5-shim)。
### 需要用来支持旧浏览器的Polyfills
### 需要用来支持旧浏览器的Polyfills
来自 [kriskowal's es5-shim](https://github.com/es-shims/es5-shim)的`es5-shim.js` 提供了如下React需要的东西
@@ -135,7 +135,7 @@ _Mounted_ 复合组件同样支持以下方法:
当在IE8里使用HTML5元素包括`<section>`, `<article>`, `<nav>`, `<header>`, 和 `<footer>`, 同样必须包含[html5shiv](https://github.com/aFarkas/html5shiv) 或者类似的脚本。
### 跨浏览器问题
### 跨浏览器问题
尽管React在抽象浏览器不同时做的相当好但一些浏览器被限制或者表现出怪异的行为我们没能找到变通的方案解决。

View File

@@ -49,7 +49,7 @@ next: tooling-integration-zh-CN.html
```javascript
// 反模式:不能工作.
render: function() {
var myInput = <input />; // 我打算在这个上调用这个方法
var myInput = <input />; // 我打算在这个上调用这个方法
this.rememberThisInput = myInput; // input在未来的某个时间点上YAY!
return (
<div>
@@ -165,10 +165,10 @@ React 假设你可以向任何的从`render()` 中返回的组件附加一个特
- 执行 DOM操作总是要求诸如`<input />` 这样的一个“原生”组件,并通过`this.refs.myInput` 来访问她的低层的MOD 节点。Refs是可以做成这个事的唯一的实践可行的方法。
- Refs自动管理如果孩子被销毁了它的ref也被销毁。在这里不用担心内存除非你做了一些疯狂的事情来自己保持一个引用
- Refs自动管理如果孩子被销毁了它的ref也被销毁。在这里不用担心内存除非你做了一些疯狂的事情来自己保持一个引用
### 小心:
- *绝对不要* 在组件的render方法内部- 获 当任何组件的render方法还在调用栈中执行的时候访问refs 。
- *绝对不要* 在组件的render方法内部- 获 当任何组件的render方法还在调用栈中执行的时候访问refs 。
- 如果你想要保护Google 闭包编译器崩溃的内力,确保绝不作为访问一个被特别的设置为一个字符串的属性。这就意味着,如果你用`ref="myRefString"` 来定义你的ref的话你必须使用`this.refs['myRefsString']` 来访问。
- 如果你不是用React做服务器编程的在你的程序中你首先的倾向是用refs来“让事情发生“。如果这是正是你的情况的话花点时间仔细的想想`state` 在这个组件的结构层次中应在在哪里使用。通常,正确的"拥有" 状态的地方是结构层次的高层。把状态放在那些地方通常可以消除使用`ref` 来”让事情发生” 的渴望 - 相反的,数据流通常能完成你的目标。
- 如果你不是用React做服务器编程的在你的程序中你首先的倾向是用refs来“让事情发生“。如果这是正是你的情况的话花点时间仔细的想想`state` 在这个组件的结构层次中应在在哪里使用。通常,正确的"拥有" 状态的地方是结构层次的高层。把状态放在那些地方通常可以消除使用`ref` 来”让事情发生” 的渴望 - 相反的,数据流通常能完成你的目标。

View File

@@ -144,4 +144,4 @@ Reactは `render()` からの出力であるコンポーネントであれば何
- *決して* コンポーネントのレンダリングメソッドの中の参照にアクセスしてはいけません。たとえコンポーネントのレンダリングメソッドのいずれかがコールスタックの中のどこかで動いているとしても。
- もしGoogle Closure Compilerのクラッシュからの回復を守りたいなら、文字列として指定されたプロパティとしてアクセスしてはいけないことに気をつけてください。これは、 `ref="myRefString"` として参照が定義されている場合は、 `this.refs['myRefString']` を使ってアクセスしなければいけないことを意味します。
- まだReactでプログラムを書いたことがない場合は、アプリケーションで「何かを起こす」ために参照を使おうとするでしょう。もしそのケースだった場合は、時間をかけて `state` がコンポーネントの階層のどこで保持されるべきか批評的に考えてください。多くの場合は、そのstateを「保持する」ための固有の場所が階層の高いレベルにあることがクリアになります。そのstateをその場所に配置することはよく「何かを起こす」ために `ref` を使うための願望を排除します。代わりに、データフローは普通、目標を達成します。
- まだReactでプログラムを書いたことがない場合は、アプリケーションで「何かを起こす」ために参照を使おうとするでしょう。もしそのケースだった場合は、時間をかけて `state` がコンポーネントの階層のどこで保持されるべきか批評的に考えてください。多くの場合は、そのstateを「保持する」ための固有の場所が階層の高いレベルにあることがクリアになります。そのstateをその場所に配置することはよく「何かを起こす」ために `ref` を使うための願望を排除します。代わりに、データフローは普通、目標を達成します。

View File

@@ -1,137 +1,125 @@
---
id: more-about-refs-ko-KR
title: refs 심화
title: refs에서 컴포넌트로
permalink: more-about-refs-ko-KR.html
prev: working-with-the-browser-ko-KR.html
next: tooling-integration-ko-KR.html
---
render 메소드를 통해 UI 구조를 얻은 다음, 반환된 컴포넌트 인스턴스에 접근하거나 메소드를 호출할 방법이 필요할 수도 있습니다. 반응적 데이터 플로우가 `render()`의 결과물에서 최신의 `props`가 각각의 자식으로 보내진 것을 항상 보장하기 때문에 애플리케이션의 데이터 플로우를 만드는데 대체로 이런 작업은 필요가 없지만, 여전히 이런 작업이 필요하거나 유리한 경우가 있긴 합니다.
컴포넌트를 빌드한 후에는 `render()`에서 반환된 컴포넌트 인스턴스에 접근하거나 메소드를 호출할 방법이 필요할 수도 있습니다. 반응적 데이터 플로우가 `render()`의 결과물에서 최신의 `props`가 각각의 자식으로 보내진 것을 항상 보장하기 때문에 애플리케이션의 데이터 플로우를 만드는데 대체로 이런 작업은 필요가 없지만, 여전히 이런 작업이 필요하거나 유리한 경우가 있긴 합니다. React는 이를 위해 `refs`라는 탈출구를 제공합니다. `refs`(레퍼런스)는 특히 다음과 같은 경우 유용합니다: 컴포넌트에 의해 렌더된 DOM 마크업을 찾을때 (인스턴스내의 절대적인 위치), 큰 프로젝트의 일부에 React 컴포넌트를 사용하는 경우 또는 기존의 코드베이스를 React로 변경하는 경우.
ref를 어떻게 얻는지 살펴보고, 예제를 완성해 봅시다.
인스턴스의 하위 계층구조에 존재하는 `<input />` 엘리먼트의 value를 빈 문자열(`''`)로 업데이트한 후 포커스 하는 경우를 생각해 봅시다.
## ReactDOM.render에서 반환된 ref
```javascript
var App = React.createClass({
getInitialState: function() {
return {userInput: ''};
},
handleChange: function(e) {
this.setState({userInput: e.target.value});
},
clearAndFocusInput: function() {
this.setState({userInput: ''}); // 입력내용을 지워줍니다
// 이제 <input />에 포커스를 주길 원합니다!
},
render: function() {
return (
<div>
<div onClick={this.clearAndFocusInput}>
클릭해서 초기화하고 포커스주기
</div>
<input
value={this.state.userInput}
onChange={this.handleChange}
/>
</div>
);
}
});
컴포넌트에서 정의한, 가상의 DOM 엘리먼트를 반환하는 `render()`와 헷갈리지 않도록 합니다. [ReactDOM.render()](/react/docs/top-level-api-ko-KR.html#reactdom.render)는 컴포넌트의 **지원 인스턴스(backing instance)**에 대한 참조를 반환 합니다. [상태를 가지지 않는 컴포넌트](/react/docs/reusable-components-ko-KR.html#stateless-functions)에 대해선 `null`을 반환하죠.
```js
var myComponent = ReactDOM.render(<MyComponent />, myContainer);
```
명심하세요. 위의 코드는 컴포넌트 인스턴스를 반환하지 않습니다! 이는 그저 **ReactElement**:React에 마운트된 컴포넌트가 어떻게 보여야 할지 알려주는 경량의 표상(representation) 입니다.
```js
var myComponentElement = <MyComponent />; // 이건 그냥 ReactElement 입니다.
한번 살펴보죠. 이 예제에서 우리는 시간이 지남에 따라 props에서 추론할 수 없는 무언가를 입력하도록 "알려주길" 원했습니다. 이 사례에서 우리는 이제 포커스 되도록 "알려주길" 원합니다. 그러나 몇 가지 문제가 있습니다. `render()`에서 반환된 것은 "자식" 컴포넌트의 실제 구성이 아니고, 단지 특정 시점의 인스턴스의 자식에 대한 *서술*일 뿐입니다. - 말하자면 스냅샷인 것이지요.
// 여기 코드가 위치합니다...
var myComponentInstance = ReactDOM.render(myComponentElement, myContainer);
myComponentInstance.doSomething();
```
> 주의:
>
> 기억하세요, `render()`에서 반환된 것은 *실제* 자식 인스턴스가 아닙니다. 단지 특정 시점의 컴포넌트의 하위 계층구조에 있는 자식 인스턴스의 *서술*일 뿐입니다.
> 이는 오직 최상위 레벨에서만 사용되어야 합니다. 컴포넌트의 내부에서는 `props`와 `state`가 자식 컴포넌트와 통신하도록 하거나 문자열이나 콜백 어트리뷰트 등 ref를 얻어오는 다른 방법을 사용하도록 하세요.
## ref 콜백 어트리뷰트
React는 어떤 컴포넌트에든 추가할 수 있는 특별한 어트리뷰트를 제공합니다. `ref` 어트리뷰트는 콜백 함수일 수 있으며 이는 컴포넌트가 마운트 된 후 즉시 실행됩니다. 참조된 컴포넌트는 파라미터로 전달될 것이며 콜백 함수는 즉시, 혹은 미래에 사용하기 위해 컴포넌트의 참조를 저장합니다.
이는 `render()`에서 반환된 무언가를 "계속 유지할 수" 없으며 아무런 의미도 없을 것이라는 뜻입니다.
`render`에서 반환되는 무엇에든 `ref` 어트리뷰트를 추가하는 것은 간단합니다:
```javascript
// 안티패턴: 이것은 동작하지 않습니다.
```js
render: function() {
var myInput = <input />; // 여기서 메소드를 호출할 겁니다.
this.rememberThisInput = myInput; // 언젠가 미래의 특정 시점에 입력할 거에요! YAY!
return (
<div>
<div>...</div>
{myInput}
</div>
<TextInput
ref={function(input) {
if (input != null) {
input.focus();
}
}} />
);
}
},
```
ES6 화살표 함수를 사용한다면 다음과 같습니다:
```js
render: function() {
return <TextInput ref={(c) => this._input = c} />;
},
componentDidMount: function() {
this._input.focus();
},
```
이 예제에서 `<input />`은 단지 `<input />`의 *서술*일 뿐입니다. 이 서술은 `<input />`에 대한 *진짜* **지원 인스턴스(backing instance)**를 생성하는 데 사용됩니다.
`<div />` 같은 DOM 컴포넌트에 ref를 추가하면 DOM 노드를 얻게 됩니다; `<TextInput />` 같은 합성 컴포넌트에 ref를 추가하면 React 클래스 인스턴스를 얻게 됩니다. 후자의 경우, 클래스에 정의되어 있는 노출된 메소드를 호출할 수 있습니다.
자 그럼 어떻게 *진짜* input의 지원 인스턴스를 다룰까요?
참조된 컴포넌트가 언마운트되고 ref가 변경되면 이전의 ref는 `null`을 인수로 호출됨을 주의 하세요. 이는 첫번째 예제에서처럼 인스턴트가 저장된 경우의 메모리 누수를 방지합니다. 또한 예제와 같이 ref를 인라인 함수 표현식으로 서술하게되면 React는 모든 업데이트에 대해 다른 함수 객체를 참조하게 됩니다. ref는 컴포넌트의 인스턴스의 호출 이전에 `null` 객체와 함께 즉시 호출될 것입니다.
## ref 문자열 어트리뷰트
React는 `render()`로 출력된 컴포넌트에 추가할 수 있는 아주 특별한 프로퍼티를 지원합니다. 특별한 프로퍼티는 `render()`에서 반환한 모든 것들에 대해 각각에 대응하는 **지원 인스턴스**를 참조할 수 있습니다. 이는 항상 어떤 시점에서든 올바른 인스턴스를 보장합니다.
React는 ref에 콜백 대신 문자열도 지원합니다 이런 접근은 이제 과거의 것이긴 합니다.
간단합니다:
1. `render`에서 반환된 값을 `ref` 어트리뷰트에 할당합니다:
```html
<input ref="myInput" />
```
```html
<input ref="myInput" />
```
2. 다른 코드(일반적으로는 이벤트 핸들러 코드)에서 `this.refs`를 통해 **지원 인스턴스**에 접근 합니다:
```javascript
this.refs.myInput
```
```javascript
var input = this.refs.myInput;
var inputValue = input.value;
var inputRect = input.getBoundingClientRect();
```
`this.refs.myInput`를 호출해 컴포넌트의 DOM 노드에 접근할 수 있습니다.
## ref 콜백 어트리뷰트
`ref` 어트리뷰트는 이름 대신 콜백 함수가 될 수도 있습니다. 이 콜백은 컴포넌트가 마운트 된 뒤 즉시 실행될 것입니다. 참조된 컴포넌트는 매개 변수로 전달되며 콜백은 이를 즉시 사용하거나, 앞으로 사용하기 위해 참조를 저장해 놓거나, 혹은 둘 다 할 것입니다.
`render`에서 반환한 모든 것에 간단하게 `ref` 어트리뷰트를 할당할 수 있습니다:
```html
<input ref={ function(component){component.focus();} } />
```
## 예제 완성하기
## 최종 예제
React 컴포넌트의 참조를 얻기 위해서, 현재의 React 컴포넌트를 위해서는 `this`를, 소유한 컴포넌트에 대해서는 ref를 사용할 수 있습니다. 다음과 같이 작동 합니다:
```javascript
var App = React.createClass({
getInitialState: function() {
return {userInput: ''};
},
handleChange: function(e) {
this.setState({userInput: e.target.value});
},
clearAndFocusInput: function() {
// input을 비워준다
this.setState({userInput: ''}, function() {
// 이 코드는 컴포넌트가 다시 렌더 된 다음 실행됩니다
this.refs.theInput.focus(); // 짠! 포커스 됨!
});
},
render: function() {
return (
<div>
<div onClick={this.clearAndFocusInput}>
클릭해서 초기화하고 포커스주기
</div>
<input
ref="theInput"
value={this.state.userInput}
onChange={this.handleChange}
/>
</div>
);
}
});
var MyComponent = React.createClass({
handleClick: function() {
// 명시적으로 텍스트 인풋에 포커스하기 위해 raw DOM API를 사용합니다.
this.myTextInput.focus();
},
render: function() {
// ref 어트리뷰트는 컴포넌트가 마운트되면
// this.refs에 컴포넌트에 대한 참조를 추가합니다.
return (
<div>
<input type="text" ref={(ref) => this.myTextInput = ref} />
<input
type="button"
value="Focus the text input"
onClick={this.handleClick}
/>
</div>
);
}
});
ReactDOM.render(
<MyComponent />,
document.getElementById('example')
);
```
이 예제에서 render 함수는 `<input />` 인스턴스의 서술을 반환했지만, 진짜 인스턴스는 `this.refs.theInput`을 통해 접근할 수 있었습니다. `render`에서 `ref="theInput"`을 가진 컴포넌트가 반환된 동안, `this.refs.theInput`은 적절한 인스턴스에 접근합니다. 이는 `<Typeahead ref="myTypeahead" />`처럼 DOM이 아닌 고수준의 컴포넌트에서도 동작합니다.
이 예제에서, 텍스트 인풋의 **지원 인스턴스**에 대한 참조를 얻었으며 버튼이 클릭되었을때 `focus()`를 호출했습니다.
합성 컴포넌트에서는 참조는 컴포넌트 클래스의 인스턴스를 가리키기 때문에 클래스에 정의된 어떤 메소드도 호출할 수 있습니다. 컴포넌트의 기저에 있는 DOM 노드에 접근하기 위해서는 [ReactDOM.findDOMNode](/react/docs/top-level-api-ko-KR.html#reactdom.finddomnode)를 "탈출구"로 사용할 수 있습니다. 하지만 이는 캡슐화를 깨며, 대부분의 경우 React 모델을 이용해 더 명확한 방법으로 구조를 짤 수 있기 때문에 추천하지 않습니다.
## 요약
@@ -139,12 +127,13 @@ Refs는 반응적인 `props`와 `state` 스트리밍을 통해서는 불편했
### 이점:
- 컴포넌트 클래스에 public 메소드(ex. Typeahead의 reset)를 선언할 수 있으며 refs를 통해 그를 호출할 수 있습니다. (ex. `this.refs.myTypeahead.reset()`)
- DOM을 측정하기 위해서는 거의 항상 `<input />` 같은 "기본" 컴포넌트를 다루고 `this.refs.myInput`를 통해 그 기저의 DOM 노드에 접근해야 합니다. Refs는 이 일을 확실하게 수행하는 몇 안 되는 실용적인 방법의 하나입니다.
- 컴포넌트 클래스에 public 메소드(ex. Typeahead의 reset)를 선언할 수 있으며 refs를 통해 그를 호출할 수 있습니다. (ex. `this.refs.myTypeahead.reset()`) 대부분, 이는 선언적으로 refs를 사용하는 것보다 내장 React 데이터 흐름을 명확하게 합니다.
- DOM을 측정하기 위해서는 거의 항상 `<input />` 같은 "기본" 컴포넌트를 다루고 ref를 통해 그 기저의 DOM 노드에 접근해야 합니다. Refs는 이 일을 확실하게 수행하는 몇 안 되는 실용적인 방법의 하나입니다.
- Refs는 자동으로 관리합니다! 자식이 파괴되면, 그의 ref도 마찬가지로 파괴됩니다. 참조를 유지하기 위해 뭔가 미친 짓을 하지 않는 한, 메모리 걱정은 하지 않아도 됩니다.
### 주의:
- 컴포넌트의 렌더 메소드에서는, 혹은 컴포넌트의 렌더 메소드가 콜스택 어디에서든 실행되는 동안에는 절대 접근하지 마세요.
- Google Closure Compiler에서의 분쇄 복원력 유지(to preserve Crushing resilience)를 위해서는 문자열로 정의한 것을 절대 프로퍼티로 접근하지 마세요. ref가 ref="myRefString"으로 정의되어 있다면 this.refs['myRefString']으로만 접근해야 한다는 이야기 입니다.
- Google Closure Compiler에서의 어드벤스드 모드 분쇄 복원력 유지(to preserve advanced-mode crushing resilience)를 위해서는 문자열로 정의한 것을 절대 프로퍼티로 접근하지 마세요. ref가 ref="myRefString"으로 정의되어 있다면 this.refs['myRefString']으로만 접근해야 한다는 이야기 입니다.
- React로 앱을 여럿 만들어 본 경험이 없다면, 보통은 처음엔 앱에서 "무언가 일어나도록" 하는데 refs를 사용하게 될 것입니다. 이 경우, 잠시 시간을 내어 `state`가 컴포넌트 계층구조의 어느 부분에서 관리되어야 할지 비판적으로 생각해 봅시다. 대개는 state가 계층구조의 더 높은 레벨에서 "소유"하는 것이 타당함이 명확해집니다. 그렇게 함으로써 `ref`를 사용해 "무언가 일어나도록" 하려는 욕망이 대부분 제거됩니다. - 대신에 데이터 플로우를 통해 대개 원하는 바를 달성하게 될 것입니다.
- Refs는 [상태를 가지지 않는 함수](/react/docs/reusable-components-ko-KR.html#stateless-functions)에 붙일 수 없습니다. 왜냐하면 컴포넌트가 내부 인스턴스를 가지지 않기 때문입니다. 상태를 가지지 않는 컴포넌트는 항상 일반 컴포넌트로 감싸 ref를 조합 컴포넌트에 붙일 수 있습니다.

View File

@@ -33,7 +33,6 @@ myComponentInstance.doSomething();
>
> 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).
## The ref Callback Attribute
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).
@@ -67,7 +66,6 @@ When attaching a ref to a DOM component like `<div />`, you get the DOM node bac
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 first 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.
## The ref String Attribute
React also supports using a string (instead of a callback) as a ref prop on any component, although this approach is mostly legacy at this point.
@@ -86,7 +84,6 @@ React also supports using a string (instead of a callback) as a ref prop on any
var inputRect = input.getBoundingClientRect();
```
## A Complete Example
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:

View File

@@ -38,11 +38,11 @@ next: tooling-integration-zh-CN.html
```
注意,在这个例子中,我们想 "告诉" input 一些东西 - 那些最后它不能从他的props推断出来的东西。在这个场景中我们想 "告诉" 它,它应该转为获得焦点。然而,有一些挑战。从`render()` 返回的东西不是你实际的 "子" 组件的组合,而是一个在某刻特定实例的子组件的 *描述* - 一个快照。
注意,在这个例子中,我们想 "告诉" input 一些东西 - 那些最后它不能从他的props推断出来的东西。在这个场景中我们想 "告诉" 它,它应该转为获得焦点。然而,有一些挑战。从`render()` 返回的东西不是你实际的 "子" 组件的组合,而是一个在某刻特定实例的子组件的 *描述* - 一个快照。
> 注意:
>
> 记住,从 `render()`返回的东西不是你的 *实际的* 被渲染出的子组件实例。从 `render()` 返回的东西仅仅是一个在特定时间你的组件的子层级中的子实例的 *描述*。
> 记住,从 `render()`返回的东西不是你的 *实际的* 被渲染出的子组件实例。从 `render()` 返回的东西仅仅是一个在特定时间你的组件的子层级中的子实例的 *描述*。
这意味着你万万不要把你从`render()`返回的东西 "抓住不放" 然后期望它变成任何有意义的东西。
@@ -61,7 +61,7 @@ next: tooling-integration-zh-CN.html
}
```
在这个例子中,`<input />` 仅仅是一个`<input />`*描述*。 这个描述被用于为`<input />`创建一个 *真实的* **支持实例(backing instance)**
在这个例子中,`<input />` 仅仅是一个`<input />`*描述*。 这个描述被用于为`<input />`创建一个 *真实的* **支持实例(backing instance)**
所以我们如何与input的 *真实的*支持实例对话?
@@ -170,5 +170,5 @@ Refs是一种很好的发送消息给特定子实例(通过流式的Reactive `pr
- *绝不* 在任何组件的 render 方法中访问 refs - 或者当任何组件的render方法还在调用栈上的任何地方运行时。
- 如果你想要保留Google Closure Compiler Crushing resilience务必不要把指明为字符串的以属性来访问。这意味这你必须用`this.refs['myRefString']`访问如果你的ref被定义为`ref="myRefString"`。
- 如果你没有用React写过数个程序你的第一反应通常是打算试着用refs来在你的应用里"让事情发生"。如果是这样,花一些时间并且更精密的思考`state`应该属于组件层级的哪个位置。常常,这会变得清晰:正确的"拥有"那个属性的地方应该在层级的更高层上。把state放在那里往往消除了任何使用`ref`来 "让事情发生"的渴望 - 作为替代,数据流通常将完成你的目
- 如果你没有用React写过数个程序你的第一反应通常是打算试着用refs来在你的应用里"让事情发生"。如果是这样,花一些时间并且更精密的思考`state`应该属于组件层级的哪个位置。常常,这会变得清晰:正确的"拥有"那个属性的地方应该在层级的更高层上。把state放在那里往往消除了任何使用`ref`来 "让事情发生"的渴望 - 作为替代,数据流通常将完成你的目

View File

@@ -38,4 +38,4 @@ JSXを使用したい場合、[ダウンロードページに](/react/downloads.
### 役に立つオープンソースのプロジェクト
オープンソースコミュニティがJSXをいくつかのエディタやビルドシステムで使用するためのツールを作成しました。一覧は[JSXのインテグレーション](https://github.com/facebook/react/wiki/Complementary-Tools#jsx-integrations)を参照してください。
オープンソースコミュニティがJSXをいくつかのエディタやビルドシステムで使用するためのツールを作成しました。一覧は[JSXのインテグレーション](https://github.com/facebook/react/wiki/Complementary-Tools#jsx-integrations)を参照してください。

View File

@@ -23,7 +23,7 @@ next: addons-ko-KR.html
### 브라우저에서 JSX 변환
JSX를 사용하신다면, [다운로드 페이지](/react/downloads.html)에서 브라우저 JSX 변환기를 제공합니다. 간단히 `<script type="text/jsx">`를 넣으면 JSX 변환기가 작동합니다.
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 변환기가 작동합니다.
> 주의:
>
@@ -32,12 +32,48 @@ JSX를 사용하신다면, [다운로드 페이지](/react/downloads.html)에서
### 상용화하기: 미리 컴파일된 JSX
[npm](https://www.npmjs.com/) 모듈을 가지고 있다면, 간단히 `npm install -g react-tools`를 실행해 커맨드 라인 `jsx` 툴을 설치할 수 있습니다. 이 툴은 JSX 구문을 일반적인 JavaScript파일로 변환해 브라우져에서 바로 실행할 수 있도록 합니다. 디렉터리를 감시해 파일이 변경되었을 때 자동으로 변환하도록 할 수도 있습니다. 예를 들면 `jsx --watch src/ build/` 이렇게요.
[npm](https://www.npmjs.com/) 모듈을 가지고 있다면, `npm install -g babel-cli`를 실행할 수 있습니다. Babel은 React v0.12이상을 내장 지원합니다. 태그는 자동으로 동등한 `React.createElement(...)`로 변환되며, `displayName`은 모든 `React.createClass` 호출에 자동으로 추론, 추가됩니다.
기본적으로는 JSX 파일들은 `.js` 확장자로 변환됩니다. `jsx --extension jsx src/ build/`를 사용해 `.jsx` 확장자로 파일들을 변환할 수 있습니다.
이 툴은 JSX 구문을 일반적인 JavaScript파일로 변환해 브라우져에서 바로 실행할 수 있도록 합니다. 디렉터리를 감시해 파일이 변경되었을 때 자동으로 변환하도록 할 수도 있습니다. 예를 들면 `babel --watch src/ --out-dir lib/` 이렇게요.
이 툴을 어떻게 사용하는지 더 자세하게 알고싶으시면 `jsx --help`를 실행해 보세요.
Babel 6부터 기본값으로 변환기가 포함되지 않게 되었습니다. 이는 `babel` 명령을 실행할 때나 `.babelrc`에 반드시 옵션을 지정해야 한다는 뜻입니다. React를 사용할 때 가장 일반적인 방법은 `es2015`, `react` 프리셋을 사용하는 것입니다. Babel의 변경에 대한 좀 더 자세한 정보는 [블로그에 올라온 Babel 6 공지 글](http://babeljs.io/blog/2015/10/29/6.0.0/)을 읽어보세요.
ES2015 문법과 React를 사용하려 할 경우의 예제입니다.
```
npm install babel-preset-es2015 babel-preset-react
babel --presets es2015,react --watch src/ --out-dir lib/
```
기본적으로는 JSX 파일들은 `.js` 확장자로 변환됩니다. 바벨을 어떻게 사용하는지 더 자세하게 알고싶으시면 `babel --help`를 실행해 보세요.
출력 예:
```
$ cat test.jsx
var HelloMessage = React.createClass({
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
ReactDOM.render(<HelloMessage name="John" />, mountNode);
$ babel test.jsx
"use strict";
var HelloMessage = React.createClass({
displayName: "HelloMessage",
render: function render() {
return React.createElement(
"div",
null,
"Hello ",
this.props.name
);
}
});
ReactDOM.render(React.createElement(HelloMessage, { name: "John" }), mountNode);
```
### 도움되는 오픈소스 프로젝트들

View File

@@ -12,8 +12,7 @@ Every project uses a different system for building and deploying JavaScript. We'
### CDN-hosted React
We provide CDN-hosted versions of React [on our download page](/react/downloads.html). These prebuilt files use the UMD module format. Dropping them in with a simple `<script>` tag will inject a `React` global into your environment. It should also work out-of-the-box in CommonJS and AMD environments.
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 a `React` global into your environment. It should also work out-of-the-box in CommonJS and AMD environments.
### Using master
@@ -29,13 +28,21 @@ If you like using JSX, Babel provides an [in-browser ES6 and JSX transformer for
>
> 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.
### Productionizing: Precompiled JSX
If you have [npm](https://www.npmjs.com/), you can run `npm install -g babel`. Babel has built-in support for React v0.12 and v0.13. Tags are automatically transformed to their equivalent `React.createElement(...)`, `displayName` is automatically inferred and added to all React.createClass calls.
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.
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/`.
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/).
Here is an example of what you will do if using ES2015 syntax and React:
```
npm install babel-preset-es2015 babel-preset-react
babel --presets es2015,react --watch src/ --out-dir lib/
```
By default JSX files with a `.js` extension are transformed. Run `babel --help` for more information on how to use Babel.
Example output:
@@ -68,7 +75,6 @@ var HelloMessage = React.createClass({
ReactDOM.render(React.createElement(HelloMessage, { name: "John" }), mountNode);
```
### Helpful Open-Source Projects
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.

View File

@@ -6,7 +6,7 @@ prev: tooling-integration-ko-KR.html
next: animation-ko-KR.html
---
`React.addons`은 React 앱을 만드는 데 유용한 유틸리티를 두는 곳입니다. **실험적인 기능으로 취급해야 하지만** 결국 코어나 유틸리티 라이브러리에 포함될 예정입니다.
React 애드온은 React 앱을 만드는 데 유용한 유틸리티의 모음입니다. **실험적인 기능으로 취급해야 하** 코어보다 더 자주 변경될 수 있습니다.
- [`TransitionGroup` 과 `CSSTransitionGroup`](animation-ko-KR.html)은 예를 들면 컴포넌트 삭제 직전의 트랜지션 처럼, 구현하기 까다로운 애니메이션과 트랜지션을 다룹니다.
- [`LinkedStateMixin`](two-way-binding-helpers-ko-KR.html)는 사용자 입력과 컴포넌트의 state사이의 조정(coordination)을 단순화 합니다.
@@ -20,6 +20,4 @@ next: animation-ko-KR.html
- [`TestUtils`](test-utils-ko-KR.html)는 테스트 케이스를 적기 위한 간단한 헬퍼입니다. (압축되지 않은 빌드에서만 사용가능)
- [`Perf`](perf-ko-KR.html)는 성능을 측정하고, 최적화를 위한 힌트를 제공합니다.
애드온을 쓰려면, 보통 `react.js` 대신 `react-with-addons.js`(혹은 압축판)을 사용해야 합니다.
npm을 이용해 React 패키지를 설치해 사용한다면, 그냥 `require('react')` 대신 `require('react/addons')`을 사용해 모든 애드온을 쓸 수 있습니다.
애드온을 쓰려면, npm에서 각각 설치하세요.(예를 들면, `npm install react-addons-pure-render-mixin`) npm을 사용하지 않는 애드온 사용법에 대한 지원은 없습니다.

View File

@@ -8,17 +8,17 @@ next: animation-zh-CN.html
`React.addons` 是我们放置一些用来构建React apps的有用的工具的地方。 **这些应该被认为是实验性的** 但是最终批量进入核心代码或者一个有用的工具库中:
- [`TransitionGroup` 和 `CSSTransitionGroup`](animation.html), 用来处理通常不能简单实现的动画和转换,比如在组件移除之前。
- [`LinkedStateMixin`](two-way-binding-helpers.html), 简化用户的表单输入数据与组件状态的协调。
- [`cloneWithProps`](clone-with-props.html), 创建React组件的浅拷贝并改变它们的props。
- [`TransitionGroup` 和 `CSSTransitionGroup`](animation.html), 用来处理通常不能简单实现的动画和转换,比如在组件移除之前。
- [`LinkedStateMixin`](two-way-binding-helpers.html), 简化用户的表单输入数据与组件状态的协调。
- [`cloneWithProps`](clone-with-props.html), 创建React组件的浅拷贝并改变它们的props。
- [`createFragment`](create-fragment.html), 创建一组外键的子级。
- [`update`](update.html), 一个使不可变数据在JavaScript里更易处理的辅助函数。
- [`update`](update.html), 一个使不可变数据在JavaScript里更易处理的辅助函数。
- [`PureRenderMixin`](pure-render-mixin.html), 一个特定情况下的性能优化器。
下面的插件只存在开发版(未压缩)React中
- [`TestUtils`](test-utils.html), 用于写测试用例的简单的辅助工具(仅存在于未压缩版本)。
- [`Perf`](perf.html), 用于测量性能并给你提示哪里可以优化。
- [`Perf`](perf.html), 用于测量性能并给你提示哪里可以优化。
要获取插件,使用 `react-with-addons.js` (和它的压缩副本)而不是通常的 `react.js`

View File

@@ -44,7 +44,7 @@ var TodoList = React.createClass({
return (
<div>
<button onClick={this.handleAdd}>Aggiungi Elemento</button>
<ReactCSSTransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={300} >
<ReactCSSTransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={300}>
{items}
</ReactCSSTransitionGroup>
</div>

View File

@@ -199,7 +199,7 @@ var ImageCarousel = React.createClass({
### 異なるコンポーネントをレンダリングする
デフォルトで、 `ReactTransitionGroup` は `span` としてレンダリングされます。この動きは、 `component` プロパティによって変更できます。例えば、 `<ul>` をレンダリングしたい場合は以下のようになります。
デフォルトで、 `ReactTransitionGroup` は `span` としてレンダリングされます。この動きは、 `component` プロパティによって変更できます。例えば、 `<ul>` をレンダリングしたい場合は以下のようになります。
```javascript{1}
<ReactTransitionGroup component="ul">

View File

@@ -18,7 +18,7 @@ React에는 애니메이션을 위한 저 수준 API로 `ReactTransitionGroup`
`ReactCSSTransitionGroup``ReactTransitions`을 위한 인터페이스입니다. 이는 애니메이션을 제어할 모든 컴포넌트를 감싸는 하나의 엘리먼트 입니다. 아래는 목록의 아이템을 페이드 인/아웃하는 간단한 예제입니다.
```javascript{28-30}
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
var ReactCSSTransitionGroup = require('react-addons-css-transition-group');
var TodoList = React.createClass({
getInitialState: function() {
@@ -45,7 +45,7 @@ var TodoList = React.createClass({
return (
<div>
<button onClick={this.handleAdd}>Add Item</button>
<ReactCSSTransitionGroup transitionName="example">
<ReactCSSTransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={300}>
{items}
</ReactCSSTransitionGroup>
</div>
@@ -53,9 +53,10 @@ var TodoList = React.createClass({
}
});
```
> 주의:
>
> `ReactCSSTransitionGroup`의 모든 자식은 [`key` 어트리뷰트](/react/docs/multiple-components-ko-KR.html#dynamic-children)를 반드시 만들어야 합니다. 한 아이템을 렌더한다 해도 예외는 아닙니다. 키는 React가 어떤 자식이 들어오고, 나가고, 머무르는지 파악할 때 사용합니다.
> `ReactCSSTransitionGroup`의 모든 자식은 [`key` 어트리뷰트](/react/docs/multiple-components-ko-KR.html#dynamic-children)를 반드시 만들어야 합니다. 한 아이템을 렌더할 때도 예외는 아닙니다. 키는 React가 어떤 자식이 들어오고, 나가고, 머무르는지 파악할 때 사용합니다.
이 컴포넌트에서 새로운 아이템이 `ReactCSSTransitionGroup`에 추가되면 `example-enter` 아이템은 CSS 클래스를 가지게 되고 다음 순간에 `example-enter-active` CSS 클래스가 추가됩니다. 이는 `transitionName` prop을 기반으로 한 관례입니다.
@@ -68,23 +69,21 @@ var TodoList = React.createClass({
.example-enter.example-enter-active {
opacity: 1;
transition: opacity .5s ease-in;
transition: opacity 500ms ease-in;
}
```
`ReactCSSTransitionGroup`에서 아이템을 제거하려해도 DOM에는 남게 됩니다. 만약 애드온을 React의 최소화하지 않은 빌드와 사용한다면, 애니메이션이나 트랜지션이 일어나는 것을 예상하고 있었다는 React의 경고를 보게 될 것입니다. 그게 바로 `ReactCSSTransitionGroup`가 DOM 엘리먼트를 애니메이션이 끝날 때까지 페이지에 남겨두는 이유입니다. 이 CSS를 넣어보세요.
```css
.example-leave {
opacity: 1;
}
.example-leave.example-leave-active {
opacity: 0.01;
transition: opacity .5s ease-in;
transition: opacity 300ms ease-in;
}
```
에니메이션 기간이 CSS와 렌더 메소드 양쪽에 지정될 필요가 있다는 것에 주의하셔야 합니다. 이는 엘리먼트에서 애니메이션 클래스를 제거할 때 (만약 남아있다면) DOM에서 엘리먼트를 제거할 때 React에 알려줍니다.
### 처음 마운트에서 애니메이션 하기
`ReactCSSTransitionGroup`은 컴포넌트를 처음 마운트할 때 추가 트렌지션 단계를 추가하기 위해, 선택적인 prop `transitionAppear`를 제공합니다. 일반적으로 처음 마운트할 때 트렌지션 단계를 넣지 않기 때문에 `transitionAppear`의 기본 값은 `false`입니다. 뒤의 예제는 `transitionAppear` prop에 `true` 값을 넘기고 있습니다.
@@ -92,7 +91,7 @@ var TodoList = React.createClass({
```javascript{3-5}
render: function() {
return (
<ReactCSSTransitionGroup transitionName="example" transitionAppear={true}>
<ReactCSSTransitionGroup transitionName="example" transitionAppear={true} transitionAppearTimeout={500}>
<h1>Fading at Initial Mount</h1>
</ReactCSSTransitionGroup>
);
@@ -104,11 +103,11 @@ var TodoList = React.createClass({
```css
.example-appear {
opacity: 0.01;
transition: opacity .5s ease-in;
}
.example-appear.example-appear-active {
opacity: 1;
transition: opacity .5s ease-in;
}
```
@@ -125,23 +124,23 @@ var TodoList = React.createClass({
```javascript
...
<ReactCSSTransitionGroup
transitionName={
transitionName={ {
enter: 'enter',
enterActive: 'enterActive',
leave: 'leave',
leaveActive: 'leaveActive',
appear: 'appear',
appearActive: 'appearActive'
}>
} }>
{item}
</ReactCSSTransitionGroup>
<ReactCSSTransitionGroup
transitionName={
transitionName={ {
enter: 'enter',
leave: 'leave',
appear: 'appear'
}>
} }>
{item2}
</ReactCSSTransitionGroup>
...
@@ -176,7 +175,7 @@ var TodoList = React.createClass({
위의 예제에서 `ReactCSSTransitionGroup`에 아이템 목록을 렌더했지만, `ReactCSSTransitionGroup`의 자식은 하나이거나 없을 수도 있습니다. 이는 한 엘리먼트가 들어오고 나가는 것의 애니메이션을 가능하게 합니다. 비슷하게, 현재 엘리먼트가 나가는 동안 새 앨리먼트의 애니메이션을 하면, 새 엘리먼트가 현재 엘리먼트를 교체하는 애니메이션을 만들 수 있습니다. 예를 들어 이렇게 간단한 이미지 회전 베너(carousel)를 구현할 수 있습니다.
```javascript{10-12}
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
var ReactCSSTransitionGroup = require('react-addons-css-transition-group');
var ImageCarousel = React.createClass({
propTypes: {
@@ -185,7 +184,7 @@ var ImageCarousel = React.createClass({
render: function() {
return (
<div>
<ReactCSSTransitionGroup transitionName="carousel">
<ReactCSSTransitionGroup transitionName="carousel" transitionEnterTimeout={300} transitionLeaveTimeout={300}>
<img src={this.props.imageSrc} key={this.props.imageSrc} />
</ReactCSSTransitionGroup>
</div>
@@ -204,7 +203,7 @@ var ImageCarousel = React.createClass({
## 저수준 API: `ReactTransitionGroup`
`ReactTransitionGroup`은 애니메이션의 기초입니다. 이는 `React.addons.TransitionGroup`으로 접근할 수 있습니다. 위에 있는 예제처럼 자식들이 선언적으로 여기에 추가되거나 삭제되는 경우, 특별한 훅이 이 생명주기에서 호출됩니다.
`ReactTransitionGroup`은 애니메이션의 기초입니다. 이는 `require('react-addons-transition-group')`으로 접근할 수 있습니다. 위 예제처럼 자식들이 선언적으로 여기에 추가되거나 삭제되는 경우, 특별한 훅이 이 생명주기에서 호출됩니다.
### `componentWillAppear(callback)`
@@ -240,11 +239,7 @@ var ImageCarousel = React.createClass({
</ReactTransitionGroup>
```
모든 React가 렌더할 수 있는 DOM 컴포넌트는 사용할 수 있습니다. 하지만 `component`가 DOM 컴포넌트일 필요는 없습니다. React 컴포넌트라면 무엇이든 넣을 수 있습니다. 직접 구현한 컴포넌트여도 됩니다!
> 주의:
>
> v0.12이전에는, DOM 컴포넌트를 사용할 때, `component` prop은 `React.DOM.*`로 참조할 필요가 있었습니다. 이제 컴포넌트가 단순히 `React.createElement`로 전달되기 때문에, `component` prop은 스트링이어야 합니다. 복합 컴포넌트는 팩토리를 넘겨야 합니다.
React가 렌더할 수 있는 DOM 컴포넌트는 전부 사용할 수 있습니다. 하지만 `component`가 DOM 컴포넌트일 필요는 없습니다. React 컴포넌트라면 무엇이든 넣을 수 있습니다. 직접 구현한 컴포넌트여도 됩니다! 그냥 `component={List}`를 적으면 컴포넌트는 `this.props.children`로 받을 수 있습니다.
사용자 정의를 포함한 어떤 프로퍼티도 렌더된 컴포넌트의 프로퍼티가 됩니다. 예를 들어, `<ul>`에 CSS 클래스를 넣어서 렌더하려면 이렇게 하면 됩니다.

View File

@@ -6,7 +6,7 @@ prev: addons.html
next: two-way-binding-helpers.html
---
React provides a `ReactTransitionGroup` addon component as a low-level API for animation, and a `ReactCSSTransitionGroup` for easily implementing basic CSS animations and transitions.
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.
## High-level API: `ReactCSSTransitionGroup`
@@ -44,7 +44,7 @@ var TodoList = React.createClass({
return (
<div>
<button onClick={this.handleAdd}>Add Item</button>
<ReactCSSTransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={300} >
<ReactCSSTransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={300}>
{items}
</ReactCSSTransitionGroup>
</div>
@@ -52,6 +52,7 @@ var TodoList = React.createClass({
}
});
```
> Note:
>
> You must provide [the `key` attribute](/react/docs/multiple-components.html#dynamic-children) for all children of `ReactCSSTransitionGroup`, even when only rendering a single item. This is how React will determine which children have entered, left, or stayed.

View File

@@ -44,7 +44,7 @@ var TodoList = React.createClass({
return (
<div>
<button onClick={this.handleAdd}>Add Item</button>
<ReactCSSTransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={300} >
<ReactCSSTransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={300}>
{items}
</ReactCSSTransitionGroup>
</div>
@@ -144,7 +144,7 @@ var TodoList = React.createClass({
...
```
### 动画组必须挂载才工作
### 动画组必须挂载才工作
为了使过渡效果应用到子级上,`ReactCSSTransitionGroup`必须已经挂载到了DOM或者 prop `transitionAppear` 必须被设置为 `true`。下面的例子不会工作,因为 `ReactCSSTransitionGroup` 随同新项目被挂载,而不是新项目在它内部被挂载。将这与上面的[入门指南](#入门指南)部分比较一下,看看不同。

View File

@@ -15,7 +15,7 @@ Reactでは所有者から子要素へと、データの流れは一方向です
しかし、データやプログラムに戻る流れを読む必要が有るアプリケーションもたくさんあります。例えば、フォームを作る際に、ユーザのインプットを受け取った時には、Reactの `state` を更新したいと思うことはよくあるでしょう。または、JavaScriptでレイアウトを形作ったり、DOM要素のサイズの変化に反応したいと思うでしょう。
Reactでは、「変更」のイベントを検知し、データソース普通はDOMですを読み、コンポーネントのうちの1つの上で `setState()` を呼ぶことでこの要求を満たすことができます。「データフローのループを止めること」は理解しやすく、維持しやすいプログラムを明確に導きます。詳細な情報については、[フォームのドキュメント](/react/docs/forms-ja-JP.html)をご覧ください。
Reactでは、「変更」のイベントを検知し、データソース普通はDOMですを読み、コンポーネントのうちの1つの上で `setState()` を呼ぶことでこの要求を満たすことができます。「データフローのループを止めること」は理解しやすく、維持しやすいプログラムを明確に導きます。詳細な情報については、[フォームのドキュメント](/react/docs/forms-ja-JP.html)をご覧ください。
2ウェイバインディングはDOMの値が常にReactの `state` と一致していることを暗黙に強制しますが、簡潔で、多くの種類のアプリケーションをサポートします。上で説明されているような共通のデータフローループパターンのセットアップや、データソースをReactの `state` に「接続する」ための糖衣構文である `ReactLink` が提供されています。
@@ -111,4 +111,4 @@ var WithoutLink = React.createClass({
});
```
`valueLink` プロパティも同様にとても単純です。単純に `onChange` イベントをハンドルし、 `this.props.valueLink.requestChange()` を呼び、 `this.props.value` の代わりに `this.props.valueLink.value` を使用します。それだけです!
`valueLink` プロパティも同様にとても単純です。単純に `onChange` イベントをハンドルし、 `this.props.valueLink.requestChange()` を呼び、 `this.props.value` の代わりに `this.props.valueLink.value` を使用します。それだけです!

View File

@@ -45,9 +45,11 @@ var NoLink = React.createClass({
이것은 정말 잘 동작하고, 데이터가 어떻게 흐르는지 매우 명확하게 보여지지만, 폼필드가 많을 경우 약간 장황해 질 수 있습니다. 타이핑을 줄이기 위해 `ReactLink`를 사용해 보겠습니다.
```javascript{2,7}
```javascript{4,9}
var LinkedStateMixin = require('react-addons-linked-state-mixin');
var WithLink = React.createClass({
mixins: [React.addons.LinkedStateMixin],
mixins: [LinkedStateMixin],
getInitialState: function() {
return {message: 'Hello!'};
},
@@ -66,7 +68,6 @@ checkbox의 `value` 어트리뷰트는 다른 것과 다르게 checkbox가 체
<input type="checkbox" checkedLink={this.linkState('booleanValue')} />
```
## 내부 구조
`ReactLink`에는 크게 인스턴스를 생성하는 면과 사용하는 면이 있습니다. `ReactLink`가 얼마나 간단한지 확인하기 위해, 이 부분들을 보다 명시적으로 고쳐 봅시다.
@@ -96,8 +97,10 @@ var WithoutMixin = React.createClass({
### valueLink 없이 ReactLink 쓰기
```javascript
var LinkedStateMixin = require('react-addons-linked-state-mixin');
var WithoutLink = React.createClass({
mixins: [React.addons.LinkedStateMixin],
mixins: [LinkedStateMixin],
getInitialState: function() {
return {message: 'Hello!'};
},

View File

@@ -45,7 +45,7 @@ var NoLink = React.createClass({
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:
```javascript{2,7}
```javascript{4,9}
var LinkedStateMixin = require('react-addons-linked-state-mixin');
var WithLink = React.createClass({
@@ -68,7 +68,6 @@ Note that checkboxes have a special behavior regarding their `value` attribute,
<input type="checkbox" checkedLink={this.linkState('booleanValue')} />
```
## Under the Hood
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.

View File

@@ -8,7 +8,7 @@ next: test-utils-ko-KR.html
> 주의:
>
> 이 모듈은 이제 [JedWatson/classnames](https://github.com/JedWatson/classnames)에 독립적으로 있고 React와 관련없습니다. 그러므로 이 애드온은 제거될 예정입니다.
> 이 모듈은 폐기예정입니다. 대신 [JedWatson/classnames](https://github.com/JedWatson/classnames)를 사용하세요.
`classSet()`은 간단히 DOM `class` 문자열을 조작하는 편리한 도구입니다.

View File

@@ -19,14 +19,14 @@ Simulate.{eventName}(
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`.**
**Cliccare un elemento**
**Cliccare un elemento**
```javascript
var node = ReactDOM.findDOMNode(this.refs.button);
React.addons.TestUtils.Simulate.click(node);
```
**Cambiare il valore di un campo di input e in seguito premere INVIO**
**Cambiare il valore di un campo di input e in seguito premere INVIO**
```javascript
var node = ReactDOM.findDOMNode(this.refs.input);

View File

@@ -6,39 +6,66 @@ prev: two-way-binding-helpers-ko-KR.html
next: clone-with-props-ko-KR.html
---
`React.addons.TestUtils`는 선택한 테스트 프레임워크(React는 [Jest](https://facebook.github.io/jest/)를 사용)에서 React 컴포넌트를 테스트하기 쉽게 합니다.
`ReactTestUtils`는 선택한 테스트 프레임워크(React는 [Jest](https://facebook.github.io/jest/)를 사용)에서 React 컴포넌트를 테스트하기 쉽게 합니다.
```
var ReactTestUtils = require('react-addons-test-utils');
```
### Simulate
```javascript
Simulate.{eventName}(DOMElement element, object eventData)
Simulate.{eventName}(
DOMElement element,
[object eventData]
)
```
DOM 노드에 이벤트 디스패치하는 것을 시뮬레이트합니다. 선택적으로 `eventData`를 통해 이벤트 데이터도 처리할 수 있습니다. **아마 `ReactTestUtils`에서 가장 유용한 유틸리티일 것 입니다.**
사용 예:
**엘리먼트 클릭**
```javascript
var node = ReactDOM.findDOMNode(this.refs.input);
React.addons.TestUtils.Simulate.click(node);
React.addons.TestUtils.Simulate.change(node, {target: {value: 'Hello, world'}});
React.addons.TestUtils.Simulate.keyDown(node, {key: "Enter"});
// <button ref="button">...</button>
var node = this.refs.button;
ReactTestUtils.Simulate.click(node);
```
**입력 필드의 값을 변경하고 엔터 누르기.**
```javascript
// <input ref="input" />
var node = this.refs.input;
node.value = 'giraffe'
ReactTestUtils.Simulate.change(node);
ReactTestUtils.Simulate.keyDown(node, {key: "Enter", keyCode: 13, which: 13});
```
*컴포넌트에서 사용할 이벤트 프로퍼티(예를 들어 keyCode, which, 등등...)는 React에서 만들어 주지 않으므로 직접 제공해야 합니다.*
`Simulate`에는 React가 이해하는 모든 이벤트에 대해 메소드가 있습니다.
### renderIntoDocument
```javascript
ReactComponent renderIntoDocument(ReactElement instance)
ReactComponent renderIntoDocument(
ReactElement instance
)
```
문서의 detach된 DOM 노드에 컴포넌트를 렌더합니다. **이 기능은 DOM을 필요로 합니다.**
> 주의:
>
> React를 임포트하기 **전에** `window`, `window.document`, `window.document.createElement`을 전역적으로 사용가능하게 해두어야 합니다. 아니면 React는 DOM과 `setState`같은 메소드가 동작하지 않는다고 생각할 수 있습니다.
### mockComponent
```javascript
object mockComponent(function componentClass, string? mockTagName)
object mockComponent(
function componentClass,
[string mockTagName]
)
```
목 컴포넌트 모듈을 이 메소드에 넘겨 더미 React 컴포넌트로 사용할 수 있도록 합니다. 이 더미는 유용한 메소드와 함께 사용해 기능을 보강할 수 있습니다. 일반적인 렌더링과는 다르게, 컴포넌트는 제공된 자식을 포함하는 평범한 `<div>`가 됩니다. (`mockTagName`을 통해 div가 아닌 다른 태그를 지정해 줄 수도 있습니다.)
@@ -46,7 +73,9 @@ object mockComponent(function componentClass, string? mockTagName)
### isElement
```javascript
boolean isElement(ReactElement element)
boolean isElement(
ReactElement element
)
```
`element`가 ReactElement면 `true`를 리턴합니다.
@@ -54,7 +83,10 @@ boolean isElement(ReactElement element)
### isElementOfType
```javascript
boolean isElementOfType(ReactElement element, function componentClass)
boolean isElementOfType(
ReactElement element,
function componentClass
)
```
`element`가 React `componentClass` 타입인 ReactElement면 `true`를 리턴합니다.
@@ -62,7 +94,9 @@ boolean isElementOfType(ReactElement element, function componentClass)
### isDOMComponent
```javascript
boolean isDOMComponent(ReactComponent instance)
boolean isDOMComponent(
ReactComponent instance
)
```
`instance`가 (`<div>``<span>`같은) DOM 컴포넌트면 `true`를 리턴합니다.
@@ -78,7 +112,10 @@ boolean isCompositeComponent(ReactComponent instance)`
### isCompositeComponentWithType
```javascript
boolean isCompositeComponentWithType(ReactComponent instance, function componentClass)
boolean isCompositeComponentWithType(
ReactComponent instance,
function componentClass
)
```
`instance`가 (`React.createClass()`로 생성된) 복합 컴포넌트고 React `componentClass` 타입이면 `true`를 리턴합니다.
@@ -86,7 +123,10 @@ boolean isCompositeComponentWithType(ReactComponent instance, function component
### findAllInRenderedTree
```javascript
array findAllInRenderedTree(ReactComponent tree, function test)
array findAllInRenderedTree(
ReactComponent tree,
function test
)
```
`tree`안의 모든 컴포넌트에서 `test(component)``true`인 모든 컴포넌트를 모읍니다. 이것만으로는 그렇게 유용하지 않습니다만, 다른 테스트 유틸와 같이 사용합니다.
@@ -94,7 +134,9 @@ array findAllInRenderedTree(ReactComponent tree, function test)
### scryRenderedDOMComponentsWithClass
```javascript
array scryRenderedDOMComponentsWithClass(ReactComponent tree, string className)
array scryRenderedDOMComponentsWithClass(
ReactComponent tree, string className
)
```
렌더된 트리의 모든 컴포넌트 인스턴스 중에서 클래스 이름이 `className`인 DOM 컴포넌트들을 찾습니다.
@@ -109,7 +151,10 @@ ReactComponent findRenderedDOMComponentWithClass(ReactComponent tree, string cla
### scryRenderedDOMComponentsWithTag
```javascript
array scryRenderedDOMComponentsWithTag(ReactComponent tree, string tagName)
array scryRenderedDOMComponentsWithTag(
ReactComponent tree,
string tagName
)
```
렌더된 트리의 모든 컴포넌트 인스턴스중에서 태그 이름이 `tagName`인 DOM 컴포넌트들을 찾습니다.
@@ -117,7 +162,10 @@ array scryRenderedDOMComponentsWithTag(ReactComponent tree, string tagName)
### findRenderedDOMComponentWithTag
```javascript
ReactComponent findRenderedDOMComponentWithTag(ReactComponent tree, string tagName)
ReactComponent findRenderedDOMComponentWithTag(
ReactComponent tree,
string tagName
)
```
`scryRenderedDOMComponentsWithTag()`와 비슷하지만 하나의 결과만 기대될 때 사용합니다. 하나의 결과를 리턴하거나 한개 이상의 결과가 나온 경우에는 예외를 던집니다.
@@ -125,7 +173,10 @@ ReactComponent findRenderedDOMComponentWithTag(ReactComponent tree, string tagNa
### scryRenderedComponentsWithType
```javascript
array scryRenderedComponentsWithType(ReactComponent tree, function componentClass)
array scryRenderedComponentsWithType(
ReactComponent tree,
function componentClass
)
```
타입이 `componentClass`인 모든 컴포넌트 인스턴스를 찾습니다.
@@ -133,7 +184,9 @@ array scryRenderedComponentsWithType(ReactComponent tree, function componentClas
### findRenderedComponentWithType
```javascript
ReactComponent findRenderedComponentWithType(ReactComponent tree, function componentClass)
ReactComponent findRenderedComponentWithType(
ReactComponent tree, function componentClass
)
```
`scryRenderedComponentsWithType()`와 비슷하지만 하나의 결과만 기대될 때 사용합니다. 하나의 결과를 리턴하거나 한개 이상의 결과가 나온 경우에는 예외를 던집니다.
@@ -149,13 +202,15 @@ ReactShallowRenderer createRenderer()
테스트에서 얕은 렌더러를 생성하고자 할때 호출합니다. 이를 이벤트와 업데이트에 스스로 반응하는 컴포넌트를 렌더하기 위한 "장소"라고 생각할 수 있습니다.
```javascript
shallowRenderer.render(ReactElement element)
shallowRenderer.render(
ReactElement element
)
```
`ReactDOM.render`와 유사합니다.
```javascript
ReactComponent shallowRenderer.getRenderOutput()
ReactElement shallowRenderer.getRenderOutput()
```
`render`가 호출 된 후, 얕게 렌더된 결과물을 반환합니다. 그 후엔 결과물에 대한 검증을 시작할 수 있습니다. 예를 들어 컴포넌트의 렌더 메소드가 다음을 반환한다면:

View File

@@ -23,7 +23,7 @@ Simulate.{eventName}(
Simulate an event dispatch on a DOM node with optional `eventData` event data. **This is possibly the single most useful utility in `ReactTestUtils`.**
**Clicking an element**
**Clicking an element**
```javascript
// <button ref="button">...</button>
@@ -31,7 +31,7 @@ var node = this.refs.button;
ReactTestUtils.Simulate.click(node);
```
**Changing the value of an input field and then pressing ENTER**
**Changing the value of an input field and then pressing ENTER.**
```javascript
// <input ref="input" />
@@ -41,7 +41,7 @@ ReactTestUtils.Simulate.change(node);
ReactTestUtils.Simulate.keyDown(node, {key: "Enter", keyCode: 13, which: 13});
```
*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*
*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.*
`Simulate` has a method for every event that React understands.
@@ -58,7 +58,7 @@ Render a component into a detached DOM node in the document. **This function req
> Note:
>
> 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.
globally available **before** you import React. Otherwise React will think it can't access the DOM and methods like `setState` won't work.
### mockComponent
@@ -198,7 +198,6 @@ ReactComponent findRenderedComponentWithType(
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.
## Shallow rendering
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.
@@ -218,7 +217,7 @@ shallowRenderer.render(
Similar to `ReactDOM.render`.
```javascript
ReactComponent shallowRenderer.getRenderOutput()
ReactElement shallowRenderer.getRenderOutput()
```
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:

View File

@@ -31,4 +31,4 @@ ReactDOM.render(
);
```
`cloneWithProps``key``ref` をクローンされた要素に渡すことはありません。 `className``style` は自動的にマージされます。
`cloneWithProps``key``ref` をクローンされた要素に渡すことはありません。 `className``style` は自動的にマージされます。

View File

@@ -12,8 +12,10 @@ next: create-fragment-ko-KR.html
드문 경우긴 하지만 원래 엘리먼트와 다른 prop을 가진 React 엘리먼트의 복사본을 만들고 싶을 때가 있습니다. 예를 들면 `this.props.children`에 클론한 엘리먼트를 넘기고 다른 prop으로 렌더링하는 경우 입니다.
```js
var cloneWithProps = require('react-addons-clone-with-props');
var _makeBlue = function(element) {
return React.addons.cloneWithProps(element, {style: {color: 'blue'}});
return cloneWithProps(element, {style: {color: 'blue'}});
};
var Blue = React.createClass({

View File

@@ -18,7 +18,7 @@ var Swapper = React.createClass({
rightChildren: React.PropTypes.node,
swapped: React.PropTypes.bool
}
},
render: function() {
var children;
if (this.props.swapped) {
@@ -33,20 +33,22 @@ var Swapper = React.createClass({
`swapped` prop을 변경할 경우 자식은 마운트 해제되거나 다시 마운트 될 수 있습니다. 두 자식 집합에 키가 할당되지 않았기 때문입니다.
이 문제를 해결하기 위해서 `React.addons.createFragment`를 사용해 자식 집합에 키를 부여할 수 있습니다.
이 문제를 해결하기 위해서 `createFragment`를 사용해 자식 집합에 키를 부여할 수 있습니다.
#### `ReactFragment React.addons.createFragment(object children)`
#### `Array<ReactNode> createFragment(object children)`
배열을 만드는 대신에 다음과 같이 해볼 수 있습니다:
```js
var createFragment = require('react-addons-create-fragment');
if (this.props.swapped) {
children = React.addons.createFragment({
children = createFragment({
right: this.props.rightChildren,
left: this.props.leftChildren
});
} else {
children = React.addons.createFragment({
children = createFragment({
left: this.props.leftChildren,
right: this.props.rightChildren
});

View File

@@ -56,7 +56,7 @@ var newData = React.addons.update(myData, {
## 使用できるコマンド
* `{$push: array}` ターゲットに `array` の全ての要素を `push()` します。
* `{$push: array}` ターゲットに `array` の全ての要素を `push()` します。
* `{$unshift: array}` ターゲットの `array` の全ての要素を `unshift()` します。
* `{$splice: array of arrays}` `arrays` の全ての要素について、その要素によって提供されるパラメータのターゲットにおいて、 `splice()` を呼び出します。
* `{$set: any}` ターゲットを完全に置き換えます。

View File

@@ -44,7 +44,9 @@ var newData = extend(myData, {
`update()`는 이런 패턴 속에서 코드를 더 쉽게 쓸 수 있도록 편의 문법을 제공합니다. 코드는 이렇습니다:
```js
var newData = React.addons.update(myData, {
var update = require('react-addons-update');
var newData = update(myData, {
x: {y: {z: {$set: 7}}},
a: {b: {$push: [9]}}
});

View File

@@ -20,7 +20,7 @@ myData.x.y.z = 7;
myData.a.b.push(9);
```
you have no way of determining which data has changed since the previous copy has been overwritten. Instead, you need to create a new copy of `myData` and change only the parts of it that need to be changed. Then you can compare the old copy of `myData` with the new one in `shouldComponentUpdate()` using triple-equals:
You have no way of determining which data has changed since the previous copy has been overwritten. Instead, you need to create a new copy of `myData` and change only the parts of it that need to be changed. Then you can compare the old copy of `myData` with the new one in `shouldComponentUpdate()` using triple-equals:
```js
var newData = deepCopy(myData);

View File

@@ -25,4 +25,4 @@ React.createClass({
> 注意:
> このミックスインはオブジェクトの比較のみを行います。それらが複雑なデータ構造を持っていた場合、深い位置における違いは見逃されることがあります。単純なpropsやstateをコンポーネントが持っている場合にのみ、使用してください。深いデータ構造が変更されることが分かっている場合は、 `forceUpdate()` を使用してください。または、ネストされたデータの比較を速く行うために[不変オブジェクト](https://facebook.github.io/immutable-js/)の使用を考えてみてください。
> 更に、 `shouldComponentUpdate` は全てのコンポーネントのサブツリーのアップデートをスキップします。全ての子要素のコンポーネントもまた、「ピュア」であることを確認してください。
> 更に、 `shouldComponentUpdate` は全てのコンポーネントのサブツリーのアップデートをスキップします。全ての子要素のコンポーネントもまた、「ピュア」であることを確認してください。

View File

@@ -11,7 +11,7 @@ React 컴포넌트의 렌더 함수가 "pure"하다면 (다른 말로, props나
예제:
```js
var PureRenderMixin = require('react/addons').addons.PureRenderMixin;
var PureRenderMixin = require('react-addons-pure-render-mixin');
React.createClass({
mixins: [PureRenderMixin],

View File

@@ -11,7 +11,7 @@ If your React component's render function is "pure" (in other words, it renders
Example:
```js
var PureRenderMixin = require('react/addons').addons.PureRenderMixin;
var PureRenderMixin = require('react-addons-pure-render-mixin');
React.createClass({
mixins: [PureRenderMixin],

View File

@@ -16,11 +16,13 @@ React는 보통 처음에는 꽤 빠릅니다. 하지만 모든 성능을 짜내
## 일반 API
여기에서 설명하는 `Perf` 객체는 `react-with-addons.js`를 사용해 개발 모드에서 빌드될 때 `React.addons.Perf`로 노출됩니다.
여기에서 설명하는 `Perf` 객체는 `require('react-addons-perf')`로 노출되고 React 개발 모드에서만 사용할 수 있습니다. 이 번들을 프로덕션에서 앱과 같이 빌드하시면 안됩니다.
### `Perf.start()`와 `Perf.stop()`
측정을 시작/정지합니다. 그 사이의 React 연산은 밑에 있는 분석을 하기위해 기록됩니다. 미미한 양의 연산은 무시됩니다.
종료 후, 측정을 하기위해서는 이후에 설명할 `Perf.getLastMeasurements()`가 필요합니다.
### `Perf.printInclusive(measurements)`
전 수행 시간을 출력합니다. 인자가 넘겨지지 않으면, 기본값은 지난 기록부터의 모든 측정이 됩니다. 이 출력은 밑에 있는 것처럼 콘솔에서 깔끔한 테이블로 그려집니다.

View File

@@ -202,4 +202,4 @@ this.messages = this.messages.push(new Message({
データ構造が不変であることで、push関数の結果を `this.messages` にアサインする必要があることに注意してください。
Reactの側では、 immutable-js のデータ構造をコンポーネントの state を保持するために使用する場合は、 `PureRenderMixin` をコンポーネントにミックスし、再レンダリングのプロセスを短縮することもできます。
Reactの側では、 immutable-js のデータ構造をコンポーネントの state を保持するために使用する場合は、 `PureRenderMixin` をコンポーネントにミックスし、再レンダリングのプロセスを短縮することもできます。

View File

@@ -3,6 +3,7 @@ id: advanced-performance-ko-KR
title: 성능 심화
permalink: advanced-performance-ko-KR.html
prev: perf-ko-KR.html
next: context-ko-KR.html
---
React를 도입하려 할 때 많은 사람이 묻는 첫 번째 질문은 React를 사용하지 않을 때처럼 애플리케이션이 빠르고 반응성도 좋을 것이냐는 것입니다. 모든 상태변화에 대해 컴포넌트의 하위 트리를 전부 다시 렌더링하는 아이디어에 대해 사람들은 이 프로세스가 성능에 부정적인 영향을 줄 것으로 생각하지만, React는 여러 가지 영리한 방법을 통해 UI를 업데이트하는데 필요한 비싼 DOM 조작을 최소화합니다.
@@ -52,7 +53,7 @@ React.createClass({
},
render: function() {
return <div>this.props.value</div>;
return <div>{this.props.value}</div>;
}
});
```
@@ -76,7 +77,7 @@ React.createClass({
},
render: function() {
return <div>this.props.value.foo</div>;
return <div>{this.props.value.foo}</div>;
}
});
```

View File

@@ -3,6 +3,7 @@ id: advanced-performance
title: Advanced Performance
permalink: advanced-performance.html
prev: perf.html
next: context.html
---
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.

View File

@@ -0,0 +1,174 @@
---
id: context
title: 컨텍스트
permalink: context-ko-KR.html
prev: advanced-performance-ko-KR.html
---
React의 가장 큰 장점 중 하나는 React 컴포넌트를 통해 데이터의 흐름을 추적하기 쉽다는 것입니다. 컴포넌트를 보면 각각의 프로퍼티가 어떻게 전달되었는지 쉽게 파악할 수 있습니다.
때때로 컴포넌트 트리를 통해 props을 전단하는 대신 수동으로 모든 레벨에서 데이터를 전달하고 싶은 경우가 있습니다. React의 "컨텍스트" 기능은 이를 가능하게 해줍니다.
> 주의:
>
> 컨텍스트는 실험적인 고급 기능입니다. 향후 릴리즈에서 API가 변경될 수 있습니다.
>
> 대부분은 애플리켄이션은 컨텍스트가 필요하지 않을겁니다. 특히 React로 시작한 경우에는 컨텍스트를 사용하지 않을겁니다. 컨텍스트의 사용은 데이터 흐름을 명확하지 않게 만들기 때문에 코드를 이해하기 어려워 집니다. 이는 마치 앱에서 전역 변수를 state로 전달하는 경우와 유사합니다.
>
> **만약 컨텍스트를 사용해야 하는 경우에도, 가능한 아껴 사용하세요.**
>
> 구축하는것이 애플리케이션이든 라이브러리든간에, 가능한 컨텍스트의 사용은 작은 영역으로 격리하고 직접적으로 컨텍스트 API를 사용하는 것을 피하세요. 그렇게 하면 API가 변경 되더라도 쉽게 업데이트 할 수 있습니다.
## 트리를 통해 정보를 자동으로 전달하기
아래와 같은 구조가 있다고 가정해 봅시다:
```javascript
var Button = React.createClass({
render: function() {
return (
<button style={{'{{'}}background: this.props.color}}>
{this.props.children}
</button>
);
}
});
var Message = React.createClass({
render: function() {
return (
<div>
{this.props.text} <Button color={this.props.color}>삭제</Button>
</div>
);
}
});
var MessageList = React.createClass({
render: function() {
var color = "purple";
var children = this.props.messages.map(function(message) {
return <Message text={message.text} color={color} />;
});
return <div>{children}</div>;
}
});
```
이 예제에서, 우리는 스타일을 주기 위해 수동으로 적절하게 `Button``Messages` 컴포넌트에 `color` 프로퍼티를 엮어서 전달했습니다. 테마는 서브트리가 정보 조각의 일부(여기선 color)에 접근하기 원하는 좋은 예제입니다. 컨텍스트를 사용하면 우리는 이를 자동으로 트리로 전달할 수 있습니다:
```javascript{2-4,7,18,25-30,33}
var Button = React.createClass({
contextTypes: {
color: React.PropTypes.string
},
render: function() {
return (
<button style={{'{{'}}background: this.context.color}}>
{this.props.children}
</button>
);
}
});
var Message = React.createClass({
render: function() {
return (
<div>
{this.props.text} <Button>Delete</Button>
</div>
);
}
});
var MessageList = React.createClass({
childContextTypes: {
color: React.PropTypes.string
},
getChildContext: function() {
return {color: "purple"};
},
render: function() {
var children = this.props.messages.map(function(message) {
return <Message text={message.text} />;
});
return <div>{children}</div>;
}
});
```
`childContextTypes`와 `getChildContext`를 `MessageList`(context provider)에 추가함으로써, React는 정보를 자동으로 아래로 전달하며 서브트리내의 어떤 컴포넌트든 (여기선 `Button`) `contextTypes`를 정의함으로써 이에 접근할 수 있습니다.
`contextTypes`가 정의되지 않은 경우, `this.context`는 빈 오브젝트가 됩니다.
## 부모-자식 커플링
컨텍스트는 다음과 같은 API를 구성할 수 있게 해줍니다:
```javascript
<Menu>
<MenuItem>가지</MenuItem>
<MenuItem>땅콩호박</MenuItem>
<MenuItem>클레멘타인</MenuItem>
</Menu>
```
`Menu` 컴포넌트에서 관련 정보를 전달함으로써 각각의 `MenuItem`가 부모인 `Menu` 컴포넌트와 통신할 수 있습니다.
**이 API를 이용해 컴포넌트를 구성하기 전에, 깔끔한 대안이 있는지 먼저 고려해 보세요.** 다음과 같이 간단히 아이템을 배열로 넘겨 보겠습니다:
```javascript
<Menu items={['가지', '땅콩호박', '클레멘타인']} />
```
원한다면 전체 React 컴포넌트를 프로퍼티로 전달할 수도 있습니다.
## Referencing context in lifecycle methods
If `contextTypes` is defined within a component, the following lifecycle methods will receive an additional parameter, the `context` object:
```javascript
void componentWillReceiveProps(
object nextProps, object nextContext
)
boolean shouldComponentUpdate(
object nextProps, object nextState, object nextContext
)
void componentWillUpdate(
object nextProps, object nextState, object nextContext
)
void componentDidUpdate(
object prevProps, object prevState, object prevContext
)
```
## Referencing context in stateless functional components
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.
```javascript
function Button(props, context) {
return (
<button style={{'{{'}}background: context.color}}>
{props.children}
</button>
);
}
Button.contextTypes = {color: React.PropTypes.string};
```
## 컨텍스트를 사용하지 말아야 하는 경우
대부분의 경우, 깔끔한 코드를 위해 전역 변수를 피하는 것과 마찬가지로 컨텍스트의 사용을 피해야 합니다. 특히 "타이핑을 줄이거나" 명시적인 프로퍼티 전달 대신 이를 사용하려는 경우 다시 한번 생각해 보세요.
컨텍스트의 가장 적절한 사용 사례는 로그인한 유저, 언어 설정, 테마 정보 등을 암시적으로 전달하는 것입니다. 컨텍스트를 사용함으로써 이런 정보들을 전역으로 다루는 대신 단일 React 서브트리 내에서 다룰 수 있습니다.
모델 데이터를 컴포넌트로 전달하는데 컨텍스트를 사용하지 마세요. 트리를 통해 명시적으로 데이터를 엮어 전달하는 것이 훨씬 이해하기 쉽습니다. 컨텍스트는 렌더되는 위치에 따라 다르게 작동하기 때문에 컴포넌트를 더욱 연결되고(coupled) 재사용성이 떨어지게 만듭니다.
## 알려진 한계점
컴포넌트에 의해 제공되는 컨텍스트의 값이 변경될 때, 중간 부모가 `shouldComponentUpdate`에서`false`을 반환한다면 그 값을 사용하는 자손은 업데이트되지 않습니다. 자세한 내용은 [#2517](https://github.com/facebook/react/issues/2517) 이슈를 확인하세요.

173
docs/docs/12-context.md Normal file
View File

@@ -0,0 +1,173 @@
---
id: context
title: Context
permalink: context.html
prev: advanced-performance.html
---
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.
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.
> Note:
>
> Context is an advanced and experimental feature. The API is likely to change in future releases.
>
> 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.
>
> **If you have to use context, use it sparingly.**
>
> 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.
## Passing info automatically through a tree
Suppose you have a structure like:
```javascript
var Button = React.createClass({
render: function() {
return (
<button style={{'{{'}}background: this.props.color}}>
{this.props.children}
</button>
);
}
});
var Message = React.createClass({
render: function() {
return (
<div>
{this.props.text} <Button color={this.props.color}>Delete</Button>
</div>
);
}
});
var MessageList = React.createClass({
render: function() {
var color = "purple";
var children = this.props.messages.map(function(message) {
return <Message text={message.text} color={color} />;
});
return <div>{children}</div>;
}
});
```
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:
```javascript{2-4,7,18,25-30,33}
var Button = React.createClass({
contextTypes: {
color: React.PropTypes.string
},
render: function() {
return (
<button style={{'{{'}}background: this.context.color}}>
{this.props.children}
</button>
);
}
});
var Message = React.createClass({
render: function() {
return (
<div>
{this.props.text} <Button>Delete</Button>
</div>
);
}
});
var MessageList = React.createClass({
childContextTypes: {
color: React.PropTypes.string
},
getChildContext: function() {
return {color: "purple"};
},
render: function() {
var children = this.props.messages.map(function(message) {
return <Message text={message.text} />;
});
return <div>{children}</div>;
}
});
```
By adding `childContextTypes` and `getChildContext` to `MessageList` (the context provider), React passes the information down automatically and any component in the subtree (in this case, `Button`) can access it by defining `contextTypes`.
If `contextTypes` is not defined, then `this.context` will be an empty object.
## Parent-child coupling
Context can also let you build an API such as:
```javascript
<Menu>
<MenuItem>aubergine</MenuItem>
<MenuItem>butternut squash</MenuItem>
<MenuItem>clementine</MenuItem>
</Menu>
```
By passing down the relevant info in the `Menu` component, each `MenuItem` can communicate back to the containing `Menu` component.
**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:
```javascript
<Menu items={['aubergine', 'butternut squash', 'clementine']} />
```
Recall that you can also pass entire React components in props if you'd like to.
## Referencing context in lifecycle methods
If `contextTypes` is defined within a component, the following lifecycle methods will receive an additional parameter, the `context` object:
```javascript
void componentWillReceiveProps(
object nextProps, object nextContext
)
boolean shouldComponentUpdate(
object nextProps, object nextState, object nextContext
)
void componentWillUpdate(
object nextProps, object nextState, object nextContext
)
void componentDidUpdate(
object prevProps, object prevState, object prevContext
)
```
## Referencing context in stateless functional components
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.
```javascript
function Button(props, context) {
return (
<button style={{'{{'}}background: context.color}}>
{props.children}
</button>
);
}
Button.contextTypes = {color: React.PropTypes.string};
```
## When not to use context
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.
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.
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.
## Known limitations
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.

View File

@@ -17,3 +17,13 @@ January 28 & 29
July 2 & 3
[Website](http://www.react-europe.org/) - [Schedule](http://www.react-europe.org/#schedule)
### Reactive 2015
November 2-4
[Website](https://reactive2015.com/) - [Schedule](https://reactive2015.com/schedule_speakers.html#schedule)
### ReactEurope 2016
June 2 & 3
[Website](http://www.react-europe.org/) - [Schedule](http://www.react-europe.org/#schedule)

View File

@@ -13,13 +13,39 @@ React를 시작하는 가장 빠른 방법은 다음의 Hello World JSFiddle 예
* **[React JSFiddle](https://jsfiddle.net/reactjs/69z2wepo/)**
* [React JSFiddle without JSX](https://jsfiddle.net/reactjs/5vjqabv3/)
## 초심자용 키트
## npm으로 React 사용하기
초심자용 키트를 내려받아 시작합니다.
[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 패키지를 사용하세요.
```js
// main.js
var React = require('react');
var ReactDOM = require('react-dom');
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
```
browserify를 설치한 후에 React DOM을 설치하고 bundle을 빌드합니다.
```sh
$ npm install --save react react-dom babelify babel-preset-react
$ browserify -t [ babelify --presets [ react ] ] main.js -o bundle.js
```
> 주의:
>
> ES2015를 사용하고 있다면, `babel-preset-es2015` 패키지도 설치할 필요가 있습니다.
## npm 없이 Quick Start 하기
만약 당신이 npm을 사용할 준비가 아직 안되었다면, 미리빌드된 React와 React DOM 파일이 포함된 초심자용 키트를 다운로드 받을 수 있습니다.
<div class="buttons-unit downloads">
<a href="/react/downloads/react-{{site.react_version}}.zip" class="button">
초심자용 키트 내려받기 {{site.react_version}}
초심자용 키트 내려받기 {{site.react_version}}
</a>
</div>
@@ -32,6 +58,7 @@ React를 시작하는 가장 빠른 방법은 다음의 Hello World JSFiddle 예
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="build/react.js"></script>
<script src="build/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
</head>
<body>
@@ -46,7 +73,7 @@ React를 시작하는 가장 빠른 방법은 다음의 Hello World JSFiddle 예
</html>
```
JavaScript 안에 보이는 XML 구문은 JSX라고 합니다; 더 자세한 내용은 [JSX syntax](/react/docs/jsx-in-depth-ko-KR.html)을 확인하세요. 일반적인 JavaScript로 번역하기 위해 `<script type="text/jsx">`를 사용하고 `JSXTransformer.js` 포함하는 것으로 실제로 브라우저에서 변환작업을 수행합니다.
JavaScript 안에 보이는 XML 구문은 JSX라고 합니다; 더 자세한 내용은 [JSX syntax](/react/docs/jsx-in-depth-ko-KR.html)을 확인하세요. 일반적인 JavaScript로 번역하기 위해 `<script type="text/babel">`를 사용하고 Babel을 포함하는 것으로 실제로 브라우저에서 변환작업을 수행합니다.
### 파일의 분리
@@ -69,19 +96,24 @@ ReactDOM.render(
### 오프라인 변환
먼저 커맨드라인 도구를 설치합니다. ([npm](https://www.npmjs.com/) 필요):
먼저 [Babel](http://babeljs.io/) 커맨드라인 도구를 설치합니다. ([npm](https://www.npmjs.com/) 필요):
```
npm install -g react-tools
npm install --global babel-cli
npm install babel-preset-react
```
그다음, `src/helloworld.js` 파일을 일반 JavaScript 파일로 변환합니다:
```
jsx --watch src/ build/
babel --presets react src --watch --out-dir build
```
수정할 때마다 `build/helloworld.js` 파일이 자동생성됩니다.
> 주의:
>
> ES2015를 사용하고 있다면, `babel-preset-es2015` 패키지도 설치할 필요가 있습니다.
수정할 때마다 `build/helloworld.js` 파일이 자동생성됩니다. 더 자세한 사용법은 [Babel CLI 문서](http://babeljs.io/docs/usage/cli/)를 읽어보세요.
```javascript{2}
ReactDOM.render(
@@ -92,14 +124,15 @@ ReactDOM.render(
아래의 내용대로 HTML 파일을 업데이트합니다:
```html{7,11}
```html{8,12}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="build/react.js"></script>
<!-- Babel는 이제 불필요합니다! -->
<script src="build/react-dom.js"></script>
<!-- Babel은 이제 불필요합니다! -->
</head>
<body>
<div id="example"></div>
@@ -108,10 +141,6 @@ ReactDOM.render(
</html>
```
## CommonJS를 원하시나요?
만약 React를 [browserify](http://browserify.org/), [webpack](https://webpack.github.io/)이나 기타 CommonJS와 호환되는 모듈시스템과 함께 사용하고 싶다면, [`react` npm 패키지](https://www.npmjs.com/package/react)를 사용하세요. 그 외에도 `jsx` 빌드툴은 아주 쉽게 CommonJS 외에도 대부분의 패키징 시스템에 통합될 수 있습니다.
## 다음 단계로
더 알아보려면 [튜토리얼](/react/docs/tutorial-ko-KR.html)과 초심자용 키트의 `examples` 디렉터리에서 다른 예제들을 확인해 보세요.

View File

@@ -30,10 +30,15 @@ ReactDOM.render(
To install React DOM and build your bundle after installing browserify:
```sh
$ npm install --save react react-dom
$ browserify -t babelify main.js -o bundle.js
$ npm install --save react react-dom babelify babel-preset-react
$ browserify -t [ babelify --presets [ react ] ] main.js -o bundle.js
```
> Note:
>
> If you are using ES2015, you will want to also use the `babel-preset-es2015` package.
## Quick Start Without npm
If you're not ready to use npm yet, you can download the starter kit which includes prebuilt copies of React and React DOM.
@@ -94,16 +99,20 @@ Note that some browsers (Chrome, e.g.) will fail to load the file unless it's se
First install the [Babel](http://babeljs.io/) command-line tools (requires [npm](https://www.npmjs.com/)):
```
npm install --global babel
npm install --global babel-cli
npm install babel-preset-react
```
Then, translate your `src/helloworld.js` file to plain JavaScript:
```
babel src --watch --out-dir build
babel --presets react src --watch --out-dir build
```
> Note:
>
> If you are using ES2015, you will want to also use the `babel-preset-es2015` package.
The file `build/helloworld.js` is autogenerated whenever you make a change. Read the [Babel CLI documentation](http://babeljs.io/docs/usage/cli/) for more advanced usage.
```javascript{2}

View File

@@ -13,9 +13,35 @@ redirect_from: "docs/index-zh-CN.html"
* **[React JSFiddle](https://jsfiddle.net/reactjs/69z2wepo/)**
* [React JSFiddle without JSX](https://jsfiddle.net/reactjs/5vjqabv3/)
## 入门教程包 (Starter Kit)
开始先下载入门教程包。
## 通过 npm 使用 React
我们建议在 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 包.
```js
// main.js
var React = require('react');
var ReactDOM = require('react-dom');
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
```
在安装 browserify 之后安装 React DOM 和构建你的应用包。
```sh
$ npm install --save react react-dom
$ browserify -t babelify main.js -o bundle.js
```
## 不使用 npm 快速开始
If you're not ready to use npm yet, you can download the starter kit which includes prebuilt copies of React and React DOM.
如果你没有做好使用 npm 的准备,你可以下载包含了 React 和 ReactDOM 预生成包的入门教程包。
<div class="buttons-unit downloads">
<a href="/react/downloads/react-{{site.react_version}}.zip" class="button">
@@ -23,7 +49,7 @@ redirect_from: "docs/index-zh-CN.html"
</a>
</div>
在入门教程包的根目录,创建一个含有下代码的 `helloworld.html`
在入门教程包的根目录,创建一个含有下代码的 `helloworld.html`
```html
<!DOCTYPE html>
@@ -32,6 +58,7 @@ redirect_from: "docs/index-zh-CN.html"
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="build/react.js"></script>
<script src="build/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
</head>
<body>
@@ -46,7 +73,7 @@ redirect_from: "docs/index-zh-CN.html"
</html>
```
在 JavaScript 代码里写着 XML 格式的代码称为 JSX可以去 [JSX 语法](/react/docs/jsx-in-depth.html) 里学习更多 JSX 相关的知识。为了把 JSX 转成标准的 JavaScript我们用 `<script type="text/jsx">` 标签包裹着含有 JSX 的代码,然后引入 `JSXTransformer.js` 库来实现在浏览器里的代码转换。
在 JavaScript 代码里写着 XML 格式的代码称为 JSX可以去 [JSX 语法](/react/docs/jsx-in-depth.html) 里学习更多 JSX 相关的知识。为了把 JSX 转成标准的 JavaScript我们用 `<script type="text/babel">` 标签,并引入 Babel 来完成在浏览器里的代码转换。
### 分离文件
@@ -65,22 +92,25 @@ ReactDOM.render(
<script type="text/babel" src="src/helloworld.js"></script>
```
注意一些浏览器(比如 Chrome )会在使用 HTTP 以外的协议加载文件时失败。
### 离线转换
先安装命令行工具(依赖 [npm](https://www.npmjs.com/)
先安装[Babel](http://babeljs.io/)命令行工具(依赖 [npm](https://www.npmjs.com/)
```
npm install -g react-tools
npm install --global babel
```
然后把你的 `src/helloworld.js` 文件转成标准的 JavaScript:
```
jsx --watch src/ build/
babel src --watch --out-dir build
```
只要你修改了, `build/helloworld.js` 文件会自动生成
`build/helloworld.js` 会在你对文件进行修改时自动生成。 阅读 [Babel CLI 文档](http://babeljs.io/docs/usage/cli/) 了解高级用法
```javascript{2}
ReactDOM.render(
@@ -108,10 +138,6 @@ ReactDOM.render(
```
## 想用 CommonJS
如果你想在 [browserify](http://browserify.org/)[webpack](https://webpack.github.io/) 或者或其它兼容CommonJS的模块系统里使用 React只要使用 [`react` npm 包](https://www.npmjs.com/package/react) 即可。而且,`jsx` 转换工具可以很轻松的地集成到大部分打包系统里(不仅仅是 CommonJS
## 下一步

View File

@@ -82,7 +82,7 @@ ReactComponent render(
> 注意:
> `React.render()` は渡されたコンテナーードの内容を制御します。内部に存在するDOM要素は最初に呼ばれた際に置き換えられます。その後に呼ばれた場合は、ReactのDOMの差分アルゴリズムを使用して、効率的に更新されます。
>
>
> `React.render()` はコンテナーードの変更は行いませんコンテナの子要素のみ変更を行います。今後、存在する子要素を上書きすることなく、存在するDOMードにコンポーネントを挿入することが可能になるでしょう。
### React.unmountComponentAtNode

View File

@@ -68,6 +68,73 @@ factoryFunction createFactory(
주어진 타입의 ReactElement를 만들어주는 함수를 리턴합니다. `React.createElement`와 마찬가지로 `type` 인자는 HTML 태그명 문자열 (예: 'div', 'span' 등) 또는 `ReactClass`입니다.
### React.isValidElement
```javascript
boolean isValidElement(* object)
```
주어진 객체가 ReactElement인지 확인합니다.
### React.DOM
`React.DOM`은 DOM 컴포넌트에 대해 `React.createElement`의 편의 래퍼(wrapper)를 제공합니다. JSX를 사용하지 않는 경우에만 사용하십시오. 예를 들어, `React.DOM.div(null, 'Hello World!')`와 같이 사용할 수 있습니다.
### React.PropTypes
`React.PropTypes`는 컴포넌트에 넘어오는 props가 올바른지 검사할 수 있는 컴포넌트의 `propTypes` 객체에 들어가는 타입을 가집니다. `propTypes`에 대한 자세한 정보는 [재사용 가능한 컴포넌트](/react/docs/reusable-components-ko-KR.html)를 참고하세요.
### React.Children
`React.Children`은 불투명한 자료 구조인 `this.props.children`를 다룰 수 있는 유틸리티를 제공합니다.
#### React.Children.map
```javascript
array React.Children.map(object children, function fn [, object thisArg])
```
`children`의 바로 밑에 있는 모든 자식에 `fn`을 호출합니다. 이 때 `this``thisArg`로 설정됩니다. `children`이 중첩된 객체나 배열일 경우 그 안의 값을 순회합니다. 따라서 `fn`에 컨테이너 객체가 넘어가는 일은 일어나지 않습니다. `children``null`이거나 `undefined`면 배열 대신 `null` 또는 `undefined`를 리턴합니다.
#### React.Children.forEach
```javascript
React.Children.forEach(object children, function fn [, object thisArg])
```
`React.Children.map()`과 비슷하지만 배열을 리턴하지 않습니다.
#### React.Children.count
```javascript
number React.Children.count(object children)
```
`children`에 들어있는 컴포넌트의 총 갯수를 리턴합니다. 이 갯수는 `map`이나 `forEach`에 넘긴 콜백이 호출되는 횟수와 동일합니다.
#### React.Children.only
```javascript
object React.Children.only(object children)
```
`children`에 단 하나의 자식이 있을 때 그 자식을 리턴합니다. 그 밖의 경우에는 예외를 발생시킵니다.
#### React.Children.toArray
```javascript
array React.Children.toArray(object children)
```
불투명한 자료구조인 `children`를 개별 자식마다 키를 할당해 평면 배열로 리턴합니다. 이는 render 메소드 내에서 자식의 컬렉션을 조작할 때, 특히 `this.props.children`을 넘기기 전에 재정렬하거나 재단할 때 유용합니다.
## ReactDOM
`react-dom` 패키지는 앱의 최상위 레벨에서 사용될 DOM 고유의 메소드를 제공하며, 원한다면 리액트 외부모델을 위한 출구로 사용될 수 있습니다. 대부분의 컴포넌트는 이 모듈을 사용할 필요가 없습니다.
### ReactDOM.render
```javascript
@@ -78,7 +145,7 @@ ReactComponent render(
)
```
주어진 ReactElement를 `container` 인자에 넘어온 DOM 안에 렌더링하고 컴포넌트의 레퍼런스를 리턴합니다.
주어진 ReactElement를 `container` 인자에 넘어온 DOM 안에 렌더링하고 컴포넌트의 [레퍼런스](/react/docs/more-about-refs-ko-KR.html)를 컴포넌트에 리턴합니다. [상태가 없는 컴포넌트](/react/docs/reusable-components-ko-KR.html#stateless-functions)에서는 `null`을 리턴합니다.
어떤 ReactElement가 이미 `container`에 렌더링 된 적이 있다면, 그것을 업데이트한 뒤 React 컴포넌트의 최신 상태를 반영하기 위해 꼭 필요한 만큼만 DOM을 변경합니다.
@@ -100,7 +167,26 @@ boolean unmountComponentAtNode(DOMElement container)
DOM에 마운트된 React 컴포넌트를 제거하고 이벤트 핸들러 및 state를 정리합니다. 컨테이너에 마운트된 컴포넌트가 없는 경우에는 호출해도 아무 동작을 하지 않습니다. 컴포넌트가 마운트 해제된 경우 `true`를, 마운트 해제할 컴포넌트가 없으면 `false`를 리턴합니다.
### ReactDOM.renderToString
### ReactDOM.findDOMNode
```javascript
DOMElement findDOMNode(ReactComponent component)
```
이 컴포넌트가 DOM에 마운트된 경우 해당하는 네이티브 브라우저 DOM 엘리먼트를 리턴합니다. 이 메소드는 폼 필드의 값이나 DOM의 크기/위치 등 DOM에서 정보를 읽을 때 유용합니다. **대부분의 경우, DOM 노드에 ref를 쓸 수 있으며 `findDOMNode`를 사욯할 필요는 없습니다.** `render``null`이나 `false`를 리턴할 때 `findDOMNode()``null`을 리턴합니다.
> 주의:
>
> `findDOMNode()`는 기본 DOM 노드에 접근하기 위한 출구입니다. 컴포넌트 추상화를 파괴하기 때문에 대부분의 경우 이것의 사용은 권장되지 않습니다.
>
> `findDOMNode()`는 마운트된 컴포넌트에서만 작동합니다. 이는 컴포넌트가 DOM에 위치해야 함을 뜻합니다. 만약 아직 생성되기전의 컴포넌트에서 `render()`에서 `findDOMNode()`를 호출하는 등 컴포넌트가 마운트 되기 이전에 이를 호출한다면, 예외가 던져질 것입니다.
>
> `findDOMNode()`는 상태가없는 컴포넌트에서 쓸 수 없습니다.
## ReactDOMServer
`react-dom/server` 패키지는 서버단에서 컴포넌트를 렌더할 수 있도록 해 줍니다.
### ReactDOMServer.renderToString
```javascript
string renderToString(ReactElement element)
@@ -111,73 +197,10 @@ string renderToString(ReactElement element)
또한 이 메소드로 서버에서 렌더링한 마크업을 포함한 노드에 `ReactDOM.render()`를 호출하면, React는 마크업을 보존하고 이벤트 핸들러만 붙이므로 최초 로딩을 매우 빠르게 느껴지게 할 수 있습니다.
### ReactDOM.renderToStaticMarkup
### ReactDOMServer.renderToStaticMarkup
```javascript
string renderToStaticMarkup(ReactElement element)
```
`renderToString`와 비슷하지만 `data-react-id`처럼 React에서 내부적으로 사용하는 추가적인 DOM 어트리뷰트를 만들지 않습니다. 추가적인 어트리뷰트를 제거하면 생성되는 마크업의 용량을 줄일 수 있기 때문에 React를 단순한 정적 페이지 생성기로 사용할 때 유용합니다.
### ReactDOM.isValidElement
```javascript
boolean isValidElement(* object)
```
주어진 객체가 ReactElement인지 확인합니다.
### ReactDOM.findDOMNode
```javascript
DOMElement findDOMNode(ReactComponent component)
```
이 컴포넌트가 DOM에 마운트된 경우 해당하는 네이티브 브라우저 DOM 엘리먼트를 리턴합니다. 이 메소드는 폼 필드의 값이나 DOM의 크기/위치 등 DOM에서 정보를 읽을 때 유용합니다. `render``null`이나 `false`를 리턴할 때 `findDOMNode()``null`을 리턴합니다.
### React.DOM
`React.DOM`은 DOM 컴포넌트에 대해 `React.createElement`의 편의 래퍼(wrapper)를 제공합니다. JSX를 사용하지 않는 경우에만 사용하십시오. 예를 들어, `React.DOM.div(null, 'Hello World!')`와 같이 사용할 수 있습니다.
### React.PropTypes
`React.PropTypes`는 컴포넌트에 넘어오는 props가 올바른지 검사할 수 있는 컴포넌트의 `propTypes` 객체에 들어가는 타입을 가집니다. `propTypes`에 대한 자세한 정보는 [재사용 가능한 컴포넌트](/react/docs/reusable-components-ko-KR.html)를 참고하세요.
### React.Children
`React.Children`은 불투명한 자료 구조인 `this.props.children`를 다룰 수 있는 유틸리티를 제공합니다.
#### React.Children.map
```javascript
object React.Children.map(object children, function fn [, object thisArg])
```
`children`의 바로 밑에 있는 모든 자식에 `fn`을 호출합니다. 이 때 `this``thisArg`로 설정됩니다. `children`이 중첩된 객체나 배열일 경우 그 안의 값을 순회합니다. 따라서 `fn`에 컨테이너 객체가 넘어가는 일은 일어나지 않습니다. `children``null`이거나 `undefined`면 빈 객체 대신 `null` 또는 `undefined`를 리턴합니다.
#### React.Children.forEach
```javascript
React.Children.forEach(object children, function fn [, object thisArg])
```
`React.Children.map()`과 비슷하지만 객체를 리턴하지 않습니다.
#### React.Children.count
```javascript
number React.Children.count(object children)
```
`children`에 들어있는 컴포넌트의 총 갯수를 리턴합니다. 이 갯수는 `map`이나 `forEach`에 넘긴 콜백이 호출되는 횟수와 동일합니다.
#### React.Children.only
```javascript
object React.Children.only(object children)
```
`children`에 단 하나의 자식이 있을 때 그 자식을 리턴합니다. 그 밖의 경우에는 예외를 발생시킵니다.

View File

@@ -97,10 +97,10 @@ Verifies the object is a ReactElement.
#### React.Children.map
```javascript
object React.Children.map(object children, function fn [, object thisArg])
array React.Children.map(object children, function fn [, object thisArg])
```
Invoke `fn` on every immediate child contained within `children` with `this` set to `thisArg`. If `children` is a nested object 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 empty object.
Invoke `fn` on every immediate child contained within `children` with `this` set to `thisArg`. If `children` is a nested object 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.
#### React.Children.forEach
@@ -108,7 +108,7 @@ Invoke `fn` on every immediate child contained within `children` with `this` set
React.Children.forEach(object children, function fn [, object thisArg])
```
Like `React.Children.map()` but does not return an object.
Like `React.Children.map()` but does not return an array.
#### React.Children.count
@@ -126,6 +126,14 @@ object React.Children.only(object children)
Return the only child in `children`. Throws otherwise.
#### React.Children.toArray
```javascript
array React.Children.toArray(object children)
```
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.
## ReactDOM
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.

View File

@@ -0,0 +1,191 @@
---
id: top-level-api-zh-CN
title: Top-Level API
permalink: top-level-api-zh-CN.html
next: component-api-zh-CN.html
redirect_from: "/docs/reference-zh-CN.html"
---
## React
`React` 是 React 库的入口点。如果你使用预编译包中的一个,则 `React` 为全局变量;如果你使用 CommonJS 模块,你可以 `require()` 它。
### React.Component
```javascript
class Component
```
当使用ES6 类定义时React.Component是 React 组件的基类。如何在React中使用 ES6 class 请参见 [可重用组件](/react/docs/reusable-components-zh-CN.html#es6-classes)。基类实际提供了哪些方法 请参见 [组件 API](/react/docs/component-api-zh-CN.html).
### React.createClass
```javascript
ReactClass createClass(object specification)
```
给定一份规格specification创建一个组件类。组件通常要实现一个 `render()` 方法,它返回 **单个的** 子级。该子级可能包含任意深度的子级结构。组件与标准原型类的不同之处在于,你不需要对它们调用 new。 它们是为你在后台构造实例(通过 new的便利的包装器。
更多关于规格对象specification object的信息请见 [组件规格和生命周期](/react/docs/component-specs-zh-CN.html) 。
### React.createElement
```javascript
ReactElement createElement(
string/ReactClass type,
[object props],
[children ...]
)
```
创建并返回一个新的给定类型的 `ReactElement`。type 参数既可以是一个 html 标签名字符串(例如. “div”“span”等等也可以是一个 `ReactClass` (用 `React.createClass` 创建的)。
### React.cloneElement
```
ReactElement cloneElement(
ReactElement element,
[object props],
[children ...]
)
```
使用 `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) 。
### React.createFactory
```javascript
factoryFunction createFactory(
string/ReactClass type
)
```
返回一个生成给定类型的 ReactElements 的函数。如同 `React.createElement`type 参数既可以是一个 html 标签名字符串(例如. “div”“span”等等也可以是一个 `ReactClass`
### React.render
```javascript
ReactComponent render(
ReactElement element,
DOMElement container,
[function callback]
)
```
渲染一个 ReactElement 到 DOM 里提供的 `容器container`中,并返回一个对组件的引用。
如果 ReactElement 之前被渲染到了 `container` 中,这将对它执行一次更新,并仅变动需要变动的 DOM 来反映最新的 React 组件。
如果提供了可选的回调函数,则该函数将会在组件渲染或者更新之后被执行。
> 注意:
>
> `React.render()` 控制你传入的 container 节点的内容。
> 当初次调用时,任何现存于内的 DOM 元素将被替换。
> 其后的调用使用 React的 diffing 算法来有效率的更新。
>
> `React.render()` 不会修改 container 节点(只修改 container 的子级)。
> 将来,也许能够直接插入一个组件到已经存在的 DOM 节点而不覆盖
> 现有的子级。
### React.unmountComponentAtNode
```javascript
boolean unmountComponentAtNode(DOMElement container)
```
从 DOM 中移除已经挂载的 React 组件,并清除它的事件处理器和 state。如果在 container 中没有组件被挂载,调用此函数将什么都不做。如果组件被卸载返回 `true`,如果没有组件被卸载返回 `false`
### React.renderToString
```javascript
string renderToString(ReactElement element)
```
把 ReactElement 渲染为它原始的 HTML 。这应该仅在服务器端使用。React 将会返回一个 HTML 字符串。你可以用这种方法在服务器端生成 HTML然后在初始请求下传这些标记以获得更快的页面加载速度及允许搜索引擎抓取页面便于 SEO
如果在一个在已经有了这种服务器预渲染标记的节点上面调用 `React.render()`React 将会维护该节点,仅绑定事件处理器,让你有一个非常高效的初次加载体验。
### React.renderToStaticMarkup
```javascript
string renderToStaticMarkup(ReactElement element)
```
类似于 `renderToString` ,除了不创建额外的 DOM 属性,比如 `data-react-id`,这仅在 React 内部使用的属性。如果你想用 React 做一个简单的静态页面生成器,这是很有用的,因为去除额外的属性能够节省很多字节。
### React.isValidElement
```javascript
boolean isValidElement(* object)
```
验证对象是否是一个 ReactElement。
### React.findDOMNode
```javascript
DOMElement findDOMNode(ReactComponent component)
```
如果这个组件已经被挂载到了 DOM它返回相应的浏览器原生的 DOM 元素。这个方法对于读取 DOM 的值很有用,比如表单域的值和执行 DOM 的测量。如果 `render` 返回 `null` 或者 `false` `findDOMNode` 返回 `null`.
### React.DOM
`React.DOM``React.createElement` 为 DOM 组件提供了便利的包装器。该方式应该只在不使用 JSX 的时使用。例如,`React.DOM.div(null, 'Hello World!')`
### React.PropTypes
`React.PropTypes` 包含了能与 组件的`propTypes` 对象一起使用的类型,用以验证传入你的组件的 props。更多有关 `propTypes` 的信息,请见 [可重用组件](/react/docs/reusable-components-zh-CN.html)。
### React.Children
`React.Children` 为处理 `this.props.children` 这个不透明的数据结构提供了工具。
#### React.Children.map
```javascript
object React.Children.map(object children, function fn [, object thisArg])
```
在每一个包含在 `children` 中的直接子级上调用 `fn` `fn`中的 `this` 设置为 `thisArg`。如果 `children` 是一个嵌套的对象或者数组,它将被遍历:不会传入容器对象到 `fn` 中。如果 children 是 `null` 或者 `undefined`,则返回 `null` 或者 `undefined` 而不是一个空对象。
#### React.Children.forEach
```javascript
React.Children.forEach(object children, function fn [, object thisArg])
```
类似 `React.Children.map()`,但是不返回对象。
#### React.Children.count
```javascript
number React.Children.count(object children)
```
返回 `children` 中的组件总数,相等于传递给 `map` 或者 `forEach` 的回调函数应被调用次数。
#### React.Children.only
```javascript
object React.Children.only(object children)
```
返回 `children` 中仅有的子级。否则抛出异常。

View File

@@ -14,14 +14,17 @@ React 컴포넌트의 인스턴스는 React가 렌더링 시에 내부적으로
### setState
```javascript
void setState(function|object nextState[, function callback])
void setState(
function|object nextState,
[function callback]
)
```
`nextState`를 현재 state에 합니다. 이벤트 핸들러와 서버 요청 콜백에서 UI 업데이트를 발생시키기 위해 이 메소드를 주로 사용합니다.
nextState를 현재 state에 얕게(shallow) 병합합니다. 이벤트 핸들러와 서버 요청 콜백에서 UI 업데이트를 발생시키기 위해 이 메소드를 주로 사용합니다.
첫번째 인자는 업데이트를 위한 키를 0개 이상 가진 객체이거나 업데이트를 위한 키들을 포함한 객체를 반환하는 함수(의 state나 props)일 수 있습니다.
객체를 사용하는 간단한 예제입니다...
객체를 사용하는 간단한 예제입니다:
```javascript
setState({mykey: '새로운 값'});
@@ -51,7 +54,10 @@ setState(function(previousState, currentProps) {
### replaceState
```javascript
void replaceState(object nextState[, function callback])
void replaceState(
object nextState,
[function callback]
)
```
`setState()`와 비슷하지만 기존에 존재하는 state 중 nextState에 없는 키는 모두 삭제됩니다.
@@ -64,7 +70,9 @@ void replaceState(object nextState[, function callback])
### forceUpdate
```javascript
void forceUpdate([function callback])
void forceUpdate(
[function callback]
)
```
기본적으로, 컴포넌트의 state나 props가 변경되면, 컴포넌트는 다시 렌더됩니다. 하지만 이런 변경이 묵시적이거나(예를들어 객체의 변경 없이 깊이 있는 데이터만 변경된 경우) `render()` 함수가 다른 값에 의존하는 경우, `forceUpdate()`를 호출해 React에게 `render()`를 다시 실행할 필요가 있다고 알릴 수 있습니다.
@@ -95,7 +103,7 @@ DOMElement getDOMNode()
boolean isMounted()
```
`isMounted()`는 컴포넌트가 DOM에 렌더링되었으면 true를, 아니면 false를 리턴합니다. 비동기적으로 `setState()``forceUpdate()`를 호출할 때 이 메소드를 사용하여 오류를 방지할 수 있습니다.
`isMounted()`는 컴포넌트가 DOM에 렌더링되었으면 `true`를, 아니면 `false`를 리턴합니다. 비동기적으로 `setState()``forceUpdate()`를 호출할 때 이 메소드를 사용하여 오류를 방지할 수 있습니다.
> 주의:
>
@@ -105,7 +113,10 @@ boolean isMounted()
### setProps
```javascript
void setProps(object nextProps[, function callback])
void setProps(
object nextProps,
[function callback]
)
```
외부 JavaScript 애플리케이션과 연동하는 경우 `ReactDOM.render()`로 렌더링된 React 컴포넌트에 변경을 알리고 싶을 때가 있습니다.
@@ -124,7 +135,10 @@ void setProps(object nextProps[, function callback])
### replaceProps
```javascript
void replaceProps(object nextProps[, function callback])
void replaceProps(
object nextProps,
function callback]
)
```
`setProps()`와 비슷하지만 두 객체를 합치는 대신 이전에 존재하던 props를 삭제합니다.

View File

@@ -29,7 +29,7 @@ Here is the simple object usage:
setState({mykey: 'my new value'});
```
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:
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:
```javascript
setState(function(previousState, currentProps) {

View File

@@ -0,0 +1,146 @@
---
id: component-api-zh-CN
title: 组件 API
permalink: component-api-zh-CN.html
prev: top-level-api-zh-CN.html
next: component-specs-zh-CN.html
---
## React.Component
当渲染时React 组件的实例在 React 内部被创建。这些实例在随后的渲染中被重复使用,并可以在组件方法中通过 `this` 访问。唯一的在 React 之外获取 React 组件实例句柄的方法是保存 `React.render` 的返回值。在其它组件内,你可以使用 [refs](/react/docs/more-about-refs-zh-CN.html) 得到相同的结果。
### setState
```javascript
setState(
function|object nextState,
[function callback]
)
```
执行一个 nextState 到当前 state 的浅合并。这是你从事件处理器和服务器请求回调用来触发 UI 更新的主要手段。
第一个参数可以是一个对象包含0或者多个keys来更新或者一个state 和 props的函数它返回一个包含要更新的keys的对象。
这里是一个简单的运用:
```javascript
setState({mykey: 'my new value'});
```
也可以以 `function(state, props)` 传递一个函数。当你想要把一个在设置任何值之前参考前一次 state+props 的值的原子更新放在队列中 这会有很用。例如,假如我们想在 state 增加一个值。
```javascript
setState(function(previousState, currentProps) {
return {myInteger: previousState.myInteger + 1};
});
```
第二个(可选)的参数是一个将会在 `setState` 完成和组件被重绘后执行的回调函数。
> 注意:
>
> *绝对不要* 直接改变 `this.state`,因为之后调用 `setState()` 可能会替换掉你做的改变。把 `this.state` 当做是不可变的。
>
> `setState()` 不会立刻改变 `this.state`,而是创建一个即将处理的 state 转变。在调用该方法之后访问 `this.state` 可能会返回现有的值。
>
> 对 `setState` 的调用没有任何同步性的保证,并且调用可能会为了性能收益批量执行。
>
> `setState()` 将总是触发一次重绘,除非在 `shouldComponentUpdate()` 中实现了条件渲染逻辑。如果可变对象被使用了,但又不能在 `shouldComponentUpdate()` 中实现这种逻辑,仅在新 state 和之前的 state 存在差异的时候调用 `setState()` 可以避免不必要的重新渲染。
### replaceState
```javascript
replaceState(
object nextState,
[function callback]
)
```
类似于 `setState()`,但是删除任何 先前存在但不在 nextState 里的 state 键。
> 注意:
>
> 这个方法在从 `React.Component` 扩展的 ES6 `class` 组件里不可用。它也许会在未来的 React 版本中被完全移除。
### forceUpdate
```javascript
forceUpdate(
[function callback]
)
```
默认情况下,当你的组件的 state 或者 props 改变,你的组件将会重绘。然而,如果它们隐式的改变(例如:在对象深处的数据改变了但没有改变对象本身)或者如果你的 `render()` 方法依赖于其他的数据,你可以用调用 `forceUpdate()` 来告诉 React 它需要重新运行 `render()`
调用 `forceUpdate()` 将会导致 `render()` 跳过 `shouldComponentUpdate()` 在组件上被调用,这会为子级触发正常的生命周期方法。包括每个子级的 `shouldComponentUpdate()` 方法。如果标记改变了React 仍仅只更新 DOM。
通常你应该试着避免所有对 `forceUpdate()` 的使用并且在 `render()` 里只从 `this.props``this.state` 读取。这会使你的组件 "纯粹" 并且你的组件会更简单和高效。
### getDOMNode
```javascript
DOMElement getDOMNode()
```
如果这个组件已经被挂载到了 DOM它返回相应的浏览器原生的 DOM 元素。这个方法对于读取 DOM 的值很有用,比如表单域的值和执行 DOM 的测量。如果 `render` 返回 `null` 或者 `false` 的时候,`this.getDOMNode()` 返回 `null`
> Note:
>
> getDOMNode 被废弃了,已经被 [React.findDOMNode()] 替换(/react/docs/top-level-api-zh-CN.html#react.finddomnode).
>
> 这个方法在从 `React.Component` 扩展的 ES6 `class` 组件里不可用。它也许会在未来的 React 版本中被完全移除。
### isMounted
```javascript
bool isMounted()
```
如果组件渲染到了 DOM 中,`isMounted()` 返回 true否则返回 `false`。可以使用该方法来控制对 `setState()``forceUpdate()` 的异步调用。
> 注意:
>
> 这个方法在从 `React.Component` 扩展的 ES6 `class` 组件里不可用。它也许会在未来的 React 版本中被完全移除。
### setProps
```javascript
setProps(
object nextProps,
[function callback]
)
```
当和一个外部的 JavaScript 应用整合的时候,你也许会想用 `React.render()` 给 React 组件标示一个改变。
在根组件上调用 `setProps()` 会改变他的属性并触发一次重绘。另外,你可以提供一个可选的回调函数,一旦 `setProps` 完成并且组件被重绘它就执行。
> 注意:
>
> 如果可能,上述的在同一个节点上再次调用 `React.render()` 的方法是优先替代的。它往往使更新更容易理解。(两种方法并没有显著的性能区别。)
>
> 这个方法仅能在根组件上被调用。也就是说,它仅在直接传给 `React.render()` 的组件上可用,在它的子级上不可用。如果你倾向于在子组件上使用 `setProps()`,不要利用响应式更新,而是当子组件在 `render()` 中创建的时候传入新的 prop 到子组件中。
>
> 这个方法在从 `React.Component` 扩展的 ES6 `class` 组件里不可用。它也许会在未来的 React 版本中被完全移除。
### replaceProps
```javascript
replaceProps(
object nextProps,
[function callback]
)
```
类似于 `setProps()`,但是删除任何先前存在的 props而不是合并这两个对象。
> 注意:
>
> 这个方法在从 `React.Component` 扩展的 ES6 `class` 组件里不可用。它也许会在未来的 React 版本中被完全移除。

Some files were not shown because too many files have changed in this diff Show More