Compare commits

...

110 Commits

Author SHA1 Message Date
Paul O’Shannessy
66cee497e7 15.3.0 2016-07-29 11:26:23 -07:00
Paul O’Shannessy
7251f6a6e9 Update readme for 15.3.0 2016-07-29 11:25:55 -07:00
Paul O’Shannessy
f7837682b4 Changelog for 15.3.0 2016-07-29 11:25:39 -07:00
Paul O’Shannessy
41f21520d1 Merge branch '15-dev' into 15-stable 2016-07-29 11:14:25 -07:00
Paul O’Shannessy
e5efe5f568 Update version of react-test-renderer 2016-07-28 22:35:19 -07:00
Dustan Kasten
396ab3eba1 ReactTestRenderer package (#7362)
(cherry picked from commit 7e874f59f5)
2016-07-28 21:42:42 -07:00
Keyan Zhang
01ad9af590 fixed incorrect doc location (#7365)
(cherry picked from commit c9dc2ab0ec)
2016-07-28 11:41:22 -07:00
Jackson Huang
5d2f6c07c3 Create 02-displaying-data.zh-TW.md (#7284)
* Create 02-displaying-data.zh-TW.md

* Update 02-displaying-data.zh-TW.md

(cherry picked from commit fe5128fe8f)
2016-07-28 11:41:22 -07:00
Gert Hengeveld
6cab7064a0 Added ReactNL conference (#7342)
(cherry picked from commit 9d33fb0b76)
2016-07-28 11:41:21 -07:00
Amjad Masad
6f80ed8615 "transient dependencies" -> "transitive dependencies" (#7341)
I think that's what you meant -- although with npm dependencies are kind of transient :P
(cherry picked from commit d157827311)
2016-07-28 11:41:21 -07:00
scloudyy
88d49edda5 Update docs zh cn (#7254)
* update 03-interactivity-and-dynamic-uis.zh-CN

* update 04-multiple-components.zh-CN

* update 05-reusable-components.zh-CN

* updat 06-transferring-props.zh-CN

* update 07-forms.zh-CN

* update 08-working-with-the-browser.zh-CN

* update 08 and 08.1

* update 09-tooling-integration.zh-CN

* revise

* don't use ES6

(cherry picked from commit 5b06667efd)
2016-07-28 11:41:21 -07:00
Veljko Tornjanski
5f705664fa Wording change in doc (#7348)
(cherry picked from commit 0805921883)
2016-07-28 11:41:21 -07:00
Seyi
6fba1f1fad Blog post: Fixed typo in post (#7336)
(cherry picked from commit 1fc5f284c0)
2016-07-22 13:23:17 -07:00
Paul O’Shannessy
127af0ffc7 Host our own images for the blog, use https links (#7339)
(cherry picked from commit 7614c12ed7)
2016-07-22 13:23:17 -07:00
Steven Syrek
86f72d0830 Correct grammatical error (subject-verb agreement) (#7338)
"It is worth repeating: there is no configuration files or complicated folder structures." > "It is worth repeating: there are no configuration files or complicated folder structures."
(cherry picked from commit c0b7d81872)
2016-07-22 13:23:17 -07:00
Dan Abramov
9423829db2 Add blog post 2016-07-22 16:59:02 +01:00
Paul O’Shannessy
f8a698e9af 15.3.0-rc.3 2016-07-21 14:36:01 -07:00
Keyan Zhang
807244badd improved warning in ReactUpdateQueue (#7326)
(cherry picked from commit 3fd582643e)
2016-07-21 14:34:16 -07:00
Alex Zherdev
2106bf5085 Mention actual prop type in element type checker (#7319)
(cherry picked from commit 8bcea5310e)
2016-07-21 14:34:16 -07:00
Sassan Haradji
2debcef8f6 prevent spamming warnings related to performance measurement code (#7299)
* prevent spamming warnings related to performance measurement code

* minor changes in names and such

* -

* -

(cherry picked from commit 1cc9a5dc71)
2016-07-21 14:34:16 -07:00
Dan Abramov
7cdcb4f696 Eagerly evaluate inline requires in Jest (#7245)
* Eagerly evaluate inline requires in Jest

I inlined some requires in #7188 to fix the build size regression.
However this caused an issue with Jest due to it resetting module registry between tests.

This is a temporary fix to #7240.
It should be reverted as part of #7178.

* Make the hack work in all environments

(cherry picked from commit 15ae5857f6)
2016-07-21 14:34:15 -07:00
Dan Abramov
8f8e215df1 Fix TestUtils crash with NODE_ENV=production (#7246)
I caused it with #7189.
We generally don’t recommend running TestUtils in production environment but this is technically a regression.

Fixes #7231.
(cherry picked from commit 27d7592cf6)
2016-07-21 14:34:15 -07:00
Paul O’Shannessy
0c56ee7a89 Switch Travis CI to Trusty Beta (#7309)
(cherry picked from commit 5ac1bae58e)
2016-07-20 11:48:19 -07:00
Paul O’Shannessy
dfebed11c2 Merge pull request #7308 from zpao/jekyll3
Upgrade to Jekyll 3
(cherry picked from commit 5e3959e071)
2016-07-19 16:36:23 -07:00
Paul O’Shannessy
0394bae0e3 [docs] Follow up to 6972 - update docs code (#7278)
(cherry picked from commit 0bfaf5156d)
2016-07-19 16:36:23 -07:00
segmentationfaulter
1e4828d9fc Update 03-interactivity-and-dynamic-uis.md (#6972)
(cherry picked from commit bf0572dde7)
2016-07-19 16:36:23 -07:00
Dan Abramov
108f25350d Clarify the section about dogfooding (#7292) 2016-07-16 15:03:00 +01:00
Dan Abramov
f40b5b5c47 Minor tweaks to Design Principles (#7283) 2016-07-14 21:30:13 +01:00
Dan Abramov
b38bbde2fe Add Design Principles to the docs (#7282) 2016-07-14 20:39:41 +01:00
Fernando Alex Helwanger
939071d737 Add mixins property to context example (#7277) 2016-07-14 14:25:44 +01:00
Paul O’Shannessy
42d7d0adad 15.3.0-rc.2 2016-07-13 14:03:52 -07:00
Troy DeMonbreun
14e6a69a46 Fix #7099 (#7251)
* Set step prop before value prop

* Embed comments on .step sequence behavior

(cherry picked from commit fc04310792)
2016-07-13 13:54:23 -07:00
Mert Kahyaoğlu
b1e1ccf632 Renaming: ReactDOM (#7265)
Rename React with ReactDOM
(cherry picked from commit 2da50a0f18)
2016-07-13 13:54:23 -07:00
Brandon Dail
7b78757c6f Add referrerPolicy to HTMLDOMPropertyConfig (#7274)
(cherry picked from commit cccef3c683)
2016-07-13 13:54:23 -07:00
Brandon Dail
7d3cf9565e Inject default batching after pending transactions (#7033)
(cherry picked from commit b6e1eb2718)
2016-07-13 13:54:22 -07:00
Paul O’Shannessy
86cc1d4e67 15.3.0-rc.1 2016-07-13 11:57:28 -07:00
Paul O’Shannessy
80d09bfbb3 Regenerate error codes 2016-07-13 11:50:57 -07:00
Keyan Zhang
615ae2f497 warn for using maps as children with owner info (#7260)
(cherry picked from commit 5103e1d6a1)
2016-07-13 11:44:10 -07:00
Ben Alpert
1c3b4af564 Test renderer improvements (#7258)
Adds `.update(newElement)` and `.unmount()` and makes children reorders and composite type swapping work.

Part of #7148.
(cherry picked from commit caec8d5ce7)
2016-07-13 11:44:10 -07:00
Ben Alpert
40cc8fa45f Update benchmarks to be more realistic polymorphically (#7255)
Previously, the extract-components script would create the same number of layers of composites as the page it captures, but it would output a new class for each time any composite is used (since we don't want to replicate all the component logic).

I changed the script to output a single type for each type in the input -- and each generated component takes an index for which output it should return. This should be closer to how the original code behaves, especially with respect to VM function call lookups where the amount of polymorphism makes a difference.

I re-recorded the benchmarks with the new scripts. They run significantly faster:

```
Comparing old.txt (control) vs new.txt (test)
Significant differences marked by ***
% change from control to test, with 99% CIs:

* ssr_pe_cold_ms_jsc_jit
    % change: -41.73% [-43.37%, -40.09%]  ***
    means: 39.3191 (control), 22.9127 (test)
* ssr_pe_cold_ms_jsc_nojit
    % change: -44.24% [-46.69%, -41.80%]  ***
    means: 45.8646 (control), 25.5764 (test)
* ssr_pe_cold_ms_node
    % change: -45.61% [-47.38%, -43.85%]  ***
    means: 90.1118 (control), 49.0116 (test)
```

This is probably in part due to the changes here, but also the page I captured has changed somewhat in the meantime and there seem to be slightly fewer components in the hierarchy, so they're not really comparable. But going forward we can use this benchmark which should be more accurate. I also included an identical copy that uses stateless functional components so we can test optimizations to those later.
(cherry picked from commit e5513eceff)
2016-07-13 11:44:09 -07:00
Kent C. Dodds
ea61ddb0d0 Add link to video chat with @spicyj (#7252)
(cherry picked from commit 12bc80a6dc)
2016-07-13 11:44:09 -07:00
Usman
9f975293e1 Fixed all eslint warnings (#7230)
(cherry picked from commit c52a2b9ab0)
2016-07-13 11:44:09 -07:00
Samy Al Zahrani
d40393fde7 Add xmlns and xmlns:xlink attributes (#6471)
(cherry picked from commit 9a80d42817)
2016-07-13 11:44:09 -07:00
Dan Abramov
8517e99816 Fix unmounting performance regression in V8 (#7232)
As reported in #7227, unmounting performance regressed with React 15.
It seems that `delete` has become much slower since we started using numeric keys.
Forcing dictionary keys to start with a dot fixes the issue.
(cherry picked from commit 64e7602b3b)
2016-07-13 11:44:09 -07:00
Ben Alpert
cf07f0cab1 Add React.PureComponent (#7195)
This provides an easy way to indicate that components should only rerender when given new props, like PureRenderMixin. If you rely on mutation in your React components, you can continue to use `React.Component`.

Inheriting from `React.PureComponent` indicates to React that your component doesn't need to rerender when the props are unchanged. We'll compare the old and new props before each render and short-circuit if they're unchanged. It's like an automatic shouldComponentUpdate.
(cherry picked from commit c8fbdac227)
2016-07-13 11:44:09 -07:00
yiminghe
ddb58dd9f3 consistent owner for stateless component (#6534)
(cherry picked from commit b11540ccb2)
2016-07-13 11:43:37 -07:00
Brandon Dail
7d9ded56a2 Use hardcoded value for PropType secret (#7194)
Rename secret!
(cherry picked from commit 2c93a41580)
2016-07-13 11:39:40 -07:00
Brandon Dail
e75e8dcbeb Warn if PropType function is called manually (#7132)
* Warn if PropType function is called in production

* Check if console is undefined before warning

* Randomize value of ReactPropTypesSecret

* Remove dev environment tests

* Rename typeCheckPass to productionWarningCheck

* Rename productionWarningCheck to expectWarningInProduction

* Call toString on Math.random()

* Rename test block for React type checks

* Make sure warning isnt emitted for failing props

* Cache warning by component and prop, warn in dev

* Pass ReactPropTypesSecret to internal checks

* Move tests to ReactPropTypes-test.js

* Update the warning message to include link

* Do not test warning for unions  with invalid args

(cherry picked from commit 95ac239cf3)
2016-07-13 11:39:40 -07:00
Troy DeMonbreun
4a0a534357 Fix for #5468: Validate PropTypes.oneOf(Type) arguments early (#6316)
* Fix for 5468: Validate proptype definitions sooner

Added typeCheckWarn() func and updated the oneOf/oneOfType tests
Added __DEV__ warning for invalid oneOf/OneOfType args

* Suppress redundant error on warn; typeCheckWarn() removed

* Return no-op

* Using emptyFunction module for consistency

* Remove createChainableTypeChecker() call

* Adjust test to assert type check passes when warned

(cherry picked from commit 6cc037bd0d)
2016-07-13 11:39:40 -07:00
Ben Alpert
d441128bf6 Make "unexpected batch number" a warning (#7133)
This was added to catch internal errors in React but doesn't seem to be doing much good except frustrating people more when their apps throw (#6895, FB-internal t11950821). Until more proper error boundaries land, let's make this a warning.
(cherry picked from commit abcd567325)
2016-07-13 11:39:40 -07:00
Dan Abramov
891e087926 Fix tests from #6158 to use Jasmine 2 (#7126)
(cherry picked from commit a49b7a2dfb)
2016-07-13 11:39:40 -07:00
Swaroop SM
9d385ef326 Warn if the included mixin is undefined (#6158)
(cherry picked from commit 18bad0669f)
2016-07-13 11:39:40 -07:00
Evan Jacobs
3b80d4dcd7 [TestUtils] Copy type to nativeEvent in Simulate.<eventName> (#6154)
Although it is unreasonable to set every possible property for
simulated events, `type` is useful for event handlers that are shared
between types and potentially have different behaviors.
(cherry picked from commit 5a20d449f6)
2016-07-13 11:39:39 -07:00
Dan Abramov
343033bf06 Resolve refs in the order of the children (#7101)
* Resolve refs in the order of the children

React makes no guarantees about ref resolution order. Unfortunately, some of the internal Facebook component APIs (specifically, layer dialogs) currently depend on the ref resolution order. Specifically, the assumption is that if the layer dialog is placed as a last child, by the time it mounts or updates, the refs to any previously declared elements have been resolved.

With the current `ReactMultiChild`, this is *usually* the case but not always. Both initial mount and an update of all components satisfy this assumption: by the time a child mounts or updates, the previous children’s refs have been resolved. The one scenario where it isn’t true is when **a new child is mounted during an update**.

In this case, the `mountComponent()` call used to be delayed until `ReactMultiChild` processes the queue. However, this is inconsistent with how updates normally work: unlike mounting, updating and unmounting happens inside `ReactChildReconciler.updateChildren()` loop.

This PR changes the `mountComponent()` to be performed inside `ReactChildReconciler`, just like `receiveComponent()` and `unmountComponent()`, and thus ensures that `attachRef()` calls are enqueued in the order the children were processed, so by the time the next child flushes, the refs of the previous children have been resolved.

This is not ideal and will probably be broken by incremental reconciler in the future. However, since we are trying to get rid of mixins in the internal codebase, and layered components are one of the biggest blockers to that, it’s lesser evil to temporarily make ref resolution order more strict until we have time to fix up the layer APIs to not rely on it, and are able to relax it again (which would be a breaking change).

* Use array instead of object to avoid lookups

(cherry picked from commit 83cbc3e5fb)
2016-07-13 11:39:39 -07:00
Jim
b688bb301c Warn if people mutate children. (#7001)
(cherry picked from commit 49238b9440)
2016-07-13 11:39:34 -07:00
Paul O’Shannessy
9138b45e82 Merge branch '15-stable' into 15-dev 2016-07-13 11:12:26 -07:00
Zac Smith
1b7f871819 Remove uneccesary colon (#7238)
Only use a colon after a statement that is a complete sentence, like [Grammer Girl says](http://www.quickanddirtytips.com/education/grammar/colons).
(cherry picked from commit 473097144c)
2016-07-13 11:11:06 -07:00
Varayut Lerdkanlayanawat
52e45997db Reformat event names in Media Events section (#7250)
(cherry picked from commit 45223dc8bf)
2016-07-13 11:11:05 -07:00
Dan Abramov
45547d1c3b Fix typos in “Mixins Considered Harmful” (#7275)
* Fix typos in “Mixins Considered Harmful”

* Use consistent code style
2016-07-13 18:47:19 +01:00
Dan Abramov
0f520b8cc0 Add a new blog post about mixins 2016-07-13 17:42:01 +01:00
Paul O’Shannessy
5478d76271 Merge pull request #7229 from zpao/blog-post-errorcodes
Blog post for error codes
(cherry picked from commit 92492e08b2)
2016-07-11 17:42:17 -07:00
Paul O’Shannessy
57a1ebb809 Fix typo in previous changelog update 2016-07-08 15:53:40 -07:00
Paul O’Shannessy
dfb5cc306f Changelog fixes 2016-07-08 15:50:04 -07:00
Paul O’Shannessy
ea880f2e2c Update website for 15.2.1 2016-07-08 15:27:35 -07:00
Paul O’Shannessy
68faf9d1b9 15.2.1 2016-07-08 15:15:02 -07:00
Paul O’Shannessy
5597ca70be Update readme for 15.2.1 2016-07-08 15:12:35 -07:00
Paul O’Shannessy
4b9d48a150 Merge branch '15-dev' into 15-stable 2016-07-08 15:11:36 -07:00
Paul O’Shannessy
6b19617333 changelog for 15.2.1 2016-07-08 15:09:28 -07:00
Keyan Zhang
86d696d933 Fixed PR link
(cherry picked from commit 48ccab788b)
2016-07-08 12:01:13 -07:00
Dan Abramov
e685ca9126 Mention @Aweary’s #6933 in 15.2.0 changelog
(cherry picked from commit 4aa860e1bb)
2016-07-08 12:01:08 -07:00
Dan Abramov
abaa9a8760 Add link to @troydemonbreun’s contribution
We missed this PR in the changelog
(cherry picked from commit 36734f4d37)
2016-07-08 12:01:01 -07:00
Paul O’Shannessy
ebabd2f8cd Rebuild error codes 2016-07-08 11:49:51 -07:00
Paul O’Shannessy
c51e8a1523 re-shrinkwrap 2016-07-08 11:46:00 -07:00
Dan Abramov
9fb898943a Make ReactPerf.start() work during reconciliation (#7208)
* Add failing test demonstrating a ReactPerf warning

* Make the failing ReactPerf test more precise

* Make ReactPerf.start() work during reconciliation

* Reorder lifecycle methods for greater clarity

* Fix memory leak

* Error boundaries should not break ReactPerf

* Put onBeginFlush/onEndFlush into transaction wrappers

This looks cleaner even though it is not strictly necessary.
We still call them manually for unmounting because it doesn't have a transaction.

(cherry picked from commit 1a0e3a3215)
2016-07-08 11:01:15 -07:00
saiyagg
ccd781d97e Remove duplicate line (#7210)
(cherry picked from commit 21ce27161d)
2016-07-08 10:58:37 -07:00
Andrey Okonetchnikov
9db68fcf5d Do not render name attribute on INPUT if it is not supplied. Closes #7198. (#7199)
(cherry picked from commit 0d892c03da)
2016-07-08 10:58:37 -07:00
Paul O’Shannessy
219e838070 Don't detach value from defaultValue for submit/reset inputs (#7197)
(cherry picked from commit 5c737b9550)
2016-07-08 10:58:37 -07:00
Dan Abramov
720ce5aa70 Pass shouldHaveDebugID flag to instantiateComponent (#7193)
* Add failing tests for #7187 and #7190

* Pass shouldHaveDebugID flag to instantiateComponent

This allows us to remove a hack that was added in #6770 and caused #7187 and #7190.

* Move logic for choosing whether to use debugID outside instantiate

(cherry picked from commit d2ff462b79)
2016-07-08 10:58:36 -07:00
Sebastian Markbåge
a0a8f2a451 Move error boundaries test into reconciler (#7166)
The src/core folder moved while this PR was pending so this file
didn't move with it.

Let's get rid of this annoying top level folder.
(cherry picked from commit 4f7a38c3b7)
2016-07-08 10:56:29 -07:00
Marshall Bowers
67cc922747 Gulp: lint, flow, and version-check (#7174)
* Add plugin loading for gulp

* Convert `lint` task to gulp

* Convert `flow` task to gulp

* Convert `version-check` task to gulp

* Add missing semicolons

(cherry picked from commit 69703e04d5)
2016-07-08 10:56:29 -07:00
Timothy Yung
75e6399261 Revise ResponderTouchHistoryStore Error Handling (#7143)
Touch behavior is inconsistent across different platforms, and ResponderTouchHistoryStore currently fatals when assumptions are broken. In addition, the behavior differs between development and production.

This pull request does a few things to make ResponderTouchHistoryStore easier to deal with:

Adds Flow to keep the TouchEvent, Touch, and TouchRecord types straight.
Changes behavior to be consistent across environments. This means either always throwing or never throwing (and making use of warning and console.error as appropriate).
When an orphaned move or end event is received, print debug information and ignore it instead of crashing and burning.
(cherry picked from commit 2b226f5fa6)
2016-07-08 10:56:29 -07:00
Dan Abramov
25528eacbc Disable DebugTools in production (#7189)
(cherry picked from commit 5d31ebcf5f)
2016-07-08 10:56:23 -07:00
Christopher Chedeau
f6b619aab1 [flow] isTextInputElement (#7075)
Summary:

I had to cast into any because flow doesn't think that checking the lowercase version of nodeName is a valid way to refine the variable from HTMLElement to HTMLInputElement. I'm also not confident enough in changing the implementation to an instanceof HTMLInputElement to please flow. It also takes care of the null check in the process.

The `nodeName &&` condition wasn't useful since the two branches are checking it against concrete values and actually makes the type different since nodeName is not a boolean per se. I replaced them with if conditions to make it clearer what it actually did instead of doing boolean logic tricks.

It is unclear why I had to type supportedInputTypes, see this internal post for a discussion: https://www.facebook.com/groups/flowtype/permalink/1084168611631753/

The only difference in behavior is that I now explicitely convert to boolean the object dereference via `!!`.

Test Plan:
npm run flow
Careful inspection of the code

Reviewers: @zpao @spicyj
(cherry picked from commit 309215fc40)
2016-07-08 10:48:57 -07:00
Dan Abramov
7547d0d8e5 Inline dev-only requires (#7188)
* Inline dev-only requires

This reduces the production bundled build size.

* Use new references after resetting module registry in tests

This fixes the tests which were broken due to inlining some requires.

(cherry picked from commit 8fe6b5fb46)
2016-07-08 10:48:57 -07:00
Christopher Chedeau
d7a6c95464 [flow] fix flattenChildren type (#7110)
Summary:
Make the debug attribute optional

Test Plan:
npm run flow

Reviewers: @keyanzhang @chicoxyzzy
(cherry picked from commit 07cfba17a9)
2016-07-08 10:48:57 -07:00
Dan Abramov
9687b35d83 Remove Danger.dangerouslyRenderMarkup as it is dead code (#7185)
(cherry picked from commit 7d0801e1a0)
2016-07-08 10:48:57 -07:00
Robin Ricard
173d065a9e Trigger a proper no-op warning for async state changes on server (#7127)
This commit fixes #5473: ReactDOMServer.renderToString: presence of onClick
handler causes errors on async update

This commit performs the following changes:

- Adds a getUpdateQueue method to ReactServerRenderingTransaction,
  ReactReconcileTransaction, ReactNativeReconcileTransaction and
  ReactTestReconcileTransaction
- Make the ReactCompositeComponent call this getUpdateQueue instead of using
  ReactUpdateQueue that was unwanted at certain moments on server
- On ReactServerRenderingTransaction, dispatch ReactUpdateQueue's methods
  while rendering and warning methods afterwards. This is done through the new
  ReactServerUpdateQueue class
- Added a series of tests that mimics the case presented in #5473 with setState,
  forceUpdate and replaceState
- Add flow typechecking on concerned files
(cherry picked from commit dbdddf1c82)
2016-07-08 10:48:56 -07:00
Richard Roncancio
67cbe6d471 Removed transitionAppearTimeout to remove warning (#7165)
- Removed the prop transitionAppearTimeout from
addons/transitions/ReactTransitionGroup in order to remove a warning
when passing unknown props to DOM elements.
(cherry picked from commit 6e5dd8926c)
2016-07-08 10:48:56 -07:00
Sebastian Markbåge
c625bc88aa Unshare not actually shared files (#7167)
This moves some files out of shared that are not actually shared
with isomorphic. They're specific to the renderers.
(cherry picked from commit 4bc1048e0d)
2016-07-08 10:48:56 -07:00
Sebastian Markbåge
f1f599d775 Merge pull request #7154 from sebmarkbage/sideeffects
[Fiber] Host Side Effects
(cherry picked from commit cf259a4ff8)
2016-07-08 10:48:56 -07:00
Sebastian Markbåge
c4b719d4dc Merge pull request #7034 from sebmarkbage/newreconciler
[Fiber] Host Container Fiber and Priority Levels
(cherry picked from commit 291f8e30a9)
2016-07-08 10:48:56 -07:00
starkch
e23690a0dc Reword invariant message about empty tags (fixes #7065) (#7066)
* addresses issue #7065

* fix test to use new message

* fix string in tests

* fix test string

* Update error message and tests

(cherry picked from commit f94912516f)
2016-07-08 10:48:56 -07:00
Dan Abramov
20d2398ab6 Fix renderSubtreeIntoContainer to update context (#7125)
* create failing test case

* Fix renderSubtreeIntoContainer to update context

Fixes #6599

* Also test re-rendering due to prop update

* Address review feedback

(cherry picked from commit 25f9f4563e)
2016-07-08 10:48:56 -07:00
Esteban
32cadeacdb Remove comment about PooledClass destructors being optional (#6560)
They are no longer optional since #4720
(cherry picked from commit 752e1595fc)
2016-07-08 10:48:56 -07:00
Sergey Rubanov
a3c0d68af9 [flow] add some typings to utils (#7104)
* add some typings to utils

* add typing of flattenChildren

* more accurate typings for flattenChildren

(cherry picked from commit 3b5c756c7a)
2016-07-08 10:48:56 -07:00
Christopher Chedeau
24cf5c7a5e [flow] type deprecated (#7076)
Summary:

Test Plan:
npm run flow

Reviewers: @zpao @spicyj @gabelevi
(cherry picked from commit 9342c2f02f)
2016-07-08 10:48:56 -07:00
Jim
8ea1ee14d5 Remove dead HAS_SIDE_EFFECTS logic (#6987)
(cherry picked from commit 416b5ef173)
2016-07-08 10:48:56 -07:00
Jared Fox
ec029f66cc fix webcomponent example issue #7056 (#7057)
* fix webcomponent example issue #7056

* update fix issue #7056, remove unused web component  callbacks

(cherry picked from commit cd9ad90d05)
2016-07-08 10:48:55 -07:00
Christopher Chedeau
ba6ca7ff71 [cleanup] Move ReactStateSetters inside of addons/link (#7085)
Summary:
The only callsite of ReactStateSetters is in LinkedStateMixin which lives in addons/link. Better move it there to avoid cluttering the other folder.

Test Plan:
None

Reviewers: @zpao @spicyj
(cherry picked from commit b0732ef881)
2016-07-08 10:48:55 -07:00
Christopher Chedeau
eb9f4efde7 [flow] type adler32 (#7080)
This one is trivial

Test Plan:
npm run flow

Reviewers: @zpao @spicyj
(cherry picked from commit 489caeb2d7)
2016-07-08 10:48:55 -07:00
Christopher Chedeau
8ee93720ce [flow] type KeyEscapeUtils (#7079)
Summary:

The only call site ensures that the value is not null: dc6fc8cc07/src/shared/utils/traverseAllChildren.js (L44)

key is stringified inside of createElement, so we are guaranteed to receive a string right now: dc6fc8cc07/src/isomorphic/classic/element/ReactElement.js (L142)

Test Plan:
npm run flow

Reviewers: @zpao @spicyj
(cherry picked from commit 12a6ad1ef5)
2016-07-08 10:48:55 -07:00
Christopher Chedeau
cea00b4b21 Merge pull request #7053 from vjeux/flow_accumulate
[flow] annotate accumulate, accumulateInto and forEachAccumulated
(cherry picked from commit 5b4dad31f8)
2016-07-08 10:48:55 -07:00
Paul O’Shannessy
f3c9508e95 Specify possible need for C++ compiler (#7064)
(cherry picked from commit 4886e028bf)
2016-07-08 10:48:55 -07:00
Toru Kobayashi
23de673537 Remove setProps and replaceProps from src (#7045)
(cherry picked from commit e8fa464d6f)
2016-07-08 10:48:55 -07:00
Jim
26870ad27b Move null-input-value-prop warning into devtool, add stack trace (#7040)
(cherry picked from commit 97d89fa5bf)
2016-07-08 10:48:55 -07:00
Paul O’Shannessy
54ee110436 Merge branch '15-stable' into 15-dev 2016-07-07 23:17:21 -07:00
Paul O’Shannessy
a011a23090 Import warnings that currently live in gists. (#7175)
(cherry picked from commit 26ed910f28)
2016-07-05 13:54:19 -07:00
Samuel Reed
0d4c994471 Add PropTypes.symbol to reusable components doc (#7171)
(cherry picked from commit 3946ac33b8)
2016-07-05 13:54:19 -07:00
Paul O’Shannessy
bc1d59ee19 Fix formatting of changelog 2016-07-01 11:56:41 -07:00
Paul O’Shannessy
3a6584b2ee Update website for 15.2.0 2016-07-01 11:41:46 -07:00
427 changed files with 26360 additions and 19271 deletions

View File

@@ -34,4 +34,4 @@ suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(2[0-4]\\|1[0-9]\\|[0-9
suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy
[version]
^0.26.0
^0.27.0

View File

@@ -1,8 +1,11 @@
---
sudo: required
dist: trusty
language: node_js
node_js:
- 4
sudo: false
rvm:
- 2.2.3
cache:
directories:
- docs/vendor/bundle

View File

@@ -1,14 +1,72 @@
/## 15.2.0 (July 1, 2016)
## 15.3.0 (July 29, 2016)
### React
- Add `React.PureComponent` - a new base class to extend, replacing `react-addons-pure-render-mixin` now that mixins don't work with ES2015 classes. ([@spicyj](https://github.com/spicyj) in [#7195](https://github.com/facebook/react/pull/7195))
- Add new warning when modifying `this.props.children`. ([@jimfb](https://github.com/jimfb) in [#7001](https://github.com/facebook/react/pull/7001))
- Fixed issue with ref resolution order. ([@gaearon](https://github.com/gaearon) in [#7101](https://github.com/facebook/react/pull/7101))
- Warn when mixin is undefined. ([@swaroopsm](https://github.com/swaroopsm) in [#6158](https://github.com/facebook/react/pull/6158))
- Downgrade "unexpected batch number" invariant to a warning. ([@spicyj](https://github.com/spicyj) in [#7133](https://github.com/facebook/react/pull/7133))
- Validate arguments to `oneOf` and `oneOfType` PropTypes sooner. ([@troydemonbreun](https://github.com/troydemonbreun) in [#6316](https://github.com/facebook/react/pull/6316))
- Warn when calling PropTypes directly. ([@Aweary](https://github.com/Aweary) in [#7132](https://github.com/facebook/react/pull/7132), [#7194](https://github.com/facebook/react/pull/7194))
- Improve warning when using Maps as children. ([@keyanzhang](https://github.com/keyanzhang) in [#7260](https://github.com/facebook/react/pull/7260))
- Add additional type information to the `PropTypes.element` warning. ([@alexzherdev](https://github.com/alexzherdev) in [#7319](https://github.com/facebook/react/pull/7319))
- Improve component identification in no-op `setState` warning. ([@keyanzhang](https://github.com/keyanzhang) in [#7326](https://github.com/facebook/react/pull/7326))
### React DOM
- Fix issue with nested server rendering. ([@Aweary](https://github.com/Aweary) in [#7033](https://github.com/facebook/react/pull/7033))
- Add `xmlns`, `xmlnsXlink` to supported SVG attributes. ([@salzhrani](https://github.com/salzhrani) in [#6471](https://github.com/facebook/react/pull/6471))
- Add `referrerPolicy` to supported HTML attributes. ([@Aweary](https://github.com/Aweary) in [#7274](https://github.com/facebook/react/pull/7274))
- Fix issue resulting in `<input type="range">` initial value being rounded. ([@troydemonbreun](https://github.com/troydemonbreun) in [#7251](https://github.com/facebook/react/pull/7251))
### React Test Renderer
- Initial public release of package allowing more focused testing. Install with `npm install react-test-renderer`. ([@spicyj](https://github.com/spicyj) in [#6944](https://github.com/facebook/react/pull/6944), [#7258](https://github.com/facebook/react/pull/7258), [@iamdustan](https://github.com/iamdustan) in [#7362](https://github.com/facebook/react/pull/7362))
### React Perf Add-on
- Fix issue resulting in excessive warnings when encountering an internal measurement error. ([@sassanh](https://github.com/sassanh) in [#7299](https://github.com/facebook/react/pull/7299))
### React TestUtils Add-on
- Implement `type` property on for events created via `TestUtils.Simulate.*`. ([@yaycmyk](https://github.com/yaycmyk) in [#6154](https://github.com/facebook/react/pull/6154))
- Fix crash when running TestUtils with the production build of React. ([@gaearon](https://github.com/gaearon) in [#7246](https://github.com/facebook/react/pull/7246))
## 15.2.1 (July 8, 2016)
### React
- Fix errant warning about missing React element. ([@gaearon](https://github.com/gaearon) in [#7193](https://github.com/facebook/react/pull/7193))
- Better removal of dev-only code, leading to a small reduction in the minified production bundle size. ([@gaearon](https://github.com/gaearon) in [#7188](https://github.com/facebook/react/pull/7188), [#7189](https://github.com/facebook/react/pull/7189))
### React DOM
- Add stack trace to null input value warning. ([@jimfb](https://github.com/jimfb) in [#7040](https://github.com/facebook/react/pull/7040))
- Fix webcomponents example. ([@jalexanderfox](https://github.com/jalexanderfox) in [#7057](https://github.com/facebook/react/pull/7057))
- Fix `unstable_renderSubtreeIntoContainer` so that context properly updates when linked to state. ([@gaearon](https://github.com/gaearon) in [#7125](https://github.com/facebook/react/pull/7125))
- Improve invariant wording for void elements. ([@starkch](https://github.com/starkch) in [#7066](https://github.com/facebook/react/pull/7066))
- Ensure no errors are thrown due to event handlers in server rendering. ([@rricard](https://github.com/rricard) in [#7127](https://github.com/facebook/react/pull/7127))
- Fix regression resulting in `value`-less submit and reset inputs removing the browser-default text. ([@zpao](https://github.com/zpao) in [#7197](https://github.com/facebook/react/pull/7197))
- Fix regression resulting in empty `name` attribute being added to inputs when not provided. ([@okonet](https://github.com/okonet) in [#7199](https://github.com/facebook/react/pull/7199))
- Fix issue with nested server rendering. ([@Aweary](https://github.com/Aweary) in [#7033](https://github.com/facebook/react/pull/7033))
### React Perf Add-on
- Make `ReactPerf.start()` work properly during lifecycle methods. ([@gaearon](https://github.com/gaearon) in [#7208](https://github.com/facebook/react/pull/7208)).
### React CSSTransitionGroup Add-on
- Fix issue resulting in spurious unknown property warnings. ([@batusai513](https://github.com/batusai513) in [#7165](https://github.com/facebook/react/pull/7165))
### React Native Renderer
- Improve error handling in cross-platform touch event handling. ([@yungsters](https://github.com/yungsters) in [#7143](https://github.com/facebook/react/pull/7143))
## 15.2.0 (July 1, 2016)
### React
- Add error codes to production invariants, with links to the view the full error text. ([@keyanzhang](https://github.com/keyanzhang) in [#6948](https://github.com/facebook/react/pull/6948))
- Include component stack information in PropType validation warnings. ([@spicyj](https://github.com/spicyj) in [#6771](https://github.com/facebook/react/pull/6771))
- Include component stack information in PropType validation warnings. ([@troydemonbreun](https://github.com/troydemonbreun) in [#6398](https://github.com/facebook/react/pull/6398), [@spicyj](https://github.com/spicyj) in [#6771](https://github.com/facebook/react/pull/6771))
- Include component stack information in key warnings. ([@keyanzhang](https://github.com/keyanzhang) in [#6799](https://github.com/facebook/react/pull/6799))
- Stop validating props at mount time, only validate at element creation. ([@keyanzhang](https://github.com/keyanzhang) in [#6823](https://github.com/facebook/react/pull/6823))
- Stop validating props at mount time, only validate at element creation. ([@keyanzhang](https://github.com/keyanzhang) in [#6824](https://github.com/facebook/react/pull/6824))
- New invariant providing actionable error in missing instance case. ([@yungsters](https://github.com/yungsters) in [#6990](https://github.com/facebook/react/pull/6990))
- Add `React.PropTypes.symbol` to support ES2015 Symbols as props. ([@puradox](https://github.com/puradox) in [#6377](https://github.com/facebook/react/pull/6377))
- Fix incorrect coercion of ref or key that are undefined in development ([@gaearon](https://github.com/gaearon) in [#6880](https://github.com/facebook/react/pull/6880))
- Fix a false positive when passing other elements props to cloneElement ([@ericmatthys](https://github.com/ericmatthys) in [#6268](https://github.com/facebook/react/pull/6268))
- Warn if you attempt to define `childContextTypes` on a functional component ([@Aweary](https://github.com/Aweary) in [#6933](https://github.com/facebook/react/pull/6933))
### React DOM
- Add warning for unknown properties on DOM elements. ([@jimfb](https://github.com/jimfb) in [#6800](https://github.com/facebook/react/pull/6800), [@gm758](https://github.com/gm758) in [#7152](https://github.com/facebook/react/pull/7152))

View File

@@ -32,6 +32,8 @@ Just make sure to run the whole test suite before submitting a pull request!
**Working on your first Pull Request?** You can learn how from this *free* series [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github)
You may also be interested in watching [this short video](https://www.youtube.com/watch?v=wUpPsEcGsg8) (26 mins) which gives an introduction on how to contribute to the React JS project.
The core team will be monitoring for pull requests. When we get one, we'll run some Facebook-specific integration tests on it first. From here, we'll need to get another person to sign off on the changes and then merge the pull request. For API changes we may need to fix internal uses, which could cause some delay. We'll do our best to provide updates and feedback throughout the process.
*Before* submitting a pull request, please make sure the following is done…

View File

@@ -52,11 +52,17 @@ module.exports = function(grunt) {
grunt.loadNpmTasks(npmTaskName);
});
grunt.registerTask('eslint', require('./grunt/tasks/eslint'));
grunt.registerTask('eslint', function() {
// Use gulp here.
spawnGulp(['eslint'], null, this.async());
});
grunt.registerTask('lint', ['eslint']);
grunt.registerTask('flow', require('./grunt/tasks/flow'));
grunt.registerTask('flow', function() {
// Use gulp here.
spawnGulp(['flow'], null, this.async());
});
grunt.registerTask('delete-build-modules', function() {
// Use gulp here.
@@ -84,7 +90,14 @@ module.exports = function(grunt) {
grunt.registerTask('npm-react-addons:release', npmReactAddonsTasks.buildReleases);
grunt.registerTask('npm-react-addons:pack', npmReactAddonsTasks.packReleases);
grunt.registerTask('version-check', require('./grunt/tasks/version-check'));
var npmReactTestRendererTasks = require('./grunt/tasks/npm-react-test');
grunt.registerTask('npm-react-test:release', npmReactTestRendererTasks.buildRelease);
grunt.registerTask('npm-react-test:pack', npmReactTestRendererTasks.packRelease);
grunt.registerTask('version-check', function() {
// Use gulp here.
spawnGulp(['version-check'], null, this.async());
});
grunt.registerTask('build:basic', [
'build-modules',
@@ -137,6 +150,8 @@ module.exports = function(grunt) {
'npm-react-native:pack',
'npm-react-addons:release',
'npm-react-addons:pack',
'npm-react-test:release',
'npm-react-test:pack',
'compare_size',
]);

View File

@@ -35,12 +35,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-15.2.0.js"></script>
<script src="https://fb.me/react-15.3.0.js"></script>
<!-- The ReactDOM Library -->
<script src="https://fb.me/react-dom-15.2.0.js"></script>
<script src="https://fb.me/react-dom-15.3.0.js"></script>
```
We've also built a [starter kit](https://facebook.github.io/react/downloads/react-15.2.0.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-15.3.0.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:
@@ -65,6 +65,7 @@ The process to build `react.js` is built entirely on top of node.js, using many
#### Prerequisites
* You have `node` installed at v4.0.0+ and `npm` at v2.0.0+.
* You have `gcc` installed or are comfortable installing a compiler if needed. Some of our `npm` dependencies may require a compliation step. On OS X, the Xcode Command Line Tools will cover this. On Ubuntu, `apt-get install build-essential` will install the required packages. Similar commands should work on other Linux distros. Windows will require some additional steps, see the [`node-gyp` installation instructions](https://github.com/nodejs/node-gyp#installation) for details.
* You are familiar with `npm` and know whether or not you need to use `sudo` when installing packages globally.
* You are familiar with `git`.

View File

@@ -1,6 +1,7 @@
---
layout: single
title: Page Not Found
permalink: 404.html
---
We couldn't find what you were looking for.

View File

@@ -3,11 +3,12 @@ source 'https://rubygems.org'
gem 'rake'
# jekyll, which builds it all
# 2.0 includes sass processing
gem 'jekyll', '~>2.0'
# 3.0 includes sass processing
gem 'jekyll', '~>3.1'
# Auto redirect pages
# Jekyll extensions
gem 'jekyll-redirect-from'
gem 'jekyll-paginate'
# JSON
gem 'json'
@@ -17,3 +18,12 @@ gem 'rb-fsevent'
# For markdown header cleanup
gem 'sanitize', '~>2.0'
# Markdown
gem 'redcarpet'
# Syntax highlighting
gem 'pygments.rb'
# Avoid having to poll for changes on Windows
gem 'wdm', '>= 0.1.0' if Gem.win_platform?

View File

@@ -1,85 +1,70 @@
GEM
remote: https://rubygems.org/
specs:
blankslate (2.1.2.4)
celluloid (0.15.2)
timers (~> 1.1.0)
classifier (1.3.4)
fast-stemmer (>= 1.0.0)
coffee-script (2.3.0)
coffee-script-source
execjs
coffee-script-source (1.7.1)
colorator (0.1)
execjs (2.2.1)
fast-stemmer (1.0.2)
ffi (1.9.3)
jekyll (2.2.0)
classifier (~> 1.3)
ffi (1.9.14)
ffi (1.9.14-x64-mingw32)
jekyll (3.1.6)
colorator (~> 0.1)
jekyll-coffeescript (~> 1.0)
jekyll-gist (~> 1.0)
jekyll-paginate (~> 1.0)
jekyll-sass-converter (~> 1.0)
jekyll-watch (~> 1.0)
jekyll-watch (~> 1.1)
kramdown (~> 1.3)
liquid (~> 2.6.1)
liquid (~> 3.0)
mercenary (~> 0.3.3)
pygments.rb (~> 0.6.0)
redcarpet (~> 3.1)
rouge (~> 1.7)
safe_yaml (~> 1.0)
toml (~> 0.1.0)
jekyll-coffeescript (1.0.0)
coffee-script (~> 2.2)
jekyll-gist (1.1.0)
jekyll-paginate (1.0.0)
jekyll-redirect-from (0.5.0)
jekyll (~> 2.0)
jekyll-sass-converter (1.2.0)
sass (~> 3.2)
jekyll-watch (1.1.0)
listen (~> 2.7)
json (1.8.1)
kramdown (1.4.1)
liquid (2.6.1)
listen (2.7.9)
celluloid (>= 0.15.2)
rb-fsevent (>= 0.9.3)
rb-inotify (>= 0.9)
mercenary (0.3.4)
mini_portile (0.6.0)
nokogiri (1.6.3.1)
mini_portile (= 0.6.0)
parslet (1.5.0)
blankslate (~> 2.0)
posix-spawn (0.3.9)
pygments.rb (0.6.0)
jekyll-paginate (1.1.0)
jekyll-redirect-from (0.11.0)
jekyll (>= 2.0)
jekyll-sass-converter (1.4.0)
sass (~> 3.4)
jekyll-watch (1.4.0)
listen (~> 3.0, < 3.1)
json (2.0.1)
kramdown (1.11.1)
liquid (3.0.6)
listen (3.0.8)
rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7)
mercenary (0.3.6)
mini_portile2 (2.1.0)
nokogiri (1.6.8)
mini_portile2 (~> 2.1.0)
pkg-config (~> 1.1.7)
nokogiri (1.6.8-x64-mingw32)
mini_portile2 (~> 2.1.0)
pkg-config (~> 1.1.7)
pkg-config (1.1.7)
posix-spawn (0.3.11)
pygments.rb (0.6.3)
posix-spawn (~> 0.3.6)
yajl-ruby (~> 1.1.0)
rake (10.3.2)
rb-fsevent (0.9.4)
rb-inotify (0.9.5)
yajl-ruby (~> 1.2.0)
rake (11.2.2)
rb-fsevent (0.9.7)
rb-inotify (0.9.7)
ffi (>= 0.5.0)
redcarpet (3.1.2)
redcarpet (3.3.4)
rouge (1.11.1)
safe_yaml (1.0.4)
sanitize (2.0.6)
sanitize (2.1.0)
nokogiri (>= 1.4.4)
sass (3.3.14)
timers (1.1.0)
toml (0.1.1)
parslet (~> 1.5.0)
yajl-ruby (1.1.0)
sass (3.4.22)
yajl-ruby (1.2.1)
PLATFORMS
ruby
x64-mingw32
DEPENDENCIES
jekyll (~> 2.0)
jekyll (~> 3.1)
jekyll-paginate
jekyll-redirect-from
json
pygments.rb
rake
rb-fsevent
redcarpet
sanitize (~> 2.0)
BUNDLED WITH
1.10.1
1.11.2

View File

@@ -5,21 +5,37 @@ url: https://facebook.github.io
baseurl: "/react"
permalink: "/blog/:year/:month/:day/:title.html"
paginate_path: "/blog/page:num/"
relative_permalinks: true
paginate: 5
timezone: America/Los_Angeles
highlighter: pygments
defaults:
- scope:
path: ''
type: post
type: posts
values:
layout: post
sectionid: blog
- scope:
path: blog
type: pages
values:
sectionid: blog
- scope:
path: docs
type: page
type: pages
values:
layout: docs
sectionid: docs
- scope:
path: tips
type: pages
values:
sectionid: docs
- scope:
path: contributing
type: pages
values:
sectionid: docs
exclude:
- Gemfile
- Gemfile.lock
@@ -36,13 +52,14 @@ sass:
sass_dir: _css
gems:
- jekyll-redirect-from
react_version: 15.1.0
- jekyll-paginate
react_version: 15.2.1
react_hashes:
dev: I9uU7ZWS2zpxPvpUfutJ7LD6Mmzk3pvvBCbfC7/imYVdtuPR9hRiLIJrVIZilwht
prod: 3aKuzevuBSs0FfxObUZ42KUGqneCk7kh9g7/aZ+Yzf5MhucA9KvfUSH5jcma9kdZ
addons_dev: 5jJyZhvy/Kkt6uTW3AY3U6bZ+0yDAS7NQDHExu76Zmoa6ABy5g42MoGj9pgeELqf
addons_prod: JkeMnC7xa++rlt5smrQVlrrBdYEy0WJbF78QOIpdQeg7UCUjWF3/gyNC/IVh5s4l
dom_dev: MWQ0uDsZsWizHa2PvAdb45Y1JXy+oLZPc0fabiueWS4rOZuKXDzqf12jjKMF8u3t
dom_prod: tEAvCNm5NozfOX3D8eOmg6E7CUNRQEaLq9xPqVr9ii9BW1cVXiuHKqrXUh3W7wg5
dom_server_dev: WTaEVUVSSkUY+GTjvLO65ZjnLMR2BBa+WkXF1F4rVIxqoMnxFcjugmyoxYwXMmF6
dom_server_prod: rFqq5Djim9lOAYssAJTvdJhtcGdz328JIjbcDq/5/r5DLwYyl8esZ1C0+CKeSXxo
dev: g2900ZIpFKhyIsz+bnx4YDEfAISugYRU58ljeAgI8TZ0A0AkRLGUCN7OmjF16Cj+
prod: ICzDcvbNpMy31akJ8WzksHoK9tl1iRIUPRCaBRN+sn/k40TNGjs9IvgPN0SekkDT
addons_dev: js+Yc2Nd259A4+UPokRNVOXJdipY9oIrkkDdFJAZzZxgryRJLkWYDrJVgM97aweF
addons_prod: DaNE8gIDQr8RWDoa4y9HX/70fzdOBzpV/e+7RJtMN1MnXEiCMpiIFtutJml6mvPC
dom_dev: LD1cH7LXOdrrq5dOOiE2N/HdgCyrw3nmUMq6oPFCJKUfWO3i7AozvBKz7G3maMHt
dom_prod: 1dLXeik7kFcDPXbz3rX9dibLTGh/D8dpAOL5X2Ml09pH8wpQlpL+JOgOnzAMCO4T
dom_server_dev: WJt1y2JljJEQ1OgpupP2ly0GgIwi7Aodp+n+/fv2bakpgWpXMnLklj5rSouRJt59
dom_server_prod: Y6UDASOvQhWWBwXy/Ccp4vSAt0YAp+ymuRXBX4hffy+pMlOgjXzryIjbiceIB6GF

View File

@@ -31,6 +31,9 @@ jingc:
josephsavona:
name: Joseph Savona
url: https://twitter.com/en_JS
keyanzhang:
name: Keyan Zhang
url: https://twitter.com/keyanzhang
kmeht:
name: Kunal Mehta
url: https://github.com/kmeht

View File

@@ -0,0 +1,4 @@
- title: Contributing
items:
- id: design-principles
title: Design Principles

View File

@@ -35,4 +35,18 @@
</ul>
</div>
{% endfor %}
<!-- Contributing Nav -->
{% for section in site.data.nav_contributing %}
<div class="nav-docs-section">
<h3>{{ section.title }}</h3>
<ul>
{% for item in section.items %}
<li>
<a href="/react/contributing/{{ item.id }}.html"{% if page.id == item.id %} class="active"{% endif %}>{{ item.title }}</a>
</li>
{% endfor %}
</ul>
</div>
{% endfor %}
</div>

View File

@@ -0,0 +1,23 @@
---
layout: default
sectionid: contributing
---
<section class="content wrap documentationContent">
{% include nav_docs.html %}
<div class="inner-content">
<h1>{{ page.title }}</h1>
<div class="subHeader">{{ page.description }}</div>
{{ content }}
<div class="docs-prevnext">
{% if page.prev %}
<a class="docs-prev" href="/react/contributing/{{ page.prev }}">&larr; Prev</a>
{% endif %}
{% if page.next %}
<a class="docs-next" href="/react/contributing/{{ page.next }}">Next &rarr;</a>
{% endif %}
</div>
</div>
</section>

View File

@@ -50,7 +50,7 @@
React
</a>
<ul class="nav-site nav-site-internal">
<li><a href="/react/docs/getting-started.html"{% if page.sectionid == 'docs' or page.sectionid == 'tips' %} class="active"{% endif %}>Docs</a></li>
<li><a href="/react/docs/getting-started.html"{% if page.sectionid == 'docs' or page.sectionid == 'tips' or page.sectionid == 'contributing' %} class="active"{% endif %}>Docs</a></li>
<li><a href="/react/support.html"{% if page.id == 'support' %} class="active"{% endif %}>Support</a></li>
<li><a href="/react/downloads.html"{% if page.id == 'downloads' %} class="active"{% endif %}>Download</a></li>
<li><a href="/react/blog/"{% if page.sectionid == 'blog' %} class="active"{% endif %}>Blog</a></li>

View File

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

View File

@@ -0,0 +1,18 @@
---
title: "Introducing React's Error Code System"
author: keyanzhang
---
Building a better developer experience has been one of the things that React deeply cares about, and a crucial part of it is to detect anti-patterns/potential errors early and provide helpful error messages when things (may) go wrong. However, most of these only exist in development mode; in production, we avoid having extra expensive assertions and sending down full error messages in order to reduce the number of bytes sent over the wire.
Prior to this release, we stripped out error messages at build-time and this is why you might have seen this message in production:
> Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.
In order to make debugging in production easier, we're introducing an Error Code System in [15.2.0](https://github.com/facebook/react/releases/tag/v15.2.0). We developed a [gulp script](https://github.com/facebook/react/blob/master/scripts/error-codes/gulp-extract-errors.js) that collects all of our `invariant` error messages and folds them to a [JSON file](https://github.com/facebook/react/blob/master/scripts/error-codes/codes.json), and at build-time Babel uses the JSON to [rewrite](https://github.com/facebook/react/blob/master/scripts/error-codes/dev-expression-with-codes.js) our `invariant` calls in production to reference the corresponding error IDs. Now when things go wrong in production, the error that React throws will contain a URL with an error ID and relevant information. The URL will point you to a page in our documentation where the original error message gets reassembled.
While we hope you don't see errors often, you can see how it works [here](/react/docs/error-decoder.html?invariant=109&args[]=Foo). This is what the same error from above will look like:
> Minified React error #109; visit https://facebook.github.io/react/docs/error-decoder.html?invariant=109&args[]=Foo for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
We do this so that the developer experience is as good as possible, while also keeping the production bundle size as small as possible. This feature shouldn't require any changes on your side — use the `min.js` files in production or bundle your application code with `process.env.NODE_ENV === 'production'` and you should be good to go!

View File

@@ -0,0 +1,614 @@
---
title: "Mixins Considered Harmful"
author: gaearon
---
“How do I share the code between several components?” is one of the first questions that people ask when they learn React. Our answer has always been to use component composition for code reuse. You can define a component and use it in several other components.
It is not always obvious how a certain pattern can be solved with composition. React is influenced by functional programming but it came into the field that was dominated by object-oriented libraries. It was hard for engineers both inside and outside of Facebook to give up on the patterns they were used to.
To ease the initial adoption and learning, we included certain escape hatches into React. The mixin system was one of those escape hatches, and its goal was to give you a way to reuse code between components when you arent sure how to solve the same problem with composition.
Three years passed since React was released. The landscape has changed. Multiple view libraries now adopt a component model similar to React. Using composition over inheritance to build declarative user interfaces is no longer a novelty. We are also more confident in the React component model, and we have seen many creative uses of it both internally and in the community.
In this post, we will consider the problems commonly caused by mixins. Then we will suggest several alternative patterns for the same use cases. We have found those patterns to scale better with the complexity of the codebase than mixins.
## Why Mixins are Broken
At Facebook, React usage has grown from a few components to thousands of them. This gives us a window into how people use React. Thanks to declarative rendering and top-down data flow, many teams were able to fix a bunch of bugs while shipping new features as they adopted React.
However its inevitable that some of our code using React gradually became incomprehensible. Occasionally, the React team would see groups of components in different projects that people were afraid to touch. These components were too easy to break accidentally, were confusing to new developers, and eventually became just as confusing to the people who wrote them in the first place. Much of this confusion was caused by mixins. At the time, I wasnt working at Facebook but I came to the [same conclusions](https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750) after writing my fair share of terrible mixins.
This doesnt mean that mixins themselves are bad. People successfully employ them in different languages and paradigms, including some functional languages. At Facebook, we extensively use traits in Hack which are fairly similar to mixins. Nevertheless, we think that mixins are unnecessary and problematic in React codebases. Heres why.
### Mixins introduce implicit dependencies
Sometimes a component relies on a certain method defined in the mixin, such as `getClassName()`. Sometimes its the other way around, and mixin calls a method like `renderHeader()` on the component. JavaScript is a dynamic language so its hard to enforce or document these dependencies.
Mixins break the common and usually safe assumption that you can rename a state key or a method by searching for its occurrences in the component file. You might write a stateful component and then your coworker might add a mixin that reads this state. In a few months, you might want to move that state up to the parent component so it can be shared with a sibling. Will you remember to update the mixin to read a prop instead? What if, by now, other components also use this mixin?
These implicit dependencies make it hard for new team members to contribute to a codebase. A components `render()` method might reference some method that isnt defined on the class. Is it safe to remove? Perhaps its defined in one of the mixins. But which one of them? You need to scroll up to the mixin list, open each of those files, and look for this method. Worse, mixins can specify their own mixins, so the search can be deep.
Often, mixins come to depend on other mixins, and removing one of them breaks the other. In these situations it is very tricky to tell how the data flows in and out of mixins, and what their dependency graph looks like. Unlike components, mixins dont form a hierarchy: they are flattened and operate in the same namespace.
### Mixins cause name clashes
There is no guarantee that two particular mixins can be used together. For example, if `FluxListenerMixin` defines `handleChange()` and `WindowSizeMixin` defines `handleChange()`, you cant use them together. You also cant define a method with this name on your own component.
Its not a big deal if you control the mixin code. When you have a conflict, you can rename that method on one of the mixins. However its tricky because some components or other mixins may already be calling this method directly, and you need to find and fix those calls as well.
If you have a name conflict with a mixin from a third party package, you cant just rename a method on it. Instead, you have to use awkward method names on your component to avoid clashes.
The situation is no better for mixin authors. Even adding a new method to a mixin is always a potentially breaking change because a method with the same name might already exist on some of the components using it, either directly or through another mixin. Once written, mixins are hard to remove or change. Bad ideas dont get refactored away because refactoring is too risky.
### Mixins cause snowballing complexity
Even when mixins start out simple, they tend to become complex over time. The example below is based on a real scenario Ive seen play out in a codebase.
A component needs some state to track mouse hover. To keep this logic reusable, you might extract `handleMouseEnter()`, `handleMouseLeave()` and `isHovering()` into a `HoverMixin`. Next, somebody needs to implement a tooltip. They dont want to duplicate the logic in `HoverMixin` so they create a `TooltipMixin` that uses `HoverMixin`. `TooltipMixin` reads `isHovering()` provided by `HoverMixin` in its `componentDidUpdate()` and either shows or hides the tooltip.
A few months later, somebody wants to make the tooltip direction configurable. In an effort to avoid code duplication, they add support for a new optional method called `getTooltipOptions()` to `TooltipMixin`. By this time, components that show popovers also use `HoverMixin`. However popovers need a different hover delay. To solve this, somebody adds support for an optional `getHoverOptions()` method and implements it in `TooltipMixin`. Those mixins are now tightly coupled.
This is fine while there are no new requirements. However this solution doesnt scale well. What if you want to support displaying multiple tooltips in a single component? You cant define the same mixin twice in a component. What if the tooltips need to be displayed automatically in a guided tour instead of on hover? Good luck decoupling `TooltipMixin` from `HoverMixin`. What if you need to support the case where the hover area and the tooltip anchor are located in different components? You cant easily hoist the state used by mixin up into the parent component. Unlike components, mixins dont lend themselves naturally to such changes.
Every new requirement makes the mixins harder to understand. Components using the same mixin become increasingly coupled with time. Any new capability gets added to all of the components using that mixin. There is no way to split a “simpler” part of the mixin without either duplicating the code or introducing more dependencies and indirection between mixins. Gradually, the encapsulation boundaries erode, and since its hard to change or remove the existing mixins, they keep getting more abstract until nobody understands how they work.
These are the same problems we faced building apps before React. We found that they are solved by declarative rendering, top-down data flow, and encapsulated components. At Facebook, we have been migrating our code to use alternative patterns to mixins, and we are generally happy with the results. You can read about those patterns below.
## Migrating from Mixins
Lets make it clear that mixins are not technically deprecated. If you use `React.createClass()`, you may keep using them. We only say that they didnt work well for us, and so we wont recommend using them in the future.
Every section below corresponds to a mixin usage pattern that we found in the Facebook codebase. For each of them, we describe the problem and a solution that we think works better than mixins. The examples are written in ES5 but once you dont need mixins, you can switch to ES6 classes if youd like.
We hope that you find this list helpful. Please let us know if we missed important use cases so we can either amend the list or be proven wrong!
### Performance Optimizations
One of the most commonly used mixins is [`PureRenderMixin`](/react/docs/pure-render-mixin.html). You might be using it in some components to [prevent unnecessary re-renders](/react/docs/advanced-performance.html#shouldcomponentupdate-in-action) when the props and state are shallowly equal to the previous props and state:
```javascript
var PureRenderMixin = require('react-addons-pure-render-mixin');
var Button = React.createClass({
mixins: [PureRenderMixin],
// ...
});
```
#### Solution
To express the same without mixins, you can use the [`shallowCompare`](/react/docs/shallow-compare.html) function directly instead:
```js
var shallowCompare = require('react-addons-shallow-compare');
var Button = React.createClass({
shouldComponentUpdate: function(nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
},
// ...
});
```
If you use a custom mixin implementing a `shouldComponentUpdate` function with different algorithm, we suggest exporting just that single function from a module and calling it directly from your components.
We understand that more typing can be annoying. For the most common case, we plan to [introduce a new base class](https://github.com/facebook/react/pull/7195) called `React.PureComponent` in the next minor release. It uses the same shallow comparison as `PureRenderMixin` does today.
### Subscriptions and Side Effects
The second most common type of mixins that we encountered are mixins that subscribe a React component to a third-party data source. Whether this data source is a Flux Store, an Rx Observable, or something else, the pattern is very similar: the subscription is created in `componentDidMount`, destroyed in `componentWillUnmount`, and the change handler calls `this.setState()`.
```javascript
var SubscriptionMixin = {
getInitialState: function() {
return {
comments: DataSource.getComments()
};
},
componentDidMount: function() {
DataSource.addChangeListener(this.handleChange);
},
componentWillUnmount: function() {
DataSource.removeChangeListener(this.handleChange);
},
handleChange: function() {
this.setState({
comments: DataSource.getComments()
});
}
};
var CommentList = React.createClass({
mixins: [SubscriptionMixin],
render: function() {
// Reading comments from state managed by mixin.
var comments = this.state.comments;
return (
<div>
{comments.map(function(comment) {
return <Comment comment={comment} key={comment.id} />
})}
</div>
)
}
});
module.exports = CommentList;
```
#### Solution
If there is just one component subscribed to this data source, it is fine to embed the subscription logic right into the component. Avoid premature abstractions.
If several components used this mixin to subscribe to a data source, a nice way to avoid repetition is to use a pattern called [“higher-order components”](https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750). It can sound intimidating so we will take a closer look at how this pattern naturally emerges from the component model.
#### Higher-Order Components Explained
Lets forget about React for a second. Consider these two functions that add and multiply numbers, logging the results as they do that:
```js
function addAndLog(x, y) {
var result = x + y;
console.log('result:', result);
return result;
}
function multiplyAndLog(x, y) {
var result = x * y;
console.log('result:', result);
return result;
}
```
These two functions are not very useful but they help us demonstrate a pattern that we can later apply to components.
Lets say that we want to extract the logging logic out of these functions without changing their signatures. How can we do this? An elegant solution is to write a [higher-order function](https://en.wikipedia.org/wiki/Higher-order_function), that is, a function that takes a function as an argument and returns a function.
Again, it sounds more intimidating than it really is:
```js
function withLogging(wrappedFunction) {
// Return a function with the same API...
return function(x, y) {
// ... that calls the original function
var result = wrappedFunction(x, y);
// ... but also logs its result!
console.log('result:', result);
return result;
};
}
```
The `withLogging` higher-order function lets us write `add` and `multiply` without the logging statements, and later wrap them to get `addAndLog` and `multiplyAndLog` with exactly the same signatures as before:
```js
function add(x, y) {
return x + y;
}
function multiply(x, y) {
return x * y;
}
function withLogging(wrappedFunction) {
return function(x, y) {
var result = wrappedFunction(x, y);
console.log('result:', result);
return result;
};
}
// Equivalent to writing addAndLog by hand:
var addAndLog = withLogging(add);
// Equivalent to writing multiplyAndLog by hand:
var multiplyAndLog = withLogging(multiply);
```
Higher-order components are a very similar pattern, but applied to components in React. We will apply this transformation from mixins in two steps.
As a first step, we will split our `CommentList` component in two, a child and a parent. The child will be only concerned with rendering the comments. The parent will set up the subscription and pass the up-to-date data to the child via props.
```js
// This is a child component.
// It only renders the comments it receives as props.
var CommentList = React.createClass({
render: function() {
// Note: now reading from props rather than state.
var comments = this.props.comments;
return (
<div>
{comments.map(function(comment) {
return <Comment comment={comment} key={comment.id} />
})}
</div>
)
}
});
// This is a parent component.
// It subscribes to the data source and renders <CommentList />.
var CommentListWithSubscription = React.createClass({
getInitialState: function() {
return {
comments: DataSource.getComments()
};
},
componentDidMount: function() {
DataSource.addChangeListener(this.handleChange);
},
componentWillUnmount: function() {
DataSource.removeChangeListener(this.handleChange);
},
handleChange: function() {
this.setState({
comments: DataSource.getComments()
});
},
render: function() {
// We pass the current state as props to CommentList.
return <CommentList comments={this.state.comments} />;
}
});
module.exports = CommentListWithSubscription;
```
There is just one final step left to do.
Remember how we made `withLogging()` take a function and return another function wrapping it? We can apply a similar pattern to React components.
We will write a new function called `withSubscription(WrappedComponent)`. Its argument could be any React component. We will pass `CommentList` as `WrappedComponent`, but we could also apply `withSubscription()` to any other component in our codebase.
This function would return another component. The returned component would manage the subscription and render `<WrappedComponent />` with the current data.
We call this pattern a “higher-order component”.
The composition happens at React rendering level rather than with a direct function call. This is why it doesnt matter whether the wrapped component is defined with `createClass()`, as an ES6 class or a function. If `WrappedComponent` is a React component, the component created by `withSubscription()` can render it.
```js
// This function takes a component...
function withSubscription(WrappedComponent) {
// ...and returns another component...
return React.createClass({
getInitialState: function() {
return {
comments: DataSource.getComments()
};
},
componentDidMount: function() {
// ... that takes care of the subscription...
DataSource.addChangeListener(this.handleChange);
},
componentWillUnmount: function() {
DataSource.removeChangeListener(this.handleChange);
},
handleChange: function() {
this.setState({
comments: DataSource.getComments()
});
},
render: function() {
// ... and renders the wrapped component with the fresh data!
return <WrappedComponent comments={this.state.comments} />;
}
});
}
```
Now we can declare `CommentListWithSubscription` by applying `withSubscription` to `CommentList`:
```js
var CommentList = React.createClass({
render: function() {
var comments = this.props.comments;
return (
<div>
{comments.map(function(comment) {
return <Comment comment={comment} key={comment.id} />
})}
</div>
)
}
});
// withSubscription() returns a new component that
// is subscribed to the data source and renders
// <CommentList /> with up-to-date data.
var CommentListWithSubscription = withSubscription(CommentList);
// The rest of the app is interested in the subscribed component
// so we export it instead of the original unwrapped CommentList.
module.exports = CommentListWithSubscription;
```
#### Solution, Revisited
Now that we understand higher-order components better, lets take another look at the complete solution that doesnt involve mixins. There are a few minor changes that are annotated with inline comments:
```js
function withSubscription(WrappedComponent) {
return React.createClass({
getInitialState: function() {
return {
comments: DataSource.getComments()
};
},
componentDidMount: function() {
DataSource.addChangeListener(this.handleChange);
},
componentWillUnmount: function() {
DataSource.removeChangeListener(this.handleChange);
},
handleChange: function() {
this.setState({
comments: DataSource.getComments()
});
},
render: function() {
// Use JSX spread syntax to pass all props and state down automatically.
return <WrappedComponent {...this.props} {...this.state} />;
}
});
}
// Optional change: convert CommentList to a functional component
// because it doesn't use lifecycle hooks or state.
function CommentList(props) {
var comments = props.comments;
return (
<div>
{comments.map(function(comment) {
return <Comment comment={comment} key={comment.id} />
})}
</div>
)
}
// Instead of declaring CommentListWithSubscription,
// we export the wrapped component right away.
module.exports = withSubscription(CommentList);
```
Higher-order components are a powerful pattern. You can pass additional arguments to them if you want to further customize their behavior. After all, they are not even a feature of React. They are just functions that receive components and return components that wrap them.
Like any solution, higher-order components have their own pitfalls. For example, if you heavily use [refs](/react/docs/more-about-refs.html), you might notice that wrapping something into a higher-order component changes the ref to point to the wrapping component. In practice we discourage using refs for component communication so we dont think its a big issue. In the future, we might consider adding [ref forwarding](https://github.com/facebook/react/issues/4213) to React to solve this annoyance.
### Rendering Logic
The next most common use case for mixins that we discovered in our codebase is sharing rendering logic between components.
Here is a typical example of this pattern:
```js
var RowMixin = {
// Called by components from render()
renderHeader: function() {
return (
<div className='row-header'>
<h1>
{this.getHeaderText() /* Defined by components */}
</h1>
</div>
);
}
};
var UserRow = React.createClass({
mixins: [RowMixin],
// Called by RowMixin.renderHeader()
getHeaderText: function() {
return this.props.user.fullName;
},
render: function() {
return (
<div>
{this.renderHeader() /* Defined by RowMixin */}
<h2>{this.props.user.biography}</h2>
</div>
)
}
});
```
Multiple components may be sharing `RowMixin` to render the header, and each of them would need to define `getHeaderText()`.
#### Solution
If you see rendering logic inside a mixin, its time to extract a component!
Instead of `RowMixin`, we will define a `<Row>` component. We will also replace the convention of defining a `getHeaderText()` method with the standard mechanism of top-data flow in React: passing props.
Finally, since neither of those components currently need lifecycle hooks or state, we can declare them as simple functions:
```js
function RowHeader(props) {
return (
<div className='row-header'>
<h1>{props.text}</h1>
</div>
);
}
function UserRow(props) {
return (
<div>
<RowHeader text={props.user.fullName} />
<h2>{props.user.biography}</h2>
</div>
);
}
```
Props keep component dependencies explicit, easy to replace, and enforceable with tools like [Flow](https://flowtype.org/) and [TypeScript](https://www.typescriptlang.org/).
> **Note:**
>
> Defining components as functions is not required. There is also nothing wrong with using lifecycle hooks and state—they are first-class React features. We use functional components in this example because they are easier to read and we didnt need those extra features, but classes would work just as fine.
### Context
Another group of mixins we discovered were helpers for providing and consuming [React context](/react/docs/context.html). Context is an experimental unstable feature, has [certain issues](https://github.com/facebook/react/issues/2517), and will likely change its API in the future. We dont recommend using it unless youre confident there is no other way of solving your problem.
Nevertheless, if you already use context today, you might have been hiding its usage with mixins like this:
```js
var RouterMixin = {
contextTypes: {
router: React.PropTypes.object.isRequired
},
// The mixin provides a method so that components
// don't have to use the context API directly.
push: function(path) {
this.context.router.push(path)
}
};
var Link = React.createClass({
mixins: [RouterMixin],
handleClick: function(e) {
e.stopPropagation();
// This method is defined in RouterMixin.
this.push(this.props.to);
},
render: function() {
return (
<a onClick={this.handleClick}>
{this.props.children}
</a>
);
}
});
module.exports = Link;
```
#### Solution
We agree that hiding context usage from consuming components is a good idea until the context API stabilizes. However, we recommend using higher-order components instead of mixins for this.
Let the wrapping component grab something from the context, and pass it down with props to the wrapped component:
```js
function withRouter(WrappedComponent) {
return React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
render: function() {
// The wrapper component reads something from the context
// and passes it down as a prop to the wrapped component.
var router = this.context.router;
return <WrappedComponent {...this.props} router={router} />;
}
});
};
var Link = React.createClass({
handleClick: function(e) {
e.stopPropagation();
// The wrapped component uses props instead of context.
this.props.router.push(this.props.to);
},
render: function() {
return (
<a onClick={this.handleClick}>
{this.props.children}
</a>
);
}
});
// Don't forget to wrap the component!
module.exports = withRouter(Link);
```
If youre using a third party library that only provides a mixin, we encourage you to file an issue with them linking to this post so that they can provide a higher-order component instead. In the meantime, you can create a higher-order component around it yourself in exactly the same way.
### Utility Methods
Sometimes, mixins are used solely to share utility functions between components:
```js
var ColorMixin = {
getLuminance(color) {
var c = parseInt(color, 16);
var r = (c & 0xFF0000) >> 16;
var g = (c & 0x00FF00) >> 8;
var b = (c & 0x0000FF);
return (0.299 * r + 0.587 * g + 0.114 * b);
}
};
var Button = React.createClass({
mixins: [ColorMixin],
render: function() {
var theme = this.getLuminance(this.props.color) > 160 ? 'dark' : 'light';
return (
<div className={theme}>
{this.props.children}
</div>
)
}
});
```
#### Solution
Put utility functions into regular JavaScript modules and import them. This also makes it easier to test them or use them outside of your components:
```js
var getLuminance = require('../utils/getLuminance');
var Button = React.createClass({
render: function() {
var theme = getLuminance(this.props.color) > 160 ? 'dark' : 'light';
return (
<div className={theme}>
{this.props.children}
</div>
)
}
});
```
### Other Use Cases
Sometimes people use mixins to selectively add logging to lifecycle hooks in some components. In the future, we intend to provide an [official DevTools API](https://github.com/facebook/react/issues/5306) that would let you implement something similar without touching the components. However its still very much a work in progress. If you heavily depend on logging mixins for debugging, you might want to keep using those mixins for a little longer.
If you cant accomplish something with a component, a higher-order component, or a utility module, it could be mean that React should provide this out of the box. [File an issue](https://github.com/facebook/react/issues/new) to tell us about your use case for mixins, and well help you consider alternatives or perhaps implement your feature request.
Mixins are not deprecated in the traditional sense. You can keep using them with `React.createClass()`, as we wont be changing it further. Eventually, as ES6 classes gain more adoption and their usability problems in React are solved, we might split `React.createClass()` into a separate package because most people wouldnt need it. Even in that case, your old mixins would keep working.
We believe that the alternatives above are better for the vast majority of cases, and we invite you to try writing React apps without using mixins.

View File

@@ -0,0 +1,165 @@
---
title: "Create Apps with No Configuration"
author: gaearon
---
**[Create React App](https://github.com/facebookincubator/create-react-app)** is a new officially supported way to create single-page React applications. It offers a modern build setup with no configuration.
## Getting Started
### Installation
First, install the global package:
```sh
npm install -g create-react-app
```
Node.js 4.x or higher is required.
### Creating an App
Now you can use it to create a new app:
```sh
create-react-app hello-world
```
This will take a while as npm installs the transitive dependencies, but once its done, you will see a list of commands you can run in the created folder:
![created folder](/react/img/blog/create-apps-with-no-configuration/created-folder.png)
### Starting the Server
Run `npm start` to launch the development server. The browser will open automatically with the created apps URL.
![compiled successfully](/react/img/blog/create-apps-with-no-configuration/compiled-successfully.png)
Create React App uses both Webpack and Babel under the hood.
The console output is tuned to be minimal to help you focus on the problems:
![failed to compile](/react/img/blog/create-apps-with-no-configuration/failed-to-compile.png)
ESLint is also integrated so lint warnings are displayed right in the console:
![compiled with warnings](/react/img/blog/create-apps-with-no-configuration/compiled-with-warnings.png)
We only picked a small subset of lint rules that often lead to bugs.
### Building for Production
To build an optimized bundle, run `npm run build`:
![npm run build](/react/img/blog/create-apps-with-no-configuration/npm-run-build.png)
It is minified, correctly envified, and the assets include content hashes for caching.
### One Dependency
Your `package.json` contains only a single build dependency and a few scripts:
```js
{
"name": "hello-world",
"dependencies": {
"react": "^15.2.1",
"react-dom": "^15.2.1"
},
"devDependencies": {
"react-scripts": "0.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject"
}
}
```
We take care of updating Babel, ESLint, and Webpack to stable compatible versions so you can update a single dependency to get them all.
### Zero Configuration
It is worth repeating: there are no configuration files or complicated folder structures. The tool only generates the files you need to build your app.
```
hello-world/
README.md
index.html
favicon.ico
node_modules/
package.json
src/
App.css
App.js
index.css
index.js
logo.svg
```
All the build settings are preconfigured and cant be changed. Some features, such as testing, are currently missing. This is an intentional limitation, and we recognize it might not work for everybody. And this brings us to the last point.
### No Lock-In
We first saw this feature in [Enclave](https://github.com/eanplatter/enclave), and we loved it. We talked to [Ean](https://twitter.com/EanPlatter), and he was excited to collaborate with us. He already sent a few pull requests!
“Ejecting” lets you leave the comfort of Create React App setup at any time. You run a single command, and all the build dependencies, configs, and scripts are moved right into your project. At this point you can customize everything you want, but effectively you are forking our configuration and going your own way. If youre experienced with build tooling and prefer to fine-tune everything to your taste, this lets you use Create React App as a boilerplate generator.
We expect that at early stages, many people will “eject” for one reason or another, but as we learn from them, we will make the default setup more and more compelling while still providing no configuration.
## Try It Out!
You can find [**Create React App**](https://github.com/facebookincubator/create-react-app) with additional instructions on GitHub.
This is an experiment, and only time will tell if it becomes a popular way of creating and building React apps, or fades into obscurity.
We welcome you to participate in this experiment. Help us build the React tooling that more people can use. We are always [open to feedback](https://github.com/facebookincubator/create-react-app/issues/11).
## The Backstory
React was one of the first libraries to embrace transpiling JavaScript. As a result, even though you can [learn React without any tooling](https://github.com/facebook/react/blob/3fd582643ef3d222a00a0c756292c15b88f9f83c/examples/basic-jsx/index.html), the React ecosystem has commonly become associated with an overwhelming explosion of tools.
Eric Clemmons called this phenomenon the “[JavaScript Fatigue](https://medium.com/@ericclemmons/javascript-fatigue-48d4011b6fc4)”:
>Ultimately, the problem is that by choosing React (and inherently JSX), youve unwittingly opted into a confusing nest of build tools, boilerplate, linters, & time-sinks to deal with before you ever get to create anything.
It is tempting to write code in ES2015 and JSX. It is sensible to use a bundler to keep the codebase modular, and a linter to catch the common mistakes. It is nice to have a development server with fast rebuilds, and a command to produce optimized bundles for production.
Combining these tools requires some experience with each of them. Even so, it is far too easy to get dragged into fighting small incompatibilities, unsatisfied peerDependencies, and illegible configuration files.
Many of those tools are plugin platforms and dont directly acknowledge each others existence. They leave it up to the users to wire them together. The tools mature and change independently, and tutorials quickly get out of date.
<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">Marc was almost ready to implement his &quot;hello world&quot; React app <a href="https://t.co/ptdg4yteF1">pic.twitter.com/ptdg4yteF1</a></p>&mdash; Thomas Fuchs (@thomasfuchs) <a href="https://twitter.com/thomasfuchs/status/708675139253174273">March 12, 2016</a></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
This doesnt mean those tools arent great. To many of us, they have become indispensable, and we very much appreciate the effort of their maintainers. They already have too much on their plates to worry about the state of the React ecosystem.
Still, we knew it was frustrating to spend days setting up a project when all you wanted was to learn React. We wanted to fix this.
## Could We Fix This?
We found ourselves in an unusual dilemma.
So far, [our strategy](/react/contributing/design-principles.html#dogfooding) has been to only release the code that we are using at Facebook. This helped us ensure that every project is battle-tested and has clearly defined scope and priorities.
However, tooling at Facebook is different than at many smaller companies. Linting, transpilation, and packaging are all handled by powerful remote development servers, and product engineers dont need to configure them. While we wish we could give a dedicated server to every user of React, even Facebook cannot scale that well!
The React community is very important to us. We knew that we couldnt fix the problem within the limits of our open source philosophy. This is why we decided to make an exception, and to ship something that we didnt use ourselves, but that we thought would be useful to the community.
## The Quest for a React <abbr title="Command Line Interface">CLI</abbr>
Having just attended [EmberCamp](http://embercamp.com/) a week ago, I was excited about [Ember CLI](https://ember-cli.com/). Ember users have a great “getting started” experience thanks to a curated set of tools united under a single command-line interface. I have heard similar feedback about [Elm Reactor](https://github.com/elm-lang/elm-reactor).
Providing a cohesive curated experience is valuable by itself, even if the user could in theory assemble those parts themselves. Kathy Sierra [explains it best](http://seriouspony.com/blog/2013/7/24/your-app-makes-me-fat):
>If your UX asks the user to make *choices*, for example, even if those choices are both clear and useful, the act of *deciding* is a cognitive drain. And not just *while* theyre deciding... even *after* we choose, an unconscious cognitive background thread is slowly consuming/leaking resources, “Was *that* the right choice?”
I never tried to write a command-line tool for React apps, and neither has [Christopher](https://twitter.com/vjeux). We were chatting on Messenger about this idea, and we decided to work together on it for a week as a hackathon project.
We knew that such projects traditionally havent been very successful in the React ecosystem. Christopher told me that multiple “React CLI” projects have started and failed at Facebook. The community tools with similar goals also exist, but so far they have not yet gained enough traction.
Still, we decided it was worth another shot. Christopher and I created a very rough proof of concept on the weekend, and [Kevin](https://twitter.com/lacker) soon joined us.
We invited some of the community members to collaborate with us, and we have spent this week working on this tool. We hope that youll enjoy using it! [Let us know what you think.](https://github.com/facebookincubator/create-react-app/issues/11)
We would like to express our gratitude to [Max Stoiber](https://twitter.com/mxstbr), [Jonny Buchanan](https://twitter.com/jbscript), [Ean Platter](https://twitter.com/eanplatter), [Tyler McGinnis](https://github.com/tylermcginnis), [Kent C. Dodds](https://github.com/kentcdodds), and [Eric Clemmons](https://twitter.com/ericclemmons) for their early feedback, ideas, and contributions.

View File

@@ -2,6 +2,7 @@
id: acknowledgements
title: Acknowledgements
layout: single
permalink: acknowledgements.html
---
We'd like to thank all of our contributors:

View File

@@ -0,0 +1,162 @@
---
id: design-principles
title: Design Principles
layout: contributing
permalink: contributing/design-principles.html
---
After using React in a couple of applications, you might be interested in contributing to React. Before [diving into specifics](https://github.com/facebook/react/blob/master/CONTRIBUTING.md), we think it's important to establish a few design principles guiding our decisions about changes in React.
We wrote this document so that you have a better idea of how we decide what React does and what React doesn't do, and what our development philosophy is like. While we are excited to see community contributions, we are not likely to choose a path that violates one or more of these principles.
>**Note:**
>
>This document assumes a strong understanding of React. It describes the design principles of *React itself*, not React components or applications.
>
>For an introduction to React, check out [Thinking in React](/react/docs/thinking-in-react.html) instead.
### Composition
The key feature of React is composition of components. Components written by different people should work well together. It is important to us that you can add functionality to a component without causing rippling changes throughout the codebase.
For example, it should be possible to introduce some local state into a component without changing any of the components using it. Similarly, it should be possible to add some initialization and teardown code to any component when necessary.
There is nothing "bad" about using state or lifecycle hooks in components. Like any powerful features, they should be used in moderation, but we have no intention to remove them. On the contrary, we think they are integral parts of what makes React useful. We might enable [more functional patterns](https://github.com/reactjs/react-future/tree/master/07%20-%20Returning%20State) in the future, but both local state and lifecycle hooks will be a part of that model.
Components are often described as "just functions" but in our view they need to be more than that to be useful. In React, components describe any composable behavior, and this includes rendering, lifecycle, and state. Some external libraries like [Relay](http://facebook.github.io/relay/) augment components with other responsibilities such as describing data dependencies. It is possible that those ideas might make it back into React too in some form.
### Common Abstraction
In general we [resist adding features](https://www.youtube.com/watch?v=4anAwXYqLG8) that can be implemented in userland. We don't want to bloat your apps with useless library code. However, there are exceptions to this.
For example, if React didn't provide support for local state or lifecycle hooks, people would create custom abstractions for them. When there are multiple abstractions competing, React can't enforce or take advantage of the properties of either of them. It has to work with the lowest common denominator.
This is why sometimes we add features to React itself. If we notice that many components implement a certain feature in incompatible or inefficient ways, we might prefer to bake it into React. We don't do it lightly. When we do it, it's because we are confident that raising the abstraction level benefits the whole ecosystem. State, lifecycle hooks, cross-browser event normalization are good examples of this.
We always discuss such improvement proposals with the community. You can find some of those discussions by the [“big picture”](https://github.com/facebook/react/issues?q=is%3Aopen+is%3Aissue+label%3A%22big+picture%22) label on the React issue tracker.
### Escape Hatches
React is pragmatic. It is driven by the needs of the products written at Facebook. While it is influenced by some paradigms that are not yet fully mainstream such as functional programming, staying accessible to a wide range of developers with different skills and experience levels is an explicit goal of the project.
If we want to deprecate a pattern that we don't like, it is our responsibility to consider all existing use cases for it and [educate the community about the alternatives](/react/blog/2016/07/13/mixins-considered-harmful.html) before we deprecate it. If some pattern that is useful for building apps is hard to express in a declarative way, we will [provide an imperative API](/react/docs/more-about-refs.html) for it. If we can't figure out a perfect API for something that we found necessary in many apps, we will [provide a temporary subpar working API](/react/docs/context.html) as long as it is possible to get rid of it later and it leaves the door open for future improvements.
### Stability
We value API stability. At Facebook, we have more than 20 thousand components using React. Many other companies, including [Twitter](https://twitter.com/) and [Airbnb](https://www.airbnb.com/), are also heavy users of React. This is why we are usually reluctant to change public APIs or behavior.
However we think stability in the sense of "nothing changes" is overrated. It quickly turns into stagnation. Instead, we prefer the stability in the sense of "It is heavily used in production, and when something changes, there is a clear (and preferably automated) migration path."
When we deprecate a pattern, we study its internal usage at Facebook and add deprecation warnings. They let us assess the impact of the change. Sometimes we back out if we see that it is too early, and we need to think more strategically about getting the codebases to the point where they are ready for this change.
If we are confident that the change is not too disruptive and the migration strategy is viable for all use cases, we release the deprecation warning to the open source community. We are closely in touch with many users of React outside of Facebook, and we monitor popular open source projects and guide them in fixing those deprecations.
Given the sheer size of the Facebook React codebase, successful internal migration is often a good indicator that other companies won't have problems either. Nevertheless sometimes people point out additional use cases we haven't thought of, and we add escape hatches for them or rethink our approach.
We don't deprecate anything without a good reason. We recognize that sometimes deprecations warnings cause frustration but we add them because deprecations clean up the road for the improvements and new features that we and many people in the community consider valuable.
For example, we added a [warning about unknown DOM props](/react/warnings/unknown-prop.html) in React 15.2.0. Many projects were affected by this. However fixing this warning is important so that we can introduce the support for [custom attributes](https://github.com/facebook/react/issues/140) to React. There is a reason like this behind every deprecation that we add.
When we add a deprecation warning, we keep it for the rest of the current major version, and [change the behavior in the next major version](/react/blog/2016/02/19/new-versioning-scheme.html). If there is a lot of repetitive manual work involved, we release a [codemod](https://www.youtube.com/watch?v=d0pOgY8__JM) script that automates most of the change. Codemods enable us to move forward without stagnation in a massive codebase, and we encourage you to use them as well.
You can find the codemods that we released in the [react-codemod](https://github.com/reactjs/react-codemod) repository.
### Interoperability
We place high value in interoperability with existing systems and gradual adoption. Facebook has a massive non-React codebase. Its website uses a mix of a server-side component system called XHP, internal UI libraries that came before React, and React itself. It is important to us that any product team can [start using React for a small feature](https://www.youtube.com/watch?v=BF58ZJ1ZQxY) rather than rewrite their code to bet on it.
This is why React provides escape hatches to work with mutable models, and tries to work well together with other UI libraries. You can wrap an existing imperative UI into a declarative component, and vice versa. This is crucial for gradual adoption.
### Scheduling
Even when your components are described as functions, when you use React you don't call them directly. Every component returns a [description of what needs to be rendered](/react/blog/2015/12/18/react-components-elements-and-instances.html#elements-describe-the-tree), and that description may include both user-written components like `<LikeButton>` and platform-specific components like `<div>`. It is up to React to "unroll" `<LikeButton>` at some point in the future and actually apply changes to the UI tree according to the render results of the components recursively.
This is a subtle distinction but a powerful one. Since you don't call that component function but let React call it, it means React has the power to delay calling it if necessary. In its current implementation React walks the tree recursively and calls render functions of the whole updated tree during a single tick. However in the future it might start [delaying some updates to avoid dropping frames](https://github.com/facebook/react/issues/6170).
This is a common theme in React design. Some popular libraries implement the "push" approach where computations are performed when the new data is available. React, however, sticks to the "pull" approach where computations can be delayed until necessary.
React is not a generic data processing library. It is a library for building user interfaces. We think that it is uniquely positioned in an app to know which computations are relevant right now and which are not.
If something is offscreen, we can delay any logic related to it. If data is arriving faster than the frame rate, we can coalesce and batch updates. We can prioritize work coming from user interactions (such as an animation caused by a button click) over less important background work (such as rendering new content just loaded from the network) to avoid dropping frames.
To be clear, we are not taking advantage of this right now. However the freedom to do something like this is why we prefer to have control over scheduling, and why `setState()` is asynchronous. Conceptually, we think of it as "scheduling an update".
The control over scheduling would be harder for us to gain if we let the user directly compose views with a "push" based paradigm common in some variations of [Functional Reactive Programming](https://en.wikipedia.org/wiki/Functional_reactive_programming). We want to own the "glue" code.
It is a key goal for React that the amount of the user code that executes before yielding back into React is minimal. This ensures that React retains the capability to schedule and split work in chunks according to what it knows about the UI.
There is an internal joke in the team that React should have been called "Schedule" because React does not want to be fully "reactive".
### Developer Experience
Providing a good developer experience is important to us.
For example, we maintain [React DevTools](https://github.com/facebook/react-devtools) which let you inspect the React component tree in Chrome and Firefox. We have heard that it brings a big productivity boost both to the Facebook engineers and to the community.
We also try to go an extra mile to provide helpful developer warnings. For example, React warns you in development if you nest tags in a way that the browser doesn't understand, or if you make a common typo in the API. Developer warnings and the related checks are the main reason why the development version of React is slower than the production version.
The usage patterns that we see internally at Facebook help us understand what the common mistakes are, and how to prevent them early. When we add new features, we try to anticipate the common mistakes and warn about them.
We are always looking out for ways to improve the developer experience. We love to hear your suggestions and accept your contributions to make it even better.
### Debugging
When something goes wrong, it is important that you have breadcrumbs to trace the mistake to its source in the codebase. In React, props and state are those breadcrumbs.
If you see something wrong on the screen, you can open React DevTools, find the component responsible for rendering, and then see if the props and state are correct. If they are, you know that the problem is in the components `render()` function, or some function that is called by `render()`. The problem is isolated.
If the state is wrong, you know that the problem is caused by one of the `setState()` calls in this file. This, too, is relatively simple to locate and fix because usually there are only a few `setState()` calls in a single file.
If the props are wrong, you can traverse the tree up in the inspector, looking for the component that first "poisoned the well" by passing bad props down.
This ability to trace any UI to the data that produced it in the form of current props and state is very important to React. It is an explicit design goal that state is not "trapped" in closures and combinators, and is available to React directly.
While the UI is dynamic, we believe that synchronous `render()` functions of props and state turn debugging from guesswork into a boring but finite procedure. We would like to preserve this constraint in React even though it makes some use cases, like complex animations, harder.
### Configuration
We find global runtime configuration options to be problematic.
For example, it is occasionally requested that we implement a function like `React.configure(options)` or `React.register(component)`. However this poses multiple problems, and we are not aware of good solutions to them.
What if somebody calls such a function from a third-party component library? What if one React app embeds another React app, and their desired configurations are incompatible? How can a third-party component specify that it requires a particular configuration? We think that global configuration doesn't work well with composition. Since composition is central to React, we don't provide global configuration in code.
We do, however, provide some global configuration on the build level. For example, we provide separate development and production builds. We may also [add a profiling build](https://github.com/facebook/react/issues/6627) in the future, and we are open to considering other build flags.
### Beyond the DOM
We see the value of React in the way it allows us to write components that have less bugs and compose together well. DOM is the original rendering target for React but [React Native](http://facebook.github.io/react-native/) is just as important both to Facebook and the community.
Being renderer-agnostic is an important design constraint of React. It adds some overhead in the internal representations. On the other hand, any improvements to the core translate across platforms.
Having a single programming model lets us form engineering teams around products instead of platforms. So far the tradeoff has been worth it for us.
### Implementation
We try to provide elegant APIs where possible. We are much less concerned with the implementation being elegant. The real world is far from perfect, and to a reasonable extent we prefer to put the ugly code into the library if it means the user does not have to write it. When we evaluate new code, we are looking for an implementation that is correct, performant and affords a good developer experience. Elegance is secondary.
We prefer boring code to clever code. Code is disposable and often changes. So it is important that it [doesn't introduce new internal abstractions unless absolutely necessary](https://youtu.be/4anAwXYqLG8?t=13m9s). Verbose code that is easy to move around, change and remove is preferred to elegant code that is prematurely abstracted and hard to change.
### Optimized for Tooling
Some commonly used APIs have verbose names. For example, we use `componentDidMount()` instead of `didMount()` or `onMount()`. This is [intentional](https://github.com/reactjs/react-future/issues/40#issuecomment-142442124). The goal is to make the points of interaction with the library highly visible.
In a massive codebase like Facebook, being able to search for uses of specific APIs is very important. We value distinct verbose names, and especially for the features that should be used sparingly. For example, `dangerouslySetInnerHTML` is hard to miss in a code review.
Optimizing for search is also important because of our reliance on [codemods](https://www.youtube.com/watch?v=d0pOgY8__JM) to make breaking changes. We want it to be easy and safe to apply vast automated changes across the codebase, and unique verbose names help us achieve this. Similarly, distinctive names make it easy to write custom [lint rules](https://github.com/yannickcr/eslint-plugin-react) about using React without worrying about potential false positives.
[JSX](/react/docs/displaying-data.html#jsx-syntax) plays a similar role. While it is not required with React, we use it extensively at Facebook both for aesthetic and pragmatic reasons.
In our codebase, JSX provides an unambigious hint to the tools that they are dealing with a React element tree. This makes it possible to add build-time optimizations such as [hoisting constant elements](http://babeljs.io/docs/plugins/transform-react-constant-elements/), safely lint and codemod internal component usage, and [include JSX source location](https://github.com/facebook/react/pull/6771) into the warnings.
### Dogfooding
We try our best to address the problems raised by the community. However we are likely to prioritize the issues that people are *also* experiencing internally at Facebook. Perhaps counter-intuitively, we think this is the main reason why the community can bet on React.
Heavy internal usage gives us the confidence that React won't disappear tomorrow. React was created at Facebook to solve its problems. It brings tangible business value to the company and is used in many of its products. [Dogfooding](https://en.wikipedia.org/wiki/Eating_your_own_dog_food) it means that our vision stays sharp and we have a focused direction going forward.
This doesn't mean that we ignore the issues raised by the community. For example, we added support for [web components](/react/docs/webcomponents.html) and [SVG](https://github.com/facebook/react/pull/6243) to React even though we don't rely on either of them internally. We are actively [listening to your pain points](https://github.com/facebook/react/issues/2686) and [address them](/react/blog/2016/07/11/introducing-reacts-error-code-system.html) to the best of our ability. The community is what makes React special to us, and we are honored to contribute back.
After releasing many open source projects at Facebook, we have learned that trying to make everyone happy at the same time produced projects with poor focus that didn't grow well. Instead, we found that picking a small audience and focusing on making them happy brings a positive net effect. That's exactly what we did with React, and so far solving the problems encountered by Facebook product teams has translated well to the open source community.
The downside of this approach is that sometimes we fail to give enough focus to the things that Facebook teams don't have to deal with, such as the "getting started" experience. We are acutely aware of this, and we are thinking of how to improve in a way that would benefit everyone in the community without making the same mistakes we did with open source projects before.

View File

@@ -1,7 +1,7 @@
---
id: why-react-de-DE
title: Warum React?
permalink: why-react-de-DE.html
permalink: docs/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.

View File

@@ -1,7 +1,7 @@
---
id: why-react-it-IT
title: Perché React?
permalink: why-react-it-IT.html
permalink: docs/why-react-it-IT.html
next: displaying-data-it-IT.html
---
React è una libreria JavaScript per creare interfacce utente scritta da Facebook e Instagram. A molti piace pensare a React come alla **V** di **[MVC](https://it.wikipedia.org/wiki/Model-View-Controller)**.

View File

@@ -1,7 +1,7 @@
---
id: why-react-ja-JP
title: なぜReactを使うのでしょうか
permalink: why-react-ja-JP.html
permalink: docs/why-react-ja-JP.html
next: displaying-data-ja-JP.html
---

View File

@@ -1,7 +1,7 @@
---
id: why-react-ko-KR
title: 왜 React인가?
permalink: why-react-ko-KR.html
permalink: docs/why-react-ko-KR.html
next: displaying-data-ko-KR.html
---

View File

@@ -1,7 +1,7 @@
---
id: why-react
title: Why React?
permalink: why-react.html
permalink: docs/why-react.html
next: displaying-data.html
---
React is a JavaScript library for creating user interfaces by Facebook and Instagram. Many people choose to think of React as the **V** in **[MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)**.

View File

@@ -1,7 +1,7 @@
---
id: why-react-ru-RU
title: Почему именно React?
permalink: why-react-ru-RU.html
permalink: docs/why-react-ru-RU.html
next: displaying-data-ru-RU.html
---
React — библиотека JavaScript для создания интерфейсов от команд Facebook и Instagram. Многие ассоциируют React с понятием **View** в паттерне **[MVC](https://ru.wikipedia.org/wiki/Model-View-Controller)**.

View File

@@ -1,7 +1,7 @@
---
id: why-react-zh-CN
title: 为什么使用 React?
permalink: why-react-zh-CN.html
permalink: docs/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**(视图)。

View File

@@ -1,7 +1,7 @@
---
id: why-react-zh-TW
title: Why React?
permalink: why-react-zh-TW.html
permalink: docs/why-react-zh-TW.html
next: displaying-data.html
---
React是Facebook和Instagram用來建立使用者介面的JavaScript函式庫. 很多人認為React就是處理 **[MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)**架構中 **V** 的部份.

View File

@@ -1,7 +1,7 @@
---
id: displaying-data-it-IT
title: Visualizzare Dati
permalink: displaying-data-it-IT.html
permalink: docs/displaying-data-it-IT.html
prev: why-react-it-IT.html
next: jsx-in-depth-it-IT.html
---

View File

@@ -1,7 +1,7 @@
---
id: displaying-data-ja-JP
title: データを表示する
permalink: displaying-data-ja-JP.html
permalink: docs/displaying-data-ja-JP.html
prev: why-react-ja-JP.html
next: jsx-in-depth-ja-JP.html

View File

@@ -1,7 +1,7 @@
---
id: displaying-data-ko-KR
title: 데이터를 표시하기
permalink: displaying-data-ko-KR.html
permalink: docs/displaying-data-ko-KR.html
prev: why-react-ko-KR.html
next: jsx-in-depth-ko-KR.html
---

View File

@@ -1,7 +1,7 @@
---
id: displaying-data
title: Displaying Data
permalink: displaying-data.html
permalink: docs/displaying-data.html
prev: why-react.html
next: jsx-in-depth.html
---

View File

@@ -1,7 +1,7 @@
---
id: displaying-data-ru-RU
title: Отображение данных
permalink: displaying-data-ru-RU.html
permalink: docs/displaying-data-ru-RU.html
prev: why-react-ru-RU.html
next: jsx-in-depth.html
---

View File

@@ -1,7 +1,7 @@
---
id: displaying-data-zh-CN
title: 显示数据
permalink: displaying-data-zh-CN.html
permalink: docs/displaying-data-zh-CN.html
prev: why-react-zh-CN.html
next: jsx-in-depth-zh-CN.html
---

View File

@@ -0,0 +1,125 @@
---
id: displaying-data-zh-TW
title: Displaying Data
permalink: displaying-data-zh-TW.html
prev: why-react-zh-TW.html
next: jsx-in-depth-zh-TW.html
---
在使用者介面所能做最基本的事情就是呈現資料. React讓呈現資料變得更加容易並且當資料有所變動時也能自動地讓使用者介面保持呈現最新的資料.
## 入門(Getting Started)
我們從一個相當簡單的範例開始. 建立一個名為 `hello-react.html` 的檔案裡面包含下列程式碼:
```html
<!DOCTYPE html>
<html>
<head>
<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.34/browser.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
// ** 將你的程式碼放在這裡! **
</script>
</body>
</html>
```
這份文件其他部份,我們將只會專注在JavaScript程式碼解說上,並且假設程式碼會被放置在如上述模板的註解區塊內. 用下列的JSX程式碼取代上述註解區塊:
```javascript
var HelloWorld = React.createClass({
render: function() {
return (
<p>
Hello, <input type="text" placeholder="Your name here" />!
It is {this.props.date.toTimeString()}
</p>
);
}
});
setInterval(function() {
ReactDOM.render(
<HelloWorld date={new Date()} />,
document.getElementById('example')
);
}, 500);
```
## 反應性更新(Reactive Updates)
在一個瀏覽器上開啟檔案 `hello-react.html` 並且在文字區塊填入你的名字. 請注意React僅僅改變UI上的時間字串 — 你在文字區塊輸入的任何文字依舊存在, 即使你並沒有寫任何程式碼來管理這個行為.React可以為你分辨出這樣的行為並且做出正確的回應.
之所以能夠分辨出這樣的行為是因為React除非在真正有必要的情況下否則不會對DOM做任何操作. **它使用一個快速的, 內部虛擬的DOM(internal mock DOM)來為你施行比較和計算最有效率的DOM變動(DOM mutation)**
輸入到元件(component)的內容我們稱為`props` — 是屬性("properties")的簡稱. 他們在JSX語法中作為傳遞屬性之用. 你應該把這些屬性當做元件中不可被改變的, 也就是說, **永遠不要對 `this.props` 做寫入的行為**.
## 元件就是函數(Components are Just Like Functions)
React元件(components)是非常簡單的. 你能把它們想成是簡單的函數帶入`props``state`(後面會討論這部份)並且呈送給HTML(render HTML). 在心中保持住這個想法, 就能容易理解元件(components).
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.
> 注意(Note):
>
> **一個局限性**: React元件(components)只能呈送(render)給一個單一根節點(root node). 如果你想要回傳多個節點(multiple nodes)他們*必須*被包裹在單一根節點內.
## JSX語法
我們深信元件(components)才是分離關注點(separate concerns)的正確方法, 而並非傳統的模板("templates")和顯示邏輯("display logic")觀念. 我們認為標記(markup)和產生它的程式碼應當緊密的綁在一起. 另外, 顯示邏輯(display logic)常常是非常複雜的, 若使用模板語言(template languages)來詮釋它就顯得笨重或累贅.
我們找到解決這個問題的最佳解答就是直接在JavaScript程式內產生HTML和元件樹(component trees)如此一來你就能使用真正的程式語言的表達能力(expressive power)來建立使用者介面(UIs).
為了能更輕鬆實現, 我們增加了一個非常簡單, **可選擇性使用的** 類似HTML的語法(HTML-like syntax) 來創建這些React樹節點(React tree nodes).
**JSX能讓你使用HTML語法來創建JavaScript物件.** 在React裡使用純JavaScript來產生一個鏈接(link)你可以這樣寫:
`React.createElement('a', {href: 'https://facebook.github.io/react/'}, 'Hello!')`
使用JSX語法則變成:
`<a href="https://facebook.github.io/react/">Hello!</a>`
我們發現這麼做能讓建立React apps更加容易並且設計師往往喜歡語法, 但是每個人都有他們自己的工作流程, 所以**在使用React時JSX並非必要.**
JSX非常簡單易懂. 若想要學習更多關於JSX, 請參閱 [JSX in depth](/react/docs/jsx-in-depth.html). 或是可以使用線上及時轉換工具 [the Babel REPL](https://babeljs.io/repl/).
JSX類似於HTML, 但不盡然完全相同. 參閱 [JSX gotchas](/react/docs/jsx-gotchas.html) 來比較一些主要的差異點.
[Babel exposes a number of ways to get started using JSX](http://babeljs.io/docs/setup/), 涵蓋從命令列工具到Ruby on Rails整合. 可以從中選擇最適合你的工具.
## React不使用JSX的範例(React without JSX)
JSX完全是可選擇性使用的; 你可以不拿JSX跟React一起使用. 你能在純粹的JavaScript環境中使用`React.createElement`來創建React元素(React elements), 它搭配一個標籤名(tag name)或是元件(component), 一個屬性物件(properties object), 和數個選擇性子參數(child arguments).
```javascript
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'));
```
為了方便起見, 你能創建速記factory函式(short-hand factory functions)然後從自訂元件(custom components)建立元素(elements).
```javascript
var Factory = React.createFactory(ComponentClass);
...
var root = Factory({ custom: 'prop' });
ReactDOM.render(root, document.getElementById('example'));
```
針對一般的HTML標籤React已經有內建的factories函式:
```javascript
var root = React.DOM.ul({ className: 'my-list' },
React.DOM.li(null, 'Text Content')
);
```

View File

@@ -1,7 +1,7 @@
---
id: jsx-in-depth-it-IT
title: JSX in Profondità
permalink: jsx-in-depth-it-IT.html
permalink: docs/jsx-in-depth-it-IT.html
prev: displaying-data-it-IT.html
next: jsx-spread-it-IT.html
---

View File

@@ -1,7 +1,7 @@
---
id: jsx-in-depth
title: JSXの深層
permalink: jsx-in-depth-ja-JP.html
permalink: docs/jsx-in-depth-ja-JP.html
prev: displaying-data-ja-JP.html
next: jsx-spread-ja_JP.html
---

View File

@@ -1,7 +1,7 @@
---
id: jsx-in-depth-ko-KR
title: JSX 깊이보기
permalink: jsx-in-depth-ko-KR.html
permalink: docs/jsx-in-depth-ko-KR.html
prev: displaying-data-ko-KR.html
next: jsx-spread-ko-KR.html
---

View File

@@ -1,7 +1,7 @@
---
id: jsx-in-depth
title: JSX in Depth
permalink: jsx-in-depth.html
permalink: docs/jsx-in-depth.html
prev: displaying-data.html
next: jsx-spread.html
---

View File

@@ -1,7 +1,7 @@
---
id: jsx-in-depth-zh-CN
title: 深入 JSX
permalink: jsx-in-depth-zh-CN.html
permalink: docs/jsx-in-depth-zh-CN.html
prev: displaying-data-zh-CN.html
next: jsx-spread-zh-CN.html
---

View File

@@ -1,7 +1,7 @@
---
id: jsx-spread-it-IT
title: Attributi Spread JSX
permalink: jsx-spread-it-IT.html
permalink: docs/jsx-spread-it-IT.html
prev: jsx-in-depth-it-IT.html
next: jsx-gotchas-it-IT.html
---

View File

@@ -1,7 +1,7 @@
---
id: jsx-spread
title: JSXの拡張属性
permalink: jsx-spread-ja-JP.html
permalink: docs/jsx-spread-ja-JP.html
prev: jsx-in-depth-ja-JP.html
next: jsx-gotchas-ja-JP.html
---

View File

@@ -1,7 +1,7 @@
---
id: jsx-spread-ko-KR
title: JSX 스프레드 어트리뷰트
permalink: jsx-spread-ko-KR.html
permalink: docs/jsx-spread-ko-KR.html
prev: jsx-in-depth-ko-KR.html
next: jsx-gotchas-ko-KR.html
---

View File

@@ -1,7 +1,7 @@
---
id: jsx-spread
title: JSX Spread Attributes
permalink: jsx-spread.html
permalink: docs/jsx-spread.html
prev: jsx-in-depth.html
next: jsx-gotchas.html
---

View File

@@ -1,7 +1,7 @@
---
id: jsx-spread-zh-CN
title: JSX 展开属性
permalink: jsx-spread-zh-CN.html
permalink: docs/jsx-spread-zh-CN.html
prev: jsx-in-depth-zh-CN.html
next: jsx-gotchas-zh-CN.html
---

View File

@@ -1,7 +1,7 @@
---
id: jsx-gotchas-it-IT
title: JSX Gotchas
permalink: jsx-gotchas-it-IT.html
permalink: docs/jsx-gotchas-it-IT.html
prev: jsx-spread-it-IT.html
next: interactivity-and-dynamic-uis-it-IT.html
---

View File

@@ -1,7 +1,7 @@
---
id: jsx-gotchas
title: JSXの理解
permalink: jsx-gotchas-ja-JP.html
permalink: docs/jsx-gotchas-ja-JP.html
prev: jsx-spread-ja-JP.html
next: interactivity-and-dynamic-uis-ja-JP.html

View File

@@ -1,7 +1,7 @@
---
id: jsx-gotchas-ko-KR
title: JSX Gotchas
permalink: jsx-gotchas-ko-KR.html
permalink: docs/jsx-gotchas-ko-KR.html
prev: jsx-spread-ko-KR.html
next: interactivity-and-dynamic-uis-ko-KR.html
---

View File

@@ -1,7 +1,7 @@
---
id: jsx-gotchas
title: JSX Gotchas
permalink: jsx-gotchas.html
permalink: docs/jsx-gotchas.html
prev: jsx-spread.html
next: interactivity-and-dynamic-uis.html
---

View File

@@ -1,7 +1,7 @@
---
id: jsx-gotchas-zh-CN
title: JSX 陷阱
permalink: jsx-gotchas-zh-CN.html
permalink: docs/jsx-gotchas-zh-CN.html
prev: jsx-spread-zh-CN.html
next: interactivity-and-dynamic-uis-zh-CN.html
---

View File

@@ -1,7 +1,7 @@
---
id: interactivity-and-dynamic-uis-it-IT
title: Interattività e UI Dinamiche
permalink: interactivity-and-dynamic-uis-it-IT.html
permalink: docs/interactivity-and-dynamic-uis-it-IT.html
prev: jsx-gotchas-it-IT.html
next: multiple-components-it-IT.html
---

View File

@@ -1,7 +1,7 @@
---
id: interactivity-and-dynamic-uis
title: 相互作用と動的なUI
permalink: interactivity-and-dynamic-uis-ja-JP.html
permalink: docs/interactivity-and-dynamic-uis-ja-JP.html
prev: jsx-gotchas-ja-JP.html
next: multiple-components-ja-JP.html
---
@@ -20,7 +20,7 @@ var LikeButton = React.createClass({
this.setState({liked: !this.state.liked});
},
render: function() {
var text = this.state.liked ? 'like' : 'haven\'t liked';
var text = this.state.liked ? 'liked' : 'haven\'t liked';
return (
<p onClick={this.handleClick}>
You {text} this. Click to toggle.

View File

@@ -1,7 +1,7 @@
---
id: interactivity-and-dynamic-uis-ko-KR
title: 상호 작용 및 동적 UI
permalink: interactivity-and-dynamic-uis-ko-KR.html
permalink: docs/interactivity-and-dynamic-uis-ko-KR.html
prev: jsx-gotchas-ko-KR.html
next: multiple-components-ko-KR.html
---
@@ -19,7 +19,7 @@ var LikeButton = React.createClass({
this.setState({liked: !this.state.liked});
},
render: function() {
var text = this.state.liked ? 'like' : 'haven\'t liked';
var text = this.state.liked ? 'liked' : 'haven\'t liked';
return (
<p onClick={this.handleClick}>
You {text} this. Click to toggle.

View File

@@ -1,7 +1,7 @@
---
id: interactivity-and-dynamic-uis
title: Interactivity and Dynamic UIs
permalink: interactivity-and-dynamic-uis.html
permalink: docs/interactivity-and-dynamic-uis.html
prev: jsx-gotchas.html
next: multiple-components.html
---
@@ -23,7 +23,7 @@ class LikeButton extends React.Component {
this.setState({liked: !this.state.liked});
}
render() {
const text = this.state.liked ? 'like' : 'haven\'t liked';
const text = this.state.liked ? 'liked' : 'haven\'t liked';
return (
<div onClick={this.handleClick}>
You {text} this. Click to toggle.

View File

@@ -1,7 +1,7 @@
---
id: interactivity-and-dynamic-uis-ru-RU
title: Интерактивные и динамические интерфейсы
permalink: interactivity-and-dynamic-uis-ru-RU.html
permalink: docs/interactivity-and-dynamic-uis-ru-RU.html
prev: jsx-gotchas.html
next: multiple-components.html
---
@@ -19,7 +19,7 @@ var LikeButton = React.createClass({
this.setState({liked: !this.state.liked});
},
render: function() {
var text = this.state.liked ? 'like' : 'haven\'t liked';
var text = this.state.liked ? 'liked' : 'haven\'t liked';
return (
<p onClick={this.handleClick}>
You {text} this. Click to toggle.
@@ -63,10 +63,10 @@ React считает интерфейсы обыкновенными конеч
**Старайтесь делать компоненты без состояния.** Следуя этому правилу, вы будете выносить работу с состоянием с уровня представления в другие, более подходящие места. Тем самым, вы снизите сложность приложения, упрощая его понимание.
Основной принцип такой: создаются несколько компонентов без состояния, которые формируют дерево. Они будут заниматься только отрисовкой данных. А все данные для них будут у родительского компонента, который будет на вершине этого дерева компонентов. Он и будет передавать данные дочерним узлам через `props`. Этот компонент с общим состоянием содержит в себе всю логику взаимодействия, а дочерние компоненты будут только отрисовывать данные, которые будут у них в `props`.
## Какие данные *надо* помещать в состояние?
**Состояние должно содержать данные, которые нужны для обновления интерфейса.** В реальных приложениях такие данные, как правило, незначительны по объему, и могут быть сериализованы в JSON. Когда вы создаете компонент с состоянием, старайтесь поместить в него минимум данных. А уже внутри метода `render()` вычисляйте остальные данные, используя значения из состояния.
**Состояние должно содержать данные, которые нужны для обновления интерфейса.** В реальных приложениях такие данные, как правило, незначительны по объему, и могут быть сериализованы в JSON. Когда вы создаете компонент с состоянием, старайтесь поместить в него минимум данных. А уже внутри метода `render()` вычисляйте остальные данные, используя значения из состояния.
Со временем вы увидите, что такой подход позволяет создавать более стройные и устойчивые к изменениям приложения. Добавление в состояние лишних данных требует от вас дополнительных затрат на их синхронизацию. Но этого можно избежать, если позволить React делать все эти вычисления за вас.
## Какие данные *не надо* помещать в состояние?

View File

@@ -1,7 +1,7 @@
---
id: interactivity-and-dynamic-uis-zh-CN
title: 动态交互式用户界面
permalink: interactivity-and-dynamic-uis-zh-CN.html
permalink: docs/interactivity-and-dynamic-uis-zh-CN.html
prev: jsx-gotchas-zh-CN.html
next: multiple-components-zh-CN.html
---
@@ -19,7 +19,7 @@ var LikeButton = React.createClass({
this.setState({liked: !this.state.liked});
},
render: function() {
var text = this.state.liked ? 'like' : 'haven\'t liked';
var text = this.state.liked ? 'liked' : 'haven\'t liked';
return (
<p onClick={this.handleClick}>
You {text} this. Click to toggle.
@@ -42,9 +42,9 @@ React 里只需把事件处理器event handler以骆峰命名camelCased
在幕后React 做了一些操作来让代码高效运行且易于理解。
**Autobinding:** 在 JavaScript 里创建回调的时候,为了保证 `this` 的正确性,一般都需要显式地绑定方法到它的实例上。在 React所有方法被自动绑定到了它的组件实例上除非使用ES6的class符号。React 还缓存这些绑定方法,所以 CPU 和内存都是非常高效。而且还能减少打字!
**自动绑定:** 在 JavaScript 里创建回调的时候,为了保证 `this` 的正确性,一般都需要显式地绑定方法到它的实例上。在 React,所有方法被自动绑定到了它的组件实例上([除非使用ES6的class符号](/react/docs/reusable-components.html#no-autobinding)。React 还缓存这些绑定方法,所以 CPU 和内存都是非常高效。而且还能减少打字!
**事件代理 ** React 实际并没有把事件处理器绑定到节点本身。当 React 启动的时候它在最外层使用唯一一个事件监听器处理所有事件。当组件被加载和卸载时只是在内部映射里添加或删除事件处理器。当事件触发React 根据映射来决定如何分发。当映射里处理器时,会当作空操作处理。参考 [David Walsh 很棒的文章](http://davidwalsh.name/event-delegate) 了解这样做高效的原因。
**事件代理:** React 实际并没有把事件处理器绑定到节点本身。当 React 启动的时候它在最外层使用唯一一个事件监听器处理所有事件。当组件被加载和卸载时只是在内部映射里添加或删除事件处理器。当事件触发React 根据映射来决定如何分发。当映射里没有事件处理函数时,会当作空操作处理。参考 [David Walsh 很棒的文章](http://davidwalsh.name/event-delegate) 了解这样做高效的原因。
## 组件其实是状态机State Machines
@@ -54,7 +54,7 @@ React 里,只需更新组件的 state然后根据新的 state 重新渲染
## State 工作原理
常用的通知 React 数据变化的方法是调用 `setState(data, callback)`。这个方法会合并merge `data``this.state`,并重新渲染组件。渲染完成后,调用可选的 `callback` 回调。大部分情况下不需要提供 `callback`,因为 React 会负责把界面更新到最新状态。
常用的通知 React 数据变化的方法是调用 `setState(data, callback)`。这个方法会合并merge `data``this.state`,并重新渲染组件。重新渲染完成后,调用可选的 `callback` 回调。大部分情况下不需要提供 `callback`,因为 React 会负责把界面更新到最新状态。
## 哪些组件应该有 State
@@ -66,12 +66,12 @@ React 里,只需更新组件的 state然后根据新的 state 重新渲染
## 哪些 *应该* 作为 State
**State 应该包括那些可能被组件的事件处理器改变并触发用户界面更新的数据。** 真实的应用中这种数据一般都很小且能被 JSON 序列化。当创建一个状态化的组件时,想象一下表示它的状态最少需要哪些数据,并只把这些数据存入 `this.state`。在 `render()` 里再根据 state 来计算你需要的其它数据。你会发现以这种方式思考和开发程序最终往往是正确的,因为如果在 state 里添加冗余数据或计算所得数据,需要经常手动保持数据同步,不能让 React 来帮你处理。
**State 应该包括那些可能被组件的事件处理器改变并触发用户界面更新的数据。** 真实的应用中这种数据一般都很小且能被 JSON 序列化。当创建一个状态化的组件时,思考一下表示它的状态最少需要哪些数据,并只把这些数据存入 `this.state`。在 `render()` 里再根据 state 来计算你需要的其它数据。你会发现以这种方式思考和开发程序最终往往是正确的,因为如果在 state 里添加冗余数据或计算所得数据,那么你就需要经常手动保持数据同步,不能让 React 来帮你处理。
## 哪些 *不应该* 作为 State
`this.state` 应该仅包括能表示用户界面状态所需的最少数据。因,它不应该包括:
`this.state` 应该仅包括能表示用户界面状态所需的最少数据。因,它不应该包括:
* **计算所得数据:** 不要担心根据 state 来预先计算数据 —— 把所有的计算都放到 `render()` 里更容易保证用户界面和数据的一致性。例如,在 state 里有一个数组listItems我们要把数组长度渲染成字符串 直接在 `render()` 里使用 `this.state.listItems.length + ' list items'` 比把它放到 state 里好的多。
* **React 组件:** 在 `render()` 里使用当前 props 和 state 来创建它。
* **基于 props 的重复数据:** 尽可能使用 props 来作为实际状态的源。把 props 保存到 state 的一个有效的场景是需要知道它以前值的时候,因为 props 可能因为父组件重绘的结果而变化。
* **基于 props 的重复数据:** 尽可能使用 props 来作为实际状态的源。把 props 保存到 state 的一个有效的场景是需要知道它以前值的时候,因为 props 可能因为父组件重绘而变化。

View File

@@ -1,7 +1,7 @@
---
id: multiple-components-it-IT
title: Componenti Multipli
permalink: multiple-components-it-IT.html
permalink: docs/multiple-components-it-IT.html
prev: interactivity-and-dynamic-uis-it-IT.html
next: reusable-components-it-IT.html
---

View File

@@ -1,7 +1,7 @@
---
id: multiple-components
title: 複数のコンポーネント
permalink: multiple-components-ja-JP.html
permalink: docs/multiple-components-ja-JP.html
prev: interactivity-and-dynamic-uis-ja-JP.html
next: reusable-components-ja-JP.html
---

View File

@@ -1,7 +1,7 @@
---
id: multiple-components-ko-KR
title: 복합 컴포넌트
permalink: multiple-components-ko-KR.html
permalink: docs/multiple-components-ko-KR.html
prev: interactivity-and-dynamic-uis-ko-KR.html
next: reusable-components-ko-KR.html
---

View File

@@ -1,7 +1,7 @@
---
id: multiple-components
title: Multiple Components
permalink: multiple-components.html
permalink: docs/multiple-components.html
prev: interactivity-and-dynamic-uis.html
next: reusable-components.html
---

View File

@@ -1,7 +1,7 @@
---
id: multiple-components-zh-CN
title: 复合组件
permalink: multiple-components-zh-CN.html
permalink: docs/multiple-components-zh-CN.html
prev: interactivity-and-dynamic-uis-zh-CN.html
next: reusable-components-zh-CN.html
---
@@ -54,9 +54,9 @@ ReactDOM.render(
## 从属关系
上面例子中,`Avatar` 拥有 `PagePic``PageLink` 的实例。`拥有者` 就是给其它组件设置 `props` 的那个组件。更正式地说,如果组件 `Y``render()` 方法是创建了组件 `X`,那么 `Y` 就拥有 `X`。上面讲过,组件不能修改自身的 `props` - 它们总是与它们拥有者设置的保持一致。这是保持用户界面一致性的基本不变量。
上面例子中,`Avatar` 拥有 `PagePic``PageLink` 的实例。`拥有者` 就是给其它组件设置 `props` 的那个组件。更正式地说,如果组件 `Y``render()` 方法是创建了组件 `X`,那么 `Y` 就拥有 `X`。上面讲过,组件不能修改自身的 `props` - 它们总是与它们拥有者设置的保持一致。这是保持用户界面一致性的基本不变量。
把从属关系与父子关系加以区别至关重要。从属关系是 React 特有的而父子关系简单来讲就是DOM 里的标签的关系。在上一个例子中,`Avatar` 拥有 `div``PagePic``PageLink` 实例,`div``PagePic``PageLink` 实例的**父级**(但不是拥有者)。
把从属关系与父子关系加以区别至关重要。从属关系是 React 特有的,而父子关系简单来讲就是 DOM 里的标签的关系。在上一个例子中,`Avatar` 拥有 `div``PagePic``PageLink` 实例,`div``PagePic``PageLink` 实例的**父级**(但不是拥有者)。
## 子级
@@ -66,7 +66,7 @@ ReactDOM.render(
<Parent><Child /></Parent>
```
`Parent` 能通过专门的 `this.props.children` props 读取子级。**`this.props.children` 是一个不透明的数据结构:** 通过 [React.Children 工具类](/react/docs/top-level-api.html#react.children) 来操作。
`Parent` 能通过专门的 `this.props.children` prop 读取子级。**`this.props.children` 是一个不透明的数据结构:** 通过 [React.Children 工具类](/react/docs/top-level-api.html#react.children) 来操作。
### 子级校正Reconciliation
@@ -123,7 +123,8 @@ ReactDOM.render(
```
当 React 校正带有 key 的子级时,它会确保它们被重新排序(而不是破坏)或者删除(而不是重用)。
`务必``key` 添加到子级数组里组件本身上,而不是每个子级内部最外层 HTML 上:
务必把 `key` 添加到子级数组中的组件本身上,而不是数组中每个子级组件内部的最外层 HTML 上:
```javascript
// 错误!
@@ -164,11 +165,11 @@ var MyComponent = React.createClass({
});
```
也可以传递ReactFragment 对象 来做有 key 的子级。详见[Keyed Fragments](create-fragment.html)
也可以传递 ReactFragment 对象来做有 key 的子级。详见[Keyed Fragments](create-fragment.html)
## 数据流
React 里,数据通过上面介绍过的 `props` 从拥有者流向归属者。这就是高效的单向数据绑定(one-way data binding):拥有者通过它的 `props``state` 计算出一些值,并把这些值绑定到它们拥有的组件的 props 上。因为这个过程会递归地调用,所以数据变化会自动在所有被使用的地方自动反映出来。
React 里,数据通过上面介绍过的 `props` 从拥有者流向归属者。这就是高效的单向数据绑定(one-way data binding):拥有者通过它`props``state` 计算出一些值,并把这些值绑定到它们拥有的组件的 props 上。因为这个过程会递归地调用,所以数据变化会自动在所有它们被使用的地方反映出来。
## 性能提醒

View File

@@ -1,7 +1,7 @@
---
id: reusable-components-it-IT
title: Componenti Riutilizzabili
permalink: reusable-components-it-IT.html
permalink: docs/reusable-components-it-IT.html
prev: multiple-components-it-IT.html
next: transferring-props-it-IT.html
---
@@ -24,6 +24,7 @@ React.createClass({
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
optionalSymbol: React.PropTypes.symbol,
// Tutto ciò che può essere mostrato: numeri, stringhe, elementi, o un array
// (o frammento) contenente questi tipi.

View File

@@ -1,7 +1,7 @@
---
id: reusable-components
title: 再利用可能なコンポーネント
permalink: reusable-components-ja-JP.html
permalink: docs/reusable-components-ja-JP.html
prev: multiple-components-ja-JP.html
next: transferring-props-ja-JP.html
---
@@ -23,6 +23,7 @@ React.createClass({
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
optionalSymbol: React.PropTypes.symbol,
// 何でもレンダリングできます。number、string、要素やそれらを含む配列など。
optionalNode: React.PropTypes.node,

View File

@@ -1,7 +1,7 @@
---
id: reusable-components-ko-KR
title: 재사용가능한 컴포넌트
permalink: reusable-components-ko-KR.html
permalink: docs/reusable-components-ko-KR.html
prev: multiple-components-ko-KR.html
next: transferring-props-ko-KR.html
---
@@ -23,6 +23,7 @@ React.createClass({
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
optionalSymbol: React.PropTypes.symbol,
// 렌더링될 수 있는 모든 것: 숫자, 문자열, 요소
// 이것들을 포함하는 배열(이나 프래그먼트)

View File

@@ -1,7 +1,7 @@
---
id: reusable-components
title: Reusable Components
permalink: reusable-components.html
permalink: docs/reusable-components.html
prev: multiple-components.html
next: transferring-props.html
---
@@ -23,6 +23,7 @@ React.createClass({
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
optionalSymbol: React.PropTypes.symbol,
// Anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
@@ -131,7 +132,7 @@ 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.
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 owner 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

View File

@@ -1,7 +1,7 @@
---
id: reusable-components-zh-CN
title: 可复用组件
permalink: reusable-components-zh-CN.html
permalink: docs/reusable-components-zh-CN.html
prev: multiple-components-zh-CN.html
next: transferring-props-zh-CN.html
---
@@ -23,6 +23,7 @@ React.createClass({
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
optionalSymbol: React.PropTypes.symbol,
// 所有可以被渲染的对象:数字,
// 字符串DOM 元素或包含这些类型的数组(or fragment) 。
@@ -118,7 +119,7 @@ var ComponentWithDefaultProps = React.createClass({
## 传递 Props捷径
有一些常用的 React 组件只是对 HTML 做简单扩展。通常,你想 复制任何传进你的组件的HTML属性 到底层的HTML元素上。为了减少输入你可以用 JSX _spread_ 语法来完成:
有一些常用的 React 组件只是对 HTML 做简单扩展。通常你想复制任何传进你的组件的HTML属性到底层的HTML元素上。为了减少输入你可以用 JSX _spread_ 语法来完成:
```javascript
var CheckLink = React.createClass({
@@ -138,9 +139,9 @@ ReactDOM.render(
## Mixins
组件是 React 里复用代码最佳方式,但是有时一些复杂的组件间也需要共用一些功能。有时会被称为 [跨切面关注点](https://en.wikipedia.org/wiki/Cross-cutting_concern)。React 使用 `mixins` 来解决这类问题。
组件是 React 里复用代码最佳方式,但是有时一些不同的组件间也需要共用一些功能。有时会被称为 [跨切面关注点](https://en.wikipedia.org/wiki/Cross-cutting_concern)。React 使用 `mixins` 来解决这类问题。
一个通用的场景是:一个组件需要定期更新。用 `setInterval()` 做很容易但当不需要它的时候取消定时器来节省内存是非常重要的。React 提供 [生命周期方法](/react/docs/working-with-the-browser.html#component-lifecycle) 来告知组件创建或销毁的时间。下面来做一个简单的 mixin使用 `setInterval()` 并保证在组件销毁时清理定时器。
一个通用的场景是:一个组件需要定期更新。用 `setInterval()` 做很容易但当不需要它的时候取消定时器来节省内存是非常重要的。React 提供 [生命周期方法](/react/docs/working-with-the-browser.html#component-lifecycle) 来告知组件创建或销毁的时间。下面来做一个简单的 mixin使用 `setInterval()` 并保证在组件销毁时清理定时器。
```javascript
var SetIntervalMixin = {
@@ -185,7 +186,7 @@ ReactDOM.render(
## ES6 Classes
你也可以以一个简单的JavaScript 类来定义你的React classes。使用ES6 class的例子:
你也可以以一个简单的 JavaScript 类来定义你的React classes。使用ES6 class的例子:
```javascript
class HelloMessage extends React.Component {
@@ -196,9 +197,9 @@ class HelloMessage extends React.Component {
ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
```
API近似于 `React.createClass` 除了 `getInitialState`。 你应该在构造函数里设置你的`state`,而不是提供一个单独的 `getInitialState` 方法。
API近似于 `React.createClass` 除了 `getInitialState`。 你应该在构造函数里设置你的`state`,而不是提供一个单独的 `getInitialState` 方法。就像 `getInitialState` 的返回值,你赋给 `this.state` 的值会被作为组件的初始 state。
另一个不同是 `propTypes``defaultProps` 在构造函数而不是class body里被定义为属性
另一个不同是 `propTypes``defaultProps` 在构造函数里被定义为属性,而不是class body 里。
```javascript
export class Counter extends React.Component {
@@ -223,11 +224,38 @@ Counter.defaultProps = { initialCount: 0 };
### 无自动绑定
方法遵循正式的ES6 class的语义意味着它们不会自动绑定`this`到实例上。你必须显示的使用`.bind(this)` or [箭头函数](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions) `=>`.
方法遵循正式的ES6 class的语义意味着它们不会自动绑定`this`到实例上。你必须显示的使用`.bind(this)` or [箭头函数](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions) `=>`
```javascript
// 你可以使用 bind() 来绑定 `this`
<div onClick={this.tick.bind(this)}>
// 或者你可以使用箭头函数
<div onClick={() => this.tick()}>
```
我们建议你在构造函数中绑定事件处理器,这样对于所有实例它们只需绑定一次:
```javascript
constructor(props) {
super(props);
this.state = {count: props.initialCount};
this.tick = this.tick.bind(this);
}
```
现在你可以直接使用 `this.tick` 因为它已经在构造函数里绑定过一次了。
```javascript
// 它已经在构造函数里绑定过了
<div onClick={this.tick}>
```
这对应用的性能有帮助,特别是当你用 [浅层比较](/react/docs/shallow-compare.html) 实现 [shouldComponentUpdate()](/react/docs/component-specs.html#updating-shouldcomponentupdate) 时。
### 没有 Mixins
不幸的是ES6的发布没有任何mixin的支持。因此当你在ES6 classes下使用React时不支持mixins。作为替代我们正在努力使它更容易支持这些用例不依靠mixins。
不幸的是ES6的发布没有任何mixin的支持。因此当你在ES6 classes下使用React时不支持mixins。作为替代我们正在努力使它更容易不依靠mixins支持这些用例
## 无状态函数
@@ -248,7 +276,7 @@ ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
```
这个简化的组件API旨在用于那些纯函数态的组件 。这些组件必须没有保持任何内部状态,没有备份实例,也没有组件生命周期方法。他们纯粹的函数式的转化他们的输入,没有引用。
然而,你仍然可以以设置函数properties的方式来指定 `.propTypes``.defaultProps`就像你在ES6类里设置他们那样。
然而,你仍然可以以设置函数 properties 的方式来指定 `.propTypes``.defaultProps`就像你在ES6类里设置他们那样。
> 注意:
>

View File

@@ -1,7 +1,7 @@
---
id: transferring-props-it-IT
title: Trasferimento delle Proprietà
permalink: transferring-props-it-IT.html
permalink: docs/transferring-props-it-IT.html
prev: reusable-components-it-IT.html
next: forms-it-IT.html
---

View File

@@ -1,7 +1,7 @@
---
id: transferring-props
title: propsの移譲
permalink: transferring-props-ja-JP.html
permalink: docs/transferring-props-ja-JP.html
prev: reusable-components-ja-JP.html
next: forms-ja-JP.html

View File

@@ -1,7 +1,7 @@
---
id: transferring-props-ko-KR
title: Props 전달
permalink: transferring-props-ko-KR.html
permalink: docs/transferring-props-ko-KR.html
prev: reusable-components-ko-KR.html
next: forms-ko-KR.html
---

View File

@@ -1,7 +1,7 @@
---
id: transferring-props
title: Transferring Props
permalink: transferring-props.html
permalink: docs/transferring-props.html
prev: reusable-components.html
next: forms.html
---

View File

@@ -1,12 +1,12 @@
---
id: transferring-props-zh-CN
title: 传递 Props
permalink: transferring-props-zh-CN.html
permalink: docs/transferring-props-zh-CN.html
prev: reusable-components-zh-CN.html
next: forms-zh-CN.html
---
React 里有一个非常常用的模式就是对组件做一层抽象。组件对外公开一个简单的属性Props来实现功能但内部细节可能非常复杂的实现
React 里有一个非常常用的模式就是对组件做一层抽象。组件对外公开一个简单的属性Props来实现功能但内部的实现可能非常复杂。
可以使用 [JSX 展开属性](/react/docs/jsx-spread-zh-CN.html) 来合并现有的 props 和其它值:
@@ -53,7 +53,7 @@ ReactDOM.render(
有时把所有属性都传下去是不安全或啰嗦的。这时可以使用 [解构赋值](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) 中的剩余属性特性来把未知属性批量提取出来。
列出所有当前使用的属性,后面跟着 `...other`
列出所有当前使用的属性,后面跟着 `...other`
```javascript
var { checked, ...other } = props;
@@ -118,11 +118,11 @@ function FancyCheckbox(props) {
> 注意:
>
> 顺序很重要,把 `{...other}` 放到 JSX props 前面会使它不被覆盖。上面例子中我们可以保证 input 的 type 是 `"checkbox"`。
> 顺序很重要,把 `{...other}` 放到 JSX props 前面会使 props 不会被覆盖。上面例子中我们可以保证 input 的 type 是 `"checkbox"`。
## 剩余属性和展开属性 `...`
剩余属性可以把对象剩下的属性提取到一个新的对象。会把所有在解构赋值中列出的属性剔除。
剩余属性可以把对象剩下的属性提取到一个新的对象。会把所有在解构赋值中列出的属性剔除。
这是 [ECMAScript 草案](https://github.com/sebmarkbage/ecmascript-rest-spread) 中的试验特性。

View File

@@ -1,7 +1,7 @@
---
id: forms-it-IT
title: Moduli
permalink: forms-it-IT.html
permalink: docs/forms-it-IT.html
prev: transferring-props-it-IT.html
next: working-with-the-browser-it-IT.html
---

View File

@@ -1,7 +1,7 @@
---
id: forms
title: フォーム
permalink: forms-ja-JP.html
permalink: docs/forms-ja-JP.html
prev: transferring-props-ja-JP.html
next: working-with-the-browser-ja-JP.html
---

View File

@@ -1,7 +1,7 @@
---
id: forms-ko-KR
title: 폼
permalink: forms-ko-KR.html
permalink: docs/forms-ko-KR.html
prev: transferring-props-ko-KR.html
next: working-with-the-browser-ko-KR.html
---

View File

@@ -1,7 +1,7 @@
---
id: forms
title: Forms
permalink: forms.html
permalink: docs/forms.html
prev: transferring-props.html
next: working-with-the-browser.html
---

View File

@@ -1,12 +1,12 @@
---
id: forms-zh-CN
title: 表单组件
permalink: forms-zh-CN.html
permalink: docs/forms-zh-CN.html
prev: transferring-props-zh-CN.html
next: working-with-the-browser-zh-CN.html
---
诸如 `<input>``<textarea>``<option>` 这样的表单组件不同于其他组件,因为他们可以通过用户交互发生变化。这些组件提供的界面使响应用户交互的表单数据处理更加容易。
诸如 `<input>``<textarea>``<option>` 这样的表单组件不同于其他原生组件,因为他们可以通过用户交互发生变化。这些组件提供的界面使响应用户交互的表单数据处理更加容易。
关于 `<form>` 事件详情请查看 [表单事件](/react/docs/events-zh-CN.html#form-events)。
@@ -76,7 +76,7 @@ next: working-with-the-browser-zh-CN.html
### 复选框与单选按钮的潜在问题
当心在力图标准化复选框与单选按钮的变换处理中React使用`click` 事件代替 `change` 事件。在大多数情况下它们表现的如同预期,除了在`change` handler中调用`preventDefault``preventDefault` 阻止了浏览器视觉上更新输入,即使`checked`被触发。变通的方式是要么移除`preventDefault`的调用,要么把`checked` 的触发放在一个`setTimeout`里。
当心在力图标准化复选框与单选按钮的变换处理中React使用 `click` 事件代替 `change` 事件。在大多数情况下它们表现的如同预期,除了在`change` handler中调用`preventDefault``preventDefault` 阻止了浏览器视觉上更新输入,即使`checked`被触发。变通的方式是要么移除`preventDefault`的调用,要么把`checked` 的触发放在一个`setTimeout`里。
## 不受控组件
@@ -102,7 +102,7 @@ next: working-with-the-browser-zh-CN.html
}
```
这个例子会像上面的 **受控组件** 例子一样运行。
这个例子会像上面的 **受控组件** 例子一样运行。
同样的, `<input type="checkbox">``<input type="radio">` 支持 `defaultChecked``<select>` 支持 `defaultValue`.
@@ -130,7 +130,7 @@ next: working-with-the-browser-zh-CN.html
}
```
既然这个方法描述了在任意时间点上的视图,那么文本输入框的值就应该*始终*为 `Untitled`
由于这个方法描述了在任意时间点上的视图,那么文本输入框的值就应该*始终*为 `Untitled`
### 为什么 `<textarea>` 使用 `value` 属性?
@@ -141,7 +141,7 @@ next: working-with-the-browser-zh-CN.html
<textarea name="description">This is the description.</textarea>
```
对 HTML 而言让开发者设置多行的值很容易。但是React 是 JavaScript没有字符串限制可以使用 `\n` 实现换行。简言之React 已经有 `value``defaultValue` 属性,`</textarea>` 组件的子节点扮演什么角色就有点模棱两可了。基于此, 设置 `<textarea>` 值时不应该使用子节点:
对 HTML 而言,让开发者设置多行的值很容易。但是,由于 React 是 JavaScript没有字符串限制可以使用 `\n` 实现换行。简言之React 已经有 `value``defaultValue` 属性,`<textarea>` 组件的子节点扮演什么角色就有点模棱两可了。基于此, 设置 `<textarea>` 值时不应该使用子节点:
```javascript
<textarea name="description" value="This is a description." />
@@ -151,7 +151,7 @@ next: working-with-the-browser-zh-CN.html
### 为什么 `<select>` 使用 `value` 属性
HTML 中 `<select>` 通常使用 `<option>``selected` 属性设置选中状态React 为了更方面的控制组件,采用以下方式代替:
HTML 中 `<select>` 通常使用 `<option>``selected` 属性设置选中状态React 为了更方便地控制组件,采用以下方式代替:
```javascript
<select value="B">

View File

@@ -1,7 +1,7 @@
---
id: working-with-the-browser-it-IT
title: Lavorare con il Browser
permalink: working-with-the-browser-it-IT.html
permalink: docs/working-with-the-browser-it-IT.html
prev: forms-it-IT.html
next: more-about-refs-it-IT.html
---

View File

@@ -1,7 +1,7 @@
---
id: working-with-the-browser
title: ブラウザと動くこと
permalink: working-with-the-browser-ja-JP.html
permalink: docs/working-with-the-browser-ja-JP.html
prev: forms-ja-JP.html
next: more-about-refs-ja-JP.html
---

View File

@@ -1,7 +1,7 @@
---
id: working-with-the-browser-ko-KR
title: 브라우저에서의 동작
permalink: working-with-the-browser-ko-KR.html
permalink: docs/working-with-the-browser-ko-KR.html
prev: forms-ko-KR.html
next: more-about-refs-ko-KR.html
---

View File

@@ -1,7 +1,7 @@
---
id: working-with-the-browser
title: Working With the Browser
permalink: working-with-the-browser.html
permalink: docs/working-with-the-browser.html
prev: forms.html
next: more-about-refs.html
---

View File

@@ -1,24 +1,24 @@
---
id: working-with-the-browser-zh-CN
title: 与浏览器协作
permalink: working-with-the-browser-zh-CN.html
permalink: docs/working-with-the-browser-zh-CN.html
prev: forms-zh-CN.html
next: more-about-refs-zh-CN.html
---
React提供了强大的抽象机制使你在大多数情况下免于直接接触DOM但有时你仅仅只需要访问底层API也许是为了与第三方库或者已有的代码协作。
## 虚拟DOM
## 虚拟 DOM
React非常快速是因为它从不直接操作DOM。React维持了一个快速的内存中的DOM表示。`render()` 方法实际上返回一个对DOM的*描述*然后React能根据内存中的“描述”来比较此“描述”以计算出最快速的方更新浏览器。
React非常快速是因为它从不直接操作DOM。React维持了一个快速的内存中的DOM表示。`render()` 方法实际上返回一个对DOM的*描述*然后React能将其与内存中的“描述”进行比较,以计算出最快速的方更新浏览器。
此外React实现了一个完备的合成事件(synthetic event)系统以使得所有的事件对象都被保证符合W3C细则而不论各个浏览器的怪癖并且所有事件跨浏览器地一致并高效的冒泡bubbles你甚至能在IE8里使用一些HTML5事件
此外React实现了一个完备的合成事件synthetic event系统以使得所有的事件对象都被保证符合W3C细则而不论各个浏览器的怪癖并且所有事件跨浏览器地一致并高效的冒泡bubbles你甚至能在IE8里使用一些HTML5事件
大多数时间你应该和React的"伪造浏览器"呆在一起因为它更高性能并且容易推理。然而有时你只需要访问底层API或许是为了与第三方库比如一个jQuery插件协作。React为你提供了安全口来直接使用底层API。
大多数时间你应该和React的"伪造浏览器"呆在一起因为它更高性能并且容易推理。然而有时你只需要访问底层API或许是为了与第三方库比如一个jQuery插件协作。React为你提供了安全口来直接使用底层API。
## Refs 和 findDOMNode()
为了与浏览器互动你需要一个指向DOM node的引用。你可以连接一个 `ref` 到任何的元素,这允许你引用 组件的 **backing instance**它很有用,如果你需要在组件上调用命令式函数或者想访问底层的DOM节点。要了解多关于 refs包括更有效使用他们的方法请查看我们的 [关于Refs的更多内容](/react/docs/more-about-refs-zh-CN.html) 文档。
为了与浏览器互动你需要一个指向DOM node的引用。你可以连接一个 `ref` 到任何的元素,这允许你引用组件的 **backing instance** 。如果你需要在组件上调用命令式函数或者想访问底层的DOM节点,它很有用。要了解多关于 refs包括更有效使用他们的方法请查看我们的 [关于Refs的更多内容](/react/docs/more-about-refs-zh-CN.html) 文档。
## 组件的生命周期
@@ -32,7 +32,7 @@ React提供生命周期方法以便你可以指定钩挂到这个过程上。
### 挂载
* `getInitialState(): object` 在组件挂载前被调用. 有状态组件(Stateful components) 应该实现此函数并返回初始state的数据。
* `getInitialState(): object` 在组件挂载前被调用有状态组件(Stateful components) 应该实现此函数并返回初始state的数据。
* `componentWillMount()` 在挂载发生前被立即调用。
* `componentDidMount()` 在挂载发生后被立即调用。 需要DOM node的初始化应该放在这里。
@@ -45,53 +45,16 @@ React提供生命周期方法以便你可以指定钩挂到这个过程上。
### 卸载
* `componentWillUnmount()` 在组件被卸载和摧毁被立即调用。清理应该放在这里。
* `componentWillUnmount()` 在组件被卸载和摧毁被立即调用。清理应该放在这里。
### 已挂载的方法
_Mounted_ 复合组件同样支持以下方法:
* `component.forceUpdate()` 可以在任何已挂载的组件上调用,在你知道 某些深处的组件状态未使用 `this.setState()` 改变了时。
* `component.forceUpdate()` 可以在任何已挂载的组件上调用,在你知道某些深处的组件状态未使用 `this.setState()` 就被改变了时。
## 浏览器支持和填充物(polyfills)
## 浏览器支持
在 Facebook我们支持老浏览器包括IE8。我们由来已久的有适当的填充物(polyfills)来让我们写前瞻性的js。这意味着我们在代码库中没有一堆散落在各处的技巧(hacks)并且我们依然能期望我们的代码"可行just work"。例如,我可以只写 `Date.now()`,而不是额外看到`+new Date()`。既然开源的React和我们内部使用的一样我们也应用了这种使用前瞻性js的哲学
React 支持绝大多数流行的浏览器,包括 Internet Explorer 9 及以上
除了这种哲学外我们也采用了这样的立场我们作为一个JS库的作者不应该把polyfills作为我们库的一部分。如果所有的库这样做就有很大的机会发送同样的polyfill多次这可能是一个相当大的无用代码。如果你的产品需要支援老的浏览器你很有可能已经在使用某些东西比如[es5-shim](https://github.com/es-shims/es5-shim)
### 需要用来支持旧浏览器的Polyfills
来自 [kriskowal's es5-shim](https://github.com/es-shims/es5-shim)的`es5-shim.js` 提供了如下React需要的东西
* `Array.isArray`
* `Array.prototype.every`
* `Array.prototype.forEach`
* `Array.prototype.indexOf`
* `Array.prototype.map`
* `Date.now`
* `Function.prototype.bind`
* `Object.keys`
* `String.prototype.split`
* `String.prototype.trim`
同样来自 [kriskowal's es5-shim](https://github.com/es-shims/es5-shim)的`es5-sham.js`, 提供了如下React需要的东西
* `Object.create`
* `Object.freeze`
非最小化的React build需要如下来自[paulmillr's console-polyfill](https://github.com/paulmillr/console-polyfill).
* `console.*`
当在IE8里使用HTML5元素包括`<section>`, `<article>`, `<nav>`, `<header>`, 和 `<footer>`, 同样必须包含[html5shiv](https://github.com/aFarkas/html5shiv) 或者类似的脚本。
### 跨浏览器问题
尽管React在抽象浏览器不同时做的相当好但一些浏览器被限制或者表现出怪异的行为我们没能找到变通的方案解决。
#### IE8的onScroll事件
在IE8`onScroll` 事件不冒泡并且IE8没有定义事件捕获阶段handlers的API意味React这没有办法去监听这些事件。
目前这个事件的handler在IE8中是被忽略的。
参见 [onScroll doesn't work in IE8](https://github.com/facebook/react/issues/631) GitHub问题 来获得更多信息.
(我们不支持那些不支持 ES5 methods 的更老的浏览器,但你可能发现如果你的页面包含了类似 [es5-shim and es5-sham](https://github.com/es-shims/es5-shim) 的填充物时是可以在更老的浏览器上运行的。是否做这一步取决于你自己。)

View File

@@ -1,7 +1,7 @@
---
id: more-about-refs-it-IT
title: Riferimenti ai Componenti
permalink: more-about-refs-it-IT.html
permalink: docs/more-about-refs-it-IT.html
prev: working-with-the-browser-it-IT.html
next: tooling-integration-it-IT.html
---

View File

@@ -1,7 +1,7 @@
---
id: more-about-refs
title: 参照についての詳細
permalink: more-about-refs-ja-JP.html
permalink: docs/more-about-refs-ja-JP.html
prev: working-with-the-browser-ja-JP.html
next: tooling-integration-ja-JP.html

View File

@@ -1,7 +1,7 @@
---
id: more-about-refs-ko-KR
title: refs에서 컴포넌트로
permalink: more-about-refs-ko-KR.html
permalink: docs/more-about-refs-ko-KR.html
prev: working-with-the-browser-ko-KR.html
next: tooling-integration-ko-KR.html
---

View File

@@ -1,11 +1,11 @@
---
id: more-about-refs
title: Refs to Components
permalink: more-about-refs.html
permalink: docs/more-about-refs.html
prev: working-with-the-browser.html
next: tooling-integration.html
---
After building your component, you may find yourself wanting to "reach out" and invoke methods on component instances returned from `render()`. In most cases, this should be unnecessary because the reactive data flow always ensures that the most recent props are sent to each child that is output from `render()`. However, there are a few cases where it still might be necessary or beneficial, so React provides an escape hatch known as `refs`. These `refs` (references) are especially useful when you need to: find the DOM markup rendered by a component (for instance, to position it absolutely), use React components in a larger non-React application, or transition your existing codebase to React.
After building your component, you may find yourself wanting to "reach out" and invoke methods on component instances returned from `render()`. In most cases, this should be unnecessary because the reactive data flow always ensures that the most recent props are sent to each child that is output from `render()`. However, there are a few cases where it still might be necessary or beneficial, so React provides an escape hatch known as `refs`. These `refs` (references) are especially useful when you need to find the DOM markup rendered by a component (for instance, to position it absolutely), use React components in a larger non-React application, or transition your existing codebase to React.
Let's look at how to get a ref, and then dive into a complete example.

View File

@@ -1,7 +1,7 @@
---
id: more-about-refs-zh-CN
title: 对组件的refs
permalink: more-about-refs-zh-CN.html
permalink: docs/more-about-refs-zh-CN.html
prev: working-with-the-browser-zh-CN.html
next: tooling-integration-zh-CN.html
---
@@ -11,8 +11,7 @@ next: tooling-integration-zh-CN.html
## 从 ReactDOM.render 返回的 ref
不要被 你在你的组件它返回一个虚拟的DOM元素里定义的 `render()` 迷惑了, [ReactDOM.render()](/react/docs/top-level-api.html#reactdom.render) 会返回一个对你的组件的 **backing instance** 的引用(或者 `null` for [stateless components](/react/docs/reusable-components.html#stateless-functions)).
不要被你在你的组件它返回一个虚拟的DOM元素里定义的 `render()` 迷惑了, [ReactDOM.render()](/react/docs/top-level-api.html#reactdom.render) 会返回一个对你的组件的 **backing instance** 的引用([无状态组件](/react/docs/reusable-components.html#stateless-functions) 返回 `null`).
```js
var myComponent = ReactDOM.render(<MyComponent />, myContainer);
@@ -64,7 +63,7 @@ React支持一种非常特殊的属性你可以附加到任何的组件上。
当连接一个ref到一个DOM组件如 `<div />`你取回DOM节点;当连接一个ref到一个复合组件如 `<TextInput />`你会得到React类的实例。在后一种情况下你可以调用任何那个组件的类暴露的方法。
注意当被引用的组件卸载和每当ref变动旧的ref将会被以`null`做参数调用。这阻止了在实例被保存的情况下的内存泄露,如第个例子。注意当像在这里的例子使用内联函数表达式写refsReact在每次更新都看到不同的函数对象ref将会被以`null` 立即调用在它被以组件实例调用前。
注意当被引用的组件卸载和每当ref变动旧的ref将会被以`null`做参数调用。这阻止了在实例被保存的情况下的内存泄露,如第个例子。注意当像在这里的例子使用内联函数表达式写refsReact在每次更新都看到不同的函数对象ref将会被以`null` 立即调用在它被以组件实例调用前。
## ref String 属性
@@ -76,7 +75,7 @@ React同样支持使用一个字符串代替回调函数在任意组件上
<input ref="myInput" />
```
2. 在其他一些代码中(典型的事件处理代码),通过`this.refs`访问 **支持实例(backing instance)**,如:
2. 在其他一些代码中(典型的事件处理代码),通过`this.refs`访问 **支持实例(backing instance)**,如:
```javascript
var input = this.refs.myInput;
@@ -85,6 +84,7 @@ React同样支持使用一个字符串代替回调函数在任意组件上
```
## 完整的示例
为了获取一个React组件的引用你既可以使用 `this` 来获取当前的React组件也可以使用一个 ref 来获取一个你拥有的组件的引用。他们像这样工作:
```javascript
@@ -121,7 +121,7 @@ ReactDOM.render(
## 总结
Refs是一种很好的发送消息给特定子实例(通过流式的Reactive `props` 和 `state`来做会不方便)的方式。它们应该,不论怎样,不是你数据流通你的应用的首选。默认情况下使用响应式数据流并为本身不是reactive的用例保存`ref`s
Refs是一种很好的发送消息给特定子实例(通过流式的Reactive `props` 和 `state`来做会不方便)的方式。它们应该,不论怎样,不是你的应用中数据流通的首选。默认情况下使用响应式数据流并为本身不是reactive的用例保存`ref`。
### 优点:

View File

@@ -1,7 +1,7 @@
---
id: tooling-integration-it-IT
title: Integrazione con Strumenti
permalink: tooling-integration-it-IT.html
permalink: docs/tooling-integration-it-IT.html
prev: more-about-refs-it-IT.html
next: addons-it-IT.html
---

View File

@@ -1,7 +1,7 @@
---
id: tooling-integration
title: インテグレーションツール
permalink: tooling-integration-ja-JP.html
permalink: docs/tooling-integration-ja-JP.html
prev: more-about-refs-ja-JP.html
next: addons-ja-JP.html
---

View File

@@ -1,7 +1,7 @@
---
id: tooling-integration-ko-KR
title: 툴 통합
permalink: tooling-integration-ko-KR.html
permalink: docs/tooling-integration-ko-KR.html
prev: more-about-refs-ko-KR.html
next: addons-ko-KR.html
---

View File

@@ -1,7 +1,7 @@
---
id: tooling-integration
title: Tooling Integration
permalink: tooling-integration.html
permalink: docs/tooling-integration.html
prev: more-about-refs.html
next: language-tooling.html
---

View File

@@ -1,80 +1,13 @@
---
id: tooling-integration-zh-CN
title: 工具集成
permalink: tooling-integration-zh-CN.html
permalink: docs/tooling-integration-zh-CN.html
prev: more-about-refs-zh-CN.html
next: addons-zh-CN.html
---
每个项目使用一个不同的系统来建立和部署JavaScript.我们努力使React尽可能环境无关
我们尽可能使 React 与环境无关。大家可以在各种语言JavaScript, TypeScript, ClojureScript, etc与各种环境(web, iOS, Android, NodeJS, Nashorn, etc)中使用 React。这里有很多工具来帮助你创建优秀的应用。在这一节中我们介绍一些在 React 中最流行的工具
## React
### CDN-hosted React
我们提供了CDN-hosted版本的React[在我们的下载页面](/react/downloads.html).这些预构建的文件使用UMD模块格式。将他们放进一个简单的`<script>` 标签将会注入一个`React` 全局变量到你的环境里。这也同样在CommonJS 和 AMD 环境里开箱即用。
### 使用 master
我们[在我们的 GitHub repository](https://github.com/facebook/react)有从`master`构建的说明。我们在`build/modules` 下构建了一个CommonJS模块的树你可以把它放到任何支持CommonJS的环境或者打包工具里。
## JSX
### 浏览器中的JSX转化
如果你喜欢使用JSXBabel5 提供了被称为browser.js 用于开发的一个浏览器内的 ES6 和 JSX 转换器,它可以从 [CDNJS](http://cdnjs.com/libraries/babel-core/5.8.34) 引用。Include `<script type="text/babel">` 标记来使用 JSX 转换器.
> 注意:
>
> 浏览器中的JSX转换器相当大并且导致额外的本可避免的客户端计算。不要在生产环境中使用 - 见下一节。
### 投入生产: 预编译 JSX
如果你有[npm](https://www.npmjs.com/),你可以运行 `npm install -g babel-cli`. Babel 对React v0.12+ 有内建支持。 标签被自动转化为它们的等价物`React.createElement(...)`, `displayName` 被自动推断并添加到所有的React.createClass 调用。
这个工具会把使用JSX语法的文件转化为简单的可直接在浏览器运行的JavaScript文件。它同样将为你监视目录并自动转化文件当他们变动时例如`babel --watch src/ --out-dir lib/`.
从 Babel 6 开始,默认不再包含转换。这意味这必须在运行 `babel` 命令时指定选项,或者 `.babelrc` 必须指定选项。附加的捆绑了一大批转化的包(presets)也同样需要被安装.协同React工作最常用的是 `es2015``react` presets.更多关于 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/
```
默认模式下带有`.js`后缀的JSX文件被转化。运行 `babel --help` 获取更多关于如何使用 Babel 的信息。
输出的例子:
```
$ 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);
```
### 有帮助的开源项目
开源社区已经创建了一些集成JSX到数个编辑器和构建系统的工具。全部列表请见[JSX integrations](https://github.com/facebook/react/wiki/Complementary-Tools#jsx-integrations) 。
* [语言工具](/react/docs/language-tooling.html) 描述如何设置例如 Babel 的工具来编译 JSX。
* [包管理](/react/docs/package-management.html) 讲述如何设置将 React 配置为项目中的依赖。
* [服务端环境](/react/docs/environments.html) 讲述如何为 React 配置服务端渲染环境。

View File

@@ -1,7 +1,7 @@
---
id: language-tooling
title: Language Tooling
permalink: language-tooling.html
permalink: docs/language-tooling.html
prev: tooling-integration.html
next: package-management.html
---

View File

@@ -1,7 +1,7 @@
---
id: package-management
title: Package Management
permalink: package-management.html
permalink: docs/package-management.html
prev: language-tooling.html
next: environments.html
---

View File

@@ -1,7 +1,7 @@
---
id: environments
title: Server-side Environments
permalink: environments.html
permalink: docs/environments.html
prev: package-management.html
next: addons.html
---

View File

@@ -1,7 +1,7 @@
---
id: addons-it-IT
title: Add-ons
permalink: addons-it-IT.html
permalink: docs/addons-it-IT.html
prev: tooling-integration-it-IT.html
next: animation-it-IT.html
---

View File

@@ -1,7 +1,7 @@
---
id: addons
title: アドオン
permalink: addons-ja-JP.html
permalink: docs/addons-ja-JP.html
prev: tooling-integration-ja-JP.html
next: animation-ja-JP.html
---

View File

@@ -1,7 +1,7 @@
---
id: addons-ko-KR
title: 애드온
permalink: addons-ko-KR.html
permalink: docs/addons-ko-KR.html
prev: tooling-integration-ko-KR.html
next: animation-ko-KR.html
---

View File

@@ -1,7 +1,7 @@
---
id: addons
title: Add-ons
permalink: addons.html
permalink: docs/addons.html
prev: environments.html
next: animation.html
---

View File

@@ -1,7 +1,7 @@
---
id: addons-zh-CN
title: 插件
permalink: addons-zh-CN.html
permalink: docs/addons-zh-CN.html
prev: tooling-integration-zh-CN.html
next: animation-zh-CN.html
---

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