According to current React version, when I use `React.render`, console shows `React.render is deprecated. Please use ReactDOM.render from require('react-dom') instead.`.
So this PR is a tiny update for the README example.
(cherry picked from commit 2b136a4f84)
You could make the argument that this should be optional, but it doesn't
work without it so we might as well just enforce it.
Makes `jest` work by default.
Seems better to fail gracefully, especially now that we support inlining. If people do this by accident we can figure out how to add a helpful warning instead.
Fixes#3285.
Split {{ in example code to avoid an Exception in jekyll.
> Liquid Exception: Variable '{{' was not properly terminated with regexp: /\}\}/ in docs/10.1-animation.md
When calling ReactTestUtils.Simulate, sometimes you want to test that an exception is thrown by the event handler. This lets you do that without relying on the fact that old jsdom doesn't implement `Event`.
Fixes#3473
I tag each React element with `$$typeof: Symbol.for('react.element')`. We need
this to be able to safely distinguish these from plain objects that might have
come from user provided JSON.
The idiomatic JavaScript way of tagging an object is for it to inherent some
prototype and then use `instanceof` to test for it.
However, this has limitations since it doesn't work with value types which
require `typeof` checks. They also don't work across realms. Which is why there
are alternative tag checks like `Array.isArray` or the `toStringTag`. Another
problem is that different instances of React that might have been created not knowing about eachother. npm tends to make this kind of problem occur a lot.
Additionally, it is our hope that ReactElement will one day be specified in
terms of a "Value Type" style record instead of a plain Object.
This Value Types proposal by @nikomatsakis is currently on hold but does satisfy all these requirements:
https://github.com/nikomatsakis/typed-objects-explainer/blob/master/valuetypes.md#the-typeof-operator
Additionally, there is already a system for coordinating tags across module
systems and even realms in ES6. Namely using `Symbol.for`.
Currently these objects are not able to transfer between Workers but there is
nothing preventing that from being possible in the future. You could imagine
even `Symbol.for` working across Worker boundaries. You could also build a
system that coordinates Symbols and Value Types from server to client or through
serialized forms. That's beyond the scope of React itself, and if it was built
it seems like it would belong with the `Symbol` system. A system could override
the `Symbol.for('react.element')` to return a plain yet
cryptographically random or unique number. That would allow ReactElements to
pass through JSON without risking the XSS issue.
The fallback solution is a plain well-known number. This makes it unsafe with
regard to the XSS issue described in #3473. We could have used a much more
convoluted solution to protect against JSON specifically but that would require
some kind of significant coordination, or change the check to do a
`typeof element.$$typeof === 'function'` check which would not make it unique to
React. It seems cleaner to just use a fixed number since the protection is just
a secondary layer anyway. I'm not sure if this is the right tradeoff.
In short, if you want the XSS protection, use a proper Symbol polyfill.
Finally, the reason for calling it `$$typeof` is to avoid confusion with `.type`
and the use case is to add a tag that the `typeof` operator would refer to.
I would use `@@typeof` but that seems to deopt in JSC. I also don't use
`__typeof` because this is more than a framework private. It should really be
part of the polyfilling layer.
Should fix#1939.
Test Plan:
With two copies of React, render a div using React1 and use that as a container to render a div with React2. Add onMouseEnter/onMouseLeave to both divs that log. Mouse around and see correct logs (as if each React was isolated), no errors.
Previously, we fetched the node once for every changed attribute. In my createElement diff, I changed it to fetch the node (once) regardless of if there were changes -- fetching it once only if there are changes is even better.
React components can be assigned a special property named `key`. Therefore, it's helpful to avoid the phrase "key property" unless you're talking about the `key` property :)
I'm not sold on the replacement phrase, though... I think it's solid, but two fancy words like "fundamental" and "invariant" next to each other just seem a bit unwelcoming xP then again, we're talking about some heavy technical stuff; if there aren't any lighter words that are equally precise, then these should probably stand.
Changed: createFragment no longer includes nulls in its output (since toArray doesn't and they share code).
Changed: React.Children.map no longer warns for clashing keys; traverseAllChildren will later when rendering.
Also change the generated key format around to accomodate. My keys are probably not bulletproof but should definitely be safe against accidental collisions.
"This ensures that" sounds a better than "That ensures that." This change is just my personal opinion, so I totally understand my change doesn't get merged.
As discussed in issue 1326
(https://github.com/facebook/react/issues/1326) transitionend events are
unreliable; they may not fire because the element is no longer painted,
the browser tab is no longer focused or for a range of other reasons.
This is particularly harmful during leave transitions since the leaving
element will be permanently stuck in the DOM (and possibly visible).
The ReactCSSTransitionGroup now requires timeouts to be passed in
explicitly for each type of animation. Omitting the timeout duration
for a transition now triggers a PropTypes warning with a link to the
updated documentation.
Turns out jest is _incredibly_ slow at resolving require paths like `require('fbjs/lib/foo')`. Like several milliseconds per require. Really adds up when all our files require `invariant` and `warning`. Here's a temporary hack to make things fast again.
Test Plan:
```
npm test src/renderers/shared/reconciler/__tests__/ReactCompositeComponent-test.js
```
has a self-proclaimed runtime of ~8 seconds now instead of ~35 seconds.
Behind a feature flag. This is a relatively simple change; adopting this strategy universally would mean that we could clean up a lot of code but this doesn't attempt to restructure more than necessary.
As of this commit, we still support objects as maps so if anyone has an object with keys 'type' and 'props' this will change behavior, but otherwise this should be pretty safe.
This simplifies event dispatching by removing the `return false` special
case for the SimpleEventPlugin which allow us to inline much more here
and the code becomes easier to follow.
This wraps a proper guard around event dispatching so that errors doesn't
interupt other event callbacks.
Instead we rethrow the first error after all callbacks have been invoked.
For DEV mode we use native event dispatching if available. This has the
benefit that caught exceptions show up in the dev tools even without caught
exceptions being turned on. Yet, all callbacks are guaranteed to fire.
Stateless pure-function components give us more opportunity to make performance optimizations. For now, we'll do a minimal implementation which has similar performance characteristics to other components in the interests of shipping 0.14 and allowing people to begin writing code using this pattern; in the future we can refactor to allocate less and avoid other unnecessary work.
```reactComponentExpect``` fails silently when passed an undefined value. It calls ```ReactTestUtils.isCompositeComponent``` with the undefined value, in which a ```render``` property is accessed, throwing a prop on undefined not found error which isn't surfaced to jest.
```
TypeError: Cannot read property 'render' of undefined
at Object.ReactTestUtils.isCompositeComponent (./react/test/ReactTestUtils.js:127:23)
at new reactComponentExpect (./react/test/reactComponentExpect.js:46:20)
at reactComponentExpect (./react/test/reactComponentExpect.js:40:12)
```
Expecting the passed-in instance to not be undefined surfaces this issue in the test runner.
Or the alternative:
`REST is an acronym for Representational State Transfer, which is an architectural style rather than a formal protocol`.
Sorry , I'am not a native speaker:)
ReactTools is deprecated, it doesn't belong at the root of the project. We'll remove it after 0.14 but for now this moves it so that it's contained and not intermixed with the rest of the project. The currect behavior of copying src/ into the package is maintained.
This ensures that we can consume code from npm that has our process.env pattern. Unfortunately we'll run the same transform on minified builds but it's pretty quick.
This reworks a few things in building and distributing React. The biggest change is using fbjs to share dependencies with other libraries. We're also using Gulp for some build steps.
With this, ReactMultiChild handles all of the children-related operations for ReactDOMComponent so that we don't process operations out of order. This is necessary because ReactMultiChild does its own batching so there's no way without its cooperation to get the timing right here.
Ideally we'll factor this logic out a bit better in subsequent updates but this is the simplest way to fix#1232 which has embarrassingly been open for over a year.
I'm proposing these changes because I found some repetition / lack of
clarity and some language that suggested that you could mutate
`this.state` directly.
Rely on jest for now until we get a better and less hacky solution to running tests in the browser, probably a totally different test suite with different behavior/goals.
I came across an issue on a React project where I needed to programatically set the default value of an input as the result of an async call. (I was prepopulating a zip code field from the Google Maps Geocoding API). It didn't work when I passed in an updated defaultValue prop, until I came across this StackOverflow: http://stackoverflow.com/questions/30146105/react-input-defaultvalue-doesnt-update-with-state. I was able to get it to do what I wanted by passing in the value prop instead.
The addons module warning is currently causing issues with babel/JSPM due to the warning message getting parsed as a require statement. Adding a break using string concatenation appears to prevent any issues.
Example error using JSPM:
```
Error loading "react-addons-{addon}" from...
```
- Add missing object-assign dependency
- Add batchedUpdates to ReactDOMClient, rename the two addons to `unstable_`
- Delete react/addons/* (leaving react/addons with a slightly updated warning)
- Add README.md, LICENSE, PATENTS to each addons package
Changes:
- moves after_script to script
- adds `set -e`
- creates a seperate matrix 'build'
Way at the bottom of the travis output:
```
1571: curl: (26) couldn't open file "build/react.tgz"
```
This seems to be broken since 12c9fee94e
No reason to limit at 100. I can't imagine a reasonable tree with depth over 10,000 but that should still be small enough to "catch infinite loops" quickly.
This hack allow us to get rid of the stateful module ReactLifeCycle since
we can infer the value of isMounted even without it. This gets rid of
the try/catch which is deopting all mountComponent calls.
As a next step we could deprecate isMounted completely and avoid stateful
APIs. Since it can be easily simulated if you truly need it.
Since I fixed the server-side rendering it is now possible to trigger these
callbacks on the client alone. They will still be queued up on the server
but they are never executed.
This allows updates to be enqueued during render. setState in
componentWillMount will still be collected as part of the first pass so
if nothing else get added as pending, they won't trigger a second rerender.
This allow us to get rid of one more stateful special case.
This simply ignores any enqueued actions. This means that we don't have to have special logic for componentWillMount. It is just that those updates are never enqueued.
This was used for any invariant that was subsequently removed. It turns
out that this is completely unnecessary now. Any setState calls will
enqueue and update and the component added to the update queue. However,
since the pending fields are reset after componentWillUnmount, any update
will still be ignored.
It was impossible to get here because if you enqueue something
Also ensure that they're only used in DEV because we will be reading
state that is DEV only here.
This should only be used for tracking string refs. For that purpose, we
need a single central stateful module that is coupled to createElement.
Which is why it needs to live in isomorphic.
Eventually this will go away completely.
This decouples the stateful imperative API from the class creation.
Instead, they get injected into the class from the renderer. Stateful
modules should always be injected.
As a convenience, just like props/context/refs, we set it up after
construction using mutation. That way it is optional to pass it along
the super call constructor chain.
We won't be able to support this after DOM-components-as-refs but we don't expect many people to be passing DOM components to this function anyway, and it should be fairly straightforward for people to clean up failing unit tests using this function.
(This module also isn't public API and never has been.)
We won't be able to support this after DOM-components-as-refs but we don't expect many people to be passing DOM components to this function anyway, and it should be fairly straightforward for people to clean up failing unit tests using this function.
Squashed commit:
[4564e55] Ensures we don't need to update this page for every release.
[b0d60f9] update script sources to be even with the example file in reactjs/react-tutorial repo
This is kind of a confusing place for it but it is intimitely tied to the
update life cycle which is what the update queue is about.
This kills some dependencies from isomorphic to the renderer.
We keep track of the fact that something is rendering for a bunch of
warnings. (ReactCurrentOwner.current !== null)
Once we get rid of owner for string refs, I'll convert those to something
like "isRendering" instead. The interesting part is that feature `__DEV__`
only. It is only used for warnings. Except for this case.
This means that we can get rid of the special case for the isRendering
stack on in prod.
- babel-eslint ^3.1.14 fixesbabel/babel-eslint#120
- babel updated from ^5.3.3 to ^3.5.5, which changes stuff, I guess
- eslint updated from ^0.21.2 to ^0.22.1, which makes `no-shadow` also
check class declarations
In xml node name casing is exactly the same as the node was originally named.
Make sure to convert node and tag names to lower case before making any node
and tag name checks.
Fixes#3960.
spicyj noticed newer versions of babel-eslint seemed not to error on
no-unused-vars, and I was able to repro. It seems like something broke
between 3.1.9 and 3.1.10. (Smaller repro case and babel-eslint bug
report to come)
His commit failed on travis, but not on his local machine:
https://travis-ci.org/facebook/react/jobs/65468729
> The two callers of this function have different warning configs
> internally (static_upstream/core/createWarning.js) so we can't sync it
> like this without changing behavior. We should just split this out
> into two separate warning calls probably – this code is a little
> overabstracted.
https://github.com/facebook/react/pull/4021#discussion_r31690020
@spicyj
I think completely removing warnAndMonitorForKeyUse is a bit difficult, without
duplicating a ton of code. This at least ensures that the format string passed
to `warning` is unique. Plus, because the FB internal code in question only
matches the beginning of the format string, I think there should be zero
internal changes that need to be made to support this refactor.
The `warning` implementation checked that the message is long enough to
be useful. See commit f5038829d for more information.
It makes more sense to move this into a lint rule, and also to apply it
for both `warning` and `invariant`. We can safely remove stuff from the
`warning` implementation as we replace the function internally anyways.
https://github.com/facebook/react/pull/4021#issuecomment-108694976
@spicyj
The wording for an incorrect number of arguments based on counting %s
substitutions. The previous wording was backwards and a bit yoda-like
leading to possible ambiguity.
This should contain all the rules we probably want to use, except
react/wrap-multilines, which requires a larger codemod, and would
clutter this commit.
See #2869
Checks that the *second* argument of warning and invariant are a literal
string, or a concatination of literal strings, and that the number of
arguments is correct based on the number of %s substrings.
This commit also fixes a few places where the existing code had broken
error messages!
The rule itself is pretty straightforward, although adding the tests
ended up being a bit painful, as eslint-tester depends on mocha, and
therefore needs to be run in a separate grunt task.
This is a machine-generated codemod, but it's pretty safe since it was
generated by hooking into eslint's own report.
A few files had to be touched up by hand because there were existing
formatting issues with nested arrays/objects:
src/shared/utils/__tests__/OrderedMap-test.js
src/shared/utils/__tests__/Transaction-test.js
src/shared/utils/__tests__/traverseAllChildren-test.js
src/isomorphic/children/__tests__/ReactChildren-test.js
Introducing: a really lame version of composite components, right inside of ReactDOMComponent!
Now ReactDOMInput isn't an actual component. This brings us closer to exposing DOM nodes as refs.
Closes#3971.
> After #3968, the next thing we should do is start linting our tests.
> Historically we've ignored them due to lack of parser compatibility.
> But that shouldn't be a problem anymore. We may want to integrate
> https://www.npmjs.com/package/eslint-plugin-react to more aggressively
> lint our JSX in tests.
I understand this diff touches a lot of stuff, so I tried to keep it to
a near-minimal set of changes to make eslint happy.
- Removes esprima-fb dependency
- Tightens up eslintrc with some minor rules we were pretty-much
following anyways.
- Adds pretty colors to the `grunt lint` output
- Breaks block-scoped-var :(
Follow-up to #3963. (Returning an Error wasn't useful; it just caused a later error when actually using it because type checkers need to be functions.)
Chrome allowed some of these to be 'null' (allow `node.challenge` etc),
but FF didn't work. This will tell React to use node.setAttribute() to
set these values.
Tested in FF, Chrome, Safari. <keygen> isn't supported on IE.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen
The code sample in tip 18 in the docs contained a call to the
.getDOMNode() method which has been deprecated. The method call was
replaced with a call to React.findDOMNode(), which is the preferred way
of getting DOM nodes from a ref.
This heuristic isn't great because it relies on inspecting deep children which aren't guaranteed to be React elements. In particular, this was causing stack overflows in a component we had that used a *DOM node* as children, like `<DOMContainer>{node}</DOMContainer>`.
This reverts commits:
0a3aa8493a64c9d9d7620c58f4f6b18cf226e442086636747f
The new folder structure is organized around major packages that are expected to ship separately in some form.
`/isomorphic`
I moved classic/modern and children utils into a directory called "isomorphic" with the main export being ReactIsomorphic. This will eventually become the "react" package.
This includes all the dependencies that you might need to create a component without dependencies on the renderer/reconciler.
The rest moves into decoupled renderers.
`/renderers/dom/client` - This is the main renderer for DOM.
`/renderers/dom/server` - This is the server-side renderer for HTML strings.
`/addons` and `/test` - Same as before for now.
You're not supposed to take on a dependency inside another package.
Shared code is organized into a "shared" directory which is intended to support all the packages in that subdirectory. Meaning that once we swap to CommonJS modules, the only time you should use `..` is to target `../shared/` or `../../shared`.
E.g. `/shared/` is common utils that are used by everything.
`/renderers/shared/` is code that is shared by all renderers, such as the main reconciliation algorithm.
Shared code will likely be copied into each package rather than referenced. This allow us to have separate state and allow inlining and deadcode elimination.
Size comparison:
```
raw gz Compared to master @ 6ed98ec0c8
= = build/JSXTransformer.js
-15736 -3247 build/react-with-addons.js
+287 +7 build/react-with-addons.min.js
-14412 -2887 build/react.js
+274 +15 build/react.min.js
```
Differences mostly look to be various bits of whitespace that Babel ends up removing during its transforms (https://gist.github.com/spicyj/21ef31f4d95fb7a58daf). In minified files, mostly additions of `"use strict";`.
My old code here didn't work properly -- for a string child, getIteratorFn would return an iterator that gave each character as its own string, and we'd attempt to loop over that too.
Tests now work in Chrome again.
Also when reusing elements in multiple contexts -- before we were mutating each element to indicate its validity; now we mutate the array containing it (which we create, in the case of rest-arg children).
Fixes#2496. Fixes#3348.
Updated documentation to reflect that using React.cloneElement is the new way to copy an element and preserve `key` and `ref`.
Fixes#3432, closes#3447.
Update links to use https:// where it is supported. There's probably a lot
more that could be fixed, but these are the core ones I found (especially
the download links in order to prevent MITM attacks). Note that there are
some fb.me links that will redirect to http:// even while accessed over
https://, but this seemed like the best way to fix those for now.
NOTE: Only non-third-party files were modified. There are references to
http:// URLs in vendored/third-party files, but seems appropriate to fix
upstream for those rather than editing the files.
Also, copy one image locally to the blog, as it was hotlinking to a site
that did not support https://.
Last, use youtube-nocookie.com instead of youtube.com for video embeds,
as the former doesn't try to set a cookie on load (privacy enhancement).
I'm not super attached to this, but this feels cleaner to me. Might even be faster since flattenChildren doesn't use the index. Probably no change though.
If there are no listeners for `onSelect` yet, do not extract events. This way we can avoid issues where listeners have been set up for some event dependencies for `SelectEventPlugin`, but not all.
For instance, if `topMouseDown` has been registered but not `topMouseUp`, event extraction will set the `mouseDown` flag to true but never unset it. This leads to bugs when `onSelect` is registered and should be firing during normal key behavior. Since no `topMouseUp` has yet occurred to unset the flag, `onSelect` fails to fire.
When the style property existed, but was set to null, `this._previousStyleCopy`
was not set back to `null` causing an old value to persist. This broke setting
the style to `null` the next time.
Fixes#3606.
As far as I can tell, this is almost equivalent and is simpler. When a component's componentDidMount is called, all the listeners for that subtree will have been attached which I think is all that matters.
All testes successfully completed.
- for-in in browsers is slow, i replaced him by Object.keys + for(array)
- simple check of lengths let us not iterate if not same
- now we dont need to test for B's keys missing from A, because if length's is same and prev check success - objB hasn't more keys
- micro optimize: calling objB.hasOwnProperty
- micro optimize: replaced !objA || !obj for more speedy check === null
#inspiredby https://github.com/jurassix/react-immutable-render-mixin/pull/4
$REACT_WEBSITE_BRANCH in https://travis-ci.org/facebook/react/settings/env_vars now needs to point to the stable branch (currently 0.13-stable). I haven't tested the commit-and-push part of this but everything else works so I'm hopeful.
I ended up needing to add this attribute to work around a common IE bug, that clicking on a scrollbar gives focus to the scroll container. I needed to set it as MUST_USE_ATTRIBUTE or the attribute would not be passed through by React successfully.
remove trailing spaces
The current documentation states that the `<select>` tag supports `defaultChecked`, but it actually doesn't. I believe this documentation was meant to be written in the proposed order.
Non-working fiddle using `defaultChecked`: http://jsfiddle.net/jqs1hsLr/1/
Working fiddle using `defaultValue`: http://jsfiddle.net/nv7z0yzL/1/
Turns out lots of people write invalid HTML all the time and no one, including your browser or React, cares. Most invalid HTML combinations don't cause magic reparented nodes; only some do. The HTML5 parsing spec (https://html.spec.whatwg.org/multipage/syntax.html) specifies which tag combinations cause strange parsing behavior. I did my best to encode the logic here. It's more lenient than before in some cases, but more strict in others (before we didn't look at the whole stack of tags; now we warn with deeply nested `p` or `form` or `a` tags).
Rendering to `document.body` in the examples is conveniently short, but it can
be misleading at the same time, especially for newcomers.
While it's possible to render React components to `document.body`, any 3rd
party scripts can also mess up with it, and it can have unintended consequences
and be source of difficult-to-trace bugs.
Now that #1169 is fixed, the only thing this is used for is to determine whether `onTouchTap` causes touch listeners to be added. The only internal uses of TapEventPlugin are where touch events are already initialized (so this doesn't make a difference) and we don't support `onTouchTap` as part of the public API so this should be safe.
This reverts an early commit that made it so that elements from two
different owner in the same slot wouldn't share state.
That behavior was helpful, and we did hit a case which was solved by this.
However, this pattern is extremely uncommon. I've yet to even find the
original case, let alone any existing cases in our codebase.
Therefore, we're dropping this to simplify elements and enable new
optimizations.
We currently override a couple DOM components. We need to ensure everything we
override is still treated as a DOM component, even if it has a composite
component wrapper.
_mountImageIntoNode moved into ReactMount and wasn't being counted where it was supposed to be. In addition, all DOM elements are now wrapped in a composite wrapper but for the perf tools we want to skip over those or else we'll double-count (at least with the current accounting -- and that's effectively what we did before so this brings us back up to parity).
Fixes#3407.
Test Plan:
Used the jsbin from #3407 and saw similar output from this branch and 0.12:

$TRAVIS_COMMIT_RANGE was broken but it seems what we're doing is worse and
resulting in false negatives.
The result of the bad range was that we weren't running lint or tests for
things we should have been. It actually looks like $TRAVIS_COMMIT has been
wrong and it's not clear why this has been working at all.
ReactDOMComponent maintains a copy of the previous style
object to support in-place mutations of props.style.
This cached object was not cleared when the style
property was removed in a props update.
Fixes#3409
There is an exception when value or defaultValue is set but there are no
children as ReactDOMSelect tries to mark the first children as selected
even if there are no children.
I mis-parsed 'shallow copies' as adjective noun, instead of as a compound verb. I've adjusted the text to make it easier to parse on the first read, which should also help ESL learners to be able to parse it easier.
Summary:
Right now, if a component specifies a propType as, for example,
`myProp: React.PropTypes.shape`, without an actual shape
parameter, any prop type will be accepted, because
`React.PropTypes.shape` returns a function (the actual validator),
not an Error, currently indicating that propType checking passed.
This can create an unfortunate situation where a component looks
like it has fully specified `propTypes`, but in fact does not.
This commit addresses this by warning if a propType checker returns
anything non-falsy that is not an Error (currently all the library
PropTypes return null or an Error).
Test Plan:
Added a unit test; ran `jest` in the root repo directory.
Also ran `grunt lint` and `grunt test`
If either argument is not an object and unequal, then shallowEqual should return false.
If only one argument is an object, then shallowEqual should return false.
Fixes#3369
This is in response to #3207 to address concerns regarding third-party
scripts and browser plugins potentially altering DOM nodes within
document.body, causing problems with reconciliation.
Closes#3211.
Console is undefined in earlier versions of IE when it is not open. This causes an uncaught exception, and breaks applications in these versions of IE when attempting to warn when the console is closed.
Admittedly, console will usually be open when testing in development, but still React should not break the application when it is not.
Without this, transitioning from `<div onClick={null} />` to `<div />` triggered `willDeleteListener` to delete the `click` handler which caused problems; now, we only call `putListener` and `deleteListener` when we have an actual listener.
I now also clean up the `onClickListeners` map upon deletion and don't double-listen when updating the event listener.
* 'master' of https://github.com/facebook/react: (30 commits)
Expose --target flag on jsx executable
Contributing: cleanup quote style
Add Relay blog post
Fix long lines in vendor/fbtransform/visitors
lint vendor/*.js
fix .eslintignore
remove ballmer example
Fix a doc. cloneWithProps clones a ReactElement.
lint from root
Fixed mistake in jsdocs types for cloneWithProps
Put deprecation warning for classSet
Lint vendor/fbtransform as well
More warnings to ReactFragment.create
Warn when using constructor function directly
Move option parsing into react-tools proper.
Remove lodash devDependency
Added the immutability talk to the React.js Conf update.
Use same pathways for browser transforms as we use in react-tools
lint: remove spaces from array brackets
lint: remove spaces from object braces
...
When animating the max-height property in Safari, entering the leave state would trigger an animation to `max-height: 0`. Then when the active state kicked in, it would jump and didn't really look right. Moving the `transition` css property to the active version fixed the issue for me and worked on Safari, Chrome and Firefox. Unfortunately I'm not in a position to test in IE at the moment, but I'll do that at my first convenience tomorrow.
Fixes#1297.
onMouseEnter and onMouseLeave shouldn't *actually* use direct dispatch, but doing so is more useful than doing nothing (and I don't think it precludes adding proper enter/leave dispatching later, either).
Test Plan:
grunt test
If several children complete leaving before rendering TransitionGroup,
only the last one was removed. This could easily happen if
callback in componentWillLeave is called synchronously and several items
are removed from array. The other case is when ReactCSSTransitionGroup
has transitionLeave={false} and array is also cleaned up.
The bug was happening because this.state.children was used as a base for
children removal and it wasn't updated until the render, so only the last
removal was actually happening.
Fix involves keeping the updated children state between invocations of
_handleDoneLeaving. After updating this.state and rendering,
updatedState is cleaned up and ready for subsequent array modifications.
Test case included.
2014-11-17 15:15:54 -08:00
742 changed files with 50135 additions and 35056 deletions
- Fixed bug where events wouldn't fire in old browsers when using React in development mode
- Fixed bug preventing use of `dangerouslySetInnerHTML` with Closure Compiler Advanced mode
- Added support for `srcLang`, `default`, and `kind` attributes for `<track>` elements
- Added support for `color` attribute
- Ensured legacy `.props` access on DOM nodes is updated on re-renders
### React TestUtils Add-on
- Fixed `scryRenderedDOMComponentsWithClass` so it works with SVG
### React CSSTransitionGroup Add-on
- Fix bug preventing `0` to be used as a timeout value
### React on Bower
- Added `react-dom.js` to `main` to improve compatibility with tooling
## 0.14.0 (October 7, 2015)
### Major changes
- Split the main `react` package into two: `react` and `react-dom`. This paves the way to writing components that can be shared between the web version of React and React Native. This means you will need to include both files and some functions have been moved from `React` to `ReactDOM`.
- Addons have been moved to seperate packages (`react-addons-clone-with-props`, `react-addons-create-fragment`, `react-addons-css-transition-group`, `react-addons-linked-state-mixin`, `react-addons-perf`, `react-addons-pure-render-mixin`, `react-addons-shallow-compare`, `react-addons-test-utils`, `react-addons-transition-group`, `react-addons-update`, `ReactDOM.unstable_batchedUpdates`).
- Stateless functional components - React components were previously created using React.createClass or using ES6 classes. This release adds a [new syntax](https://facebook.github.io/react/docs/reusable-components.html#stateless-functions) where a user defines a single [stateless render function](https://facebook.github.io/react/docs/reusable-components.html#stateless-functions) (with one parameter: `props`) which returns a JSX element, and this function may be used as a component.
- Refs to DOM components as the DOM node itself. Previously the only useful thing you can do with a DOM component is call `getDOMNode()` to get the underlying DOM node. Starting with this release, a ref to a DOM component _is_ the actual DOM node. **Note that refs to custom (user-defined) components work exactly as before; only the built-in DOM components are affected by this change.**
### Breaking changes
-`React.initializeTouchEvents` is no longer necessary and has been removed completely. Touch events now work automatically.
- Add-Ons: Due to the DOM node refs change mentioned above, `TestUtils.findAllInRenderedTree` and related helpers are no longer able to take a DOM component, only a custom component.
- The `props` object is now frozen, so mutating props after creating a component element is no longer supported. In most cases, [`React.cloneElement`](/react/docs/top-level-api.html#react.cloneelement) should be used instead. This change makes your components easier to reason about and enables the compiler optimizations mentioned above.
- Plain objects are no longer supported as React children; arrays should be used instead. You can use the [`createFragment`](/react/docs/create-fragment.html) helper to migrate, which now returns an array.
- Add-Ons: `classSet` has been removed. Use [classnames](https://github.com/JedWatson/classnames) instead.
- Web components (custom elements) now use native property names. Eg: `class` instead of `className`.
### Deprecations
-`this.getDOMNode()` is now deprecated and `ReactDOM.findDOMNode(this)` can be used instead. Note that in the common case, `findDOMNode` is now unnecessary since a ref to the DOM component is now the actual DOM node.
-`setProps` and `replaceProps` are now deprecated. Instead, call ReactDOM.render again at the top level with the new props.
- ES6 component classes must now extend `React.Component` in order to enable stateless function components. The [ES3 module pattern](/react/blog/2015/01/27/react-v0.13.0-beta-1.html#other-languages) will continue to work.
- Reusing and mutating a `style` object between renders has been deprecated. This mirrors our change to freeze the `props` object.
- Add-Ons: `cloneWithProps` is now deprecated. Use [`React.cloneElement`](/react/docs/top-level-api.html#react.cloneelement) instead (unlike `cloneWithProps`, `cloneElement` does not merge `className` or `style` automatically; you can merge them manually if needed).
- Add-Ons: To improve reliability, `CSSTransitionGroup` will no longer listen to transition events. Instead, you should specify transition durations manually using props such as `transitionEnterTimeout={500}`.
### Notable enhancements
- Added `React.Children.toArray` which takes a nested children object and returns a flat array with keys assigned to each child. This helper makes it easier to manipulate collections of children in your `render` methods, especially if you want to reorder or slice `this.props.children` before passing it down. In addition, `React.Children.map` now returns plain arrays too.
- React uses `console.error` instead of `console.warn` for warnings so that browsers show a full stack trace in the console. (Our warnings appear when you use patterns that will break in future releases and for code that is likely to behave unexpectedly, so we do consider our warnings to be “must-fix” errors.)
- Previously, including untrusted objects as React children [could result in an XSS security vulnerability](http://danlec.com/blog/xss-via-a-spoofed-react-element). This problem should be avoided by properly validating input at the application layer and by never passing untrusted objects around your application code. As an additional layer of protection, [React now tags elements](https://github.com/facebook/react/pull/4832) with a specific [ES2015 (ES6) `Symbol`](http://www.2ality.com/2014/12/es6-symbols.html) in browsers that support it, in order to ensure that React never considers untrusted JSON to be a valid element. If this extra security protection is important to you, you should add a `Symbol` polyfill for older browsers, such as the one included by [Babel’s polyfill](http://babeljs.io/docs/usage/polyfill/).
- When possible, React DOM now generates XHTML-compatible markup.
- React DOM now supports these standard HTML attributes: `capture`, `challenge`, `inputMode`, `is`, `keyParams`, `keyType`, `minLength`, `summary`, `wrap`. It also now supports these non-standard attributes: `autoSave`, `results`, `security`.
- React DOM now supports these SVG attributes, which render into namespaced attributes: `xlinkActuate`, `xlinkArcrole`, `xlinkHref`, `xlinkRole`, `xlinkShow`, `xlinkTitle`, `xlinkType`, `xmlBase`, `xmlLang`, `xmlSpace`.
- The `image` SVG tag is now supported by React DOM.
- In React DOM, arbitrary attributes are supported on custom elements (those with a hyphen in the tag name or an `is="..."` attribute).
- React DOM now supports these media events on `audio` and `video` tags: `onAbort`, `onCanPlay`, `onCanPlayThrough`, `onDurationChange`, `onEmptied`, `onEncrypted`, `onEnded`, `onError`, `onLoadedData`, `onLoadedMetadata`, `onLoadStart`, `onPause`, `onPlay`, `onPlaying`, `onProgress`, `onRateChange`, `onSeeked`, `onSeeking`, `onStalled`, `onSuspend`, `onTimeUpdate`, `onVolumeChange`, `onWaiting`.
- Many small performance improvements have been made.
- Many warnings show more context than before.
- Add-Ons: A [`shallowCompare`](https://github.com/facebook/react/pull/3355) add-on has been added as a migration path for `PureRenderMixin` in ES6 classes.
- Add-Ons: `CSSTransitionGroup` can now use [custom class names](https://github.com/facebook/react/blob/48942b85/docs/docs/10.1-animation.md#custom-classes) instead of appending `-enter-active` or similar to the transition name.
### New helpful warnings
- React DOM now warns you when nesting HTML elements invalidly, which helps you avoid surprising errors during updates.
- Passing `document.body` directly as the container to `ReactDOM.render` now gives a warning as doing so can cause problems with browser extensions that modify the DOM.
- Using multiple instances of React together is not supported, so we now warn when we detect this case to help you avoid running into the resulting problems.
### Notable bug fixes
- Click events are handled by React DOM more reliably in mobile browsers, particularly in Mobile Safari.
- SVG elements are created with the correct namespace in more cases.
- React DOM now renders `<option>` elements with multiple text children properly and renders `<select>` elements on the server with the correct option selected.
- When two separate copies of React add nodes to the same document (including when a browser extension uses React), React DOM tries harder not to throw exceptions during event handling.
- Using non-lowercase HTML tag names in React DOM (e.g., `React.createElement('DIV')`) no longer causes problems, though we continue to recommend lowercase for consistency with the JSX tag name convention (lowercase names refer to built-in components, capitalized names refer to custom components).
- React DOM understands that these CSS properties are unitless and does not append “px” to their values: `animationIterationCount`, `boxOrdinalGroup`, `flexOrder`, `tabSize`, `stopOpacity`.
- Add-Ons: When using the test utils, `Simulate.mouseEnter` and `Simulate.mouseLeave` now work.
- Add-Ons: ReactTransitionGroup now correctly handles multiple nodes being removed simultaneously.
### React Tools / Babel
#### Breaking Changes
- The `react-tools` package and `JSXTransformer.js` browser file [have been deprecated](/react/blog/2015/06/12/deprecating-jstransform-and-react-tools.html). You can continue using version `0.13.3` of both, but we no longer support them and recommend migrating to [Babel](http://babeljs.io/), which has built-in support for React and JSX.
#### New Features
- Babel 5.8.24 introduces **Inlining React elements:** The `optimisation.react.inlineElements` transform converts JSX elements to object literals like `{type: 'div', props: ...}` instead of calls to `React.createElement`. This should only be enabled in production, since it disables some development warnings/checks.
- Babel 5.8.24 introduces **Constant hoisting for React elements:** The `optimisation.react.constantElements` transform hoists element creation to the top level for subtrees that are fully static, which reduces calls to `React.createElement` and the resulting allocations. More importantly, it tells React that the subtree hasn’t changed so React can completely skip it when reconciling. This should only be enabled in production, since it disables some development warnings/checks.
## 0.13.3 (May 8, 2015)
### React Core
@@ -126,6 +219,12 @@
*`es3` restores the previous default behavior. An additional transform is added here to ensure the use of reserved words as properties is safe (eg `this.static` will become `this['static']` for IE8 compatibility).
* The transform for the call spread operator has also been enabled.
### JSXTransformer
#### Breaking Changes
* The return value of `transform` now contains `sourceMap` as a JS object already, not an instance of `SourceMapGenerator`.
React is one of Facebook's first open source projects that is both under very active development and is also being used to ship code to everybody on [facebook.com](https://www.facebook.com). We're still working out the kinks to make contributing to this project as easy and transparent as possible, but we're not quite there yet. Hopefully this document makes the process for contributing clear and preempts some questions you may have.
React is one of Facebook's first open source projects that is both under very active development and is also being used to ship code to everybody on [facebook.com](https://www.facebook.com). We're still working out the kinks to make contributing to this project as easy and transparent as possible, but we're not quite there yet. Hopefully this document makes the process for contributing clear and answers some questions that you may have.
## [Code of Conduct](https://code.facebook.com/codeofconduct)
Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read [the full text](https://code.facebook.com/codeofconduct) so that you can understand what actions will and will not be tolerated.
## Our Development Process
@@ -23,11 +27,11 @@ The core team will be monitoring for pull requests. When we get one, we'll run s
5. Make sure your code lints (`grunt lint`) - we've done our best to make sure these rules match our internal linting guidelines.
6. If you haven't already, complete the CLA.
### Contributor License Agreement ("CLA")
### Contributor License Agreement (CLA)
In order to accept your pull request, we need you to submit a CLA. You only need to do this once, so if you've done this for another Facebook open source project, you're good to go. If you are submitting a pull request for the first time, just let us know that you have completed the CLA and we can cross-check with your GitHub username.
[Complete your CLA here](https://code.facebook.com/cla)
[Complete your CLA here.](https://code.facebook.com/cla)
## Bugs
@@ -50,15 +54,20 @@ Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
## Style Guide
### Code
Our linter will catch most styling issues that may exist in your code.
You can check the status of your code styling by simply running: `grunt lint`
* Use semicolons;
* Commas last,
However, there are still some styles that the linter cannot pick up. If you are unsure about something, looking at [Airbnb's Style Guide](https://github.com/airbnb/javascript) will guide you in the right direction.
### Code Conventions
* Use semicolons `;`
* Commas last `,`
* 2 spaces for indentation (no tabs)
* Prefer `'` over `"`
*`'use strict';`
* 80 character line length
*"Attractive"
*Write "attractive" code
* Do not use the optional parameters of `setTimeout` and `setInterval`
React is a JavaScript library for building user interfaces.
@@ -8,7 +8,7 @@ React is a JavaScript library for building user interfaces.
**NEW**! Check out our newest project [React Native](https://github.com/facebook/react-native), which uses React and JavaScript to create native mobile apps.
[Learn how to use React in your own project.](https://facebook.github.io/react/docs/getting-started.html).
[Learn how to use React in your own project](https://facebook.github.io/react/docs/getting-started.html).
## Examples
@@ -21,7 +21,7 @@ var HelloMessage = React.createClass({
}
});
React.render(
ReactDOM.render(
<HelloMessagename="John"/>,
document.getElementById('container')
);
@@ -37,12 +37,12 @@ The fastest way to get started is to serve JavaScript from the CDN (also availab
We've also built a [starter kit](https://facebook.github.io/react/downloads/react-0.13.3.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
We've also built a [starter kit](https://facebook.github.io/react/downloads/react-0.14.1.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:
@@ -60,7 +60,7 @@ The process to build `react.js` is built entirely on top of node.js, using many
#### Prerequisites
* You have `node` installed at v0.10.0+ (it might work at lower versions, we just haven't tested).
* You have `node` installed at v0.10.0+ (it might work at lower versions, we just haven't tested) and `npm` at v2.0.0+.
* You are familiar with `npm` and know whether or not you need to use `sudo` when installing packages globally.
* You are familiar with `git`.
@@ -86,8 +86,6 @@ We use grunt to automate many tasks. Run `grunt -h` to see a mostly complete lis
grunt test
# Build and run tests in your browser
grunt test --debug
# For speed, you can use fasttest and add --filter to only run one test
grunt fasttest --filter=ReactIdentity
# Lint the code with ESLint
grunt lint
# Wipe out build directory
@@ -105,3 +103,6 @@ Examples provided in this repository and in the documentation are [separately li
### More…
There's only so much we can cram in here. To read more about the community and guidelines for submitting pull requests, please read the [Contributing document](CONTRIBUTING.md).
## Troubleshooting
See the [Troubleshooting Guide](https://github.com/facebook/react/wiki/Troubleshooting)
@@ -33,7 +33,7 @@ There are other features of ES6 we're already using in core. I'm sure we'll see
## Context
While we haven't documented `context`, it exists in some form in React already. It exists as a way to pass values through a tree without having to use props at every single point. We've seen this need crop up time and time again, so we want to make this as easy as possible. It's use has performance tradeoffs, and there are known weaknesses in our implementation, so we want to make sure this is a solid feature.
While we haven't documented `context`, it exists in some form in React already. It exists as a way to pass values through a tree without having to use props at every single point. We've seen this need crop up time and time again, so we want to make this as easy as possible. Its use has performance tradeoffs, and there are known weaknesses in our implementation, so we want to make sure this is a solid feature.
@@ -77,7 +77,7 @@ We believe there are a number of weakness in typical REST systems, ones that are
* Fetching complicated object graphs require multiple round trips between the client and server to render single views. For mobile applications operating in variable network conditions, these multiple roundtrips are highly undesirable.
* Invariably fields and additional data are added to REST endpoints as the system requirements change. However, old clients also receive this additional data as well, because the data fetching specification is encoded on the server rather than the client. As result, these payloads tend to grow over time for all clients. When this becomes a problem for a system, one solution is to overlay a versioning system onto the REST endpoints. Versioning also complicates a server, and results in code duplication, spaghetti code, or a sophisticated, hand-rolled infrastructure to manage it. Another solution to limit over-fetching is to provide multiple views – such as “compact” vs “full” – of the same REST endpoint, however this coarse granularity often does not offer adequate flexibility.
* REST endpoints are usually weakly-typed and lack machine-readable metadata. While there is much debate about the merits of strong- versus weak-typing in distributed systems, we believe in strong typing because of the correctness guarantees and tooling opportunities it provides. Developer deal with systems that lack this metadata by inspecting frequently out-of-date documentation and then writing code against the documentation.
* REST endpoints are usually weakly-typed and lack machine-readable metadata. While there is much debate about the merits of strong- versus weak-typing in distributed systems, we believe in strong typing because of the correctness guarantees and tooling opportunities it provides. Developers deal with systems that lack this metadata by inspecting frequently out-of-date documentation and then writing code against the documentation.
* Many of these attributes are linked to the fact that “REST is intended for long-lived network-based applications that span multiple organizations” [according to its inventor](http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven). This is not a requirement for APIs that serve a client app built within the same organization.
Nearly all externally facing REST APIs we know of trend or end up in these non-ideal states, as well as nearly all *internal* REST APIs. The consequences of opaqueness and over-fetching are more severe in internal APIs since their velocity of change and level of usage is almost always higher.
@@ -90,7 +90,7 @@ Because of multiple round-trips and over-fetching, applications built in the RES
Many applications have no formalized client-server contract. Product developers access server capabilities through *ad hoc* endpoints and write custom code to fetch the data they need. Servers define procedures, and they return data. This approach has the virtue of simplicity, but can often become untenable as systems age.
* These systems typically define a custom endpoint per view. For systems with a wide surface area this can quickly grow into a maintenance nightmare of orphaned endpoints, inconsistent tooling, and massive server code duplication. Disciplined engineering organizations can mitigate these issues with great engineering practices, high quality abstractions, and custom tooling. However, given our experience we believe that custom endpoints tend to lead to entropic server codebases.
* Much like REST, the payloads of custom endpoints grow monotonically (even with mitigation from versioning systems) as the server evolves. Deployed clients cannot break, and, with rapid release cycles and backwards compatibility guarantees, distributed applications will have large numbers of extant versions. Under these constraints it is difficult remove data from a custom endpoint.
* Much like REST, the payloads of custom endpoints grow monotonically (even with mitigation from versioning systems) as the server evolves. Deployed clients cannot break, and, with rapid release cycles and backwards compatibility guarantees, distributed applications will have large numbers of extant versions. Under these constraints it is difficult to remove data from a custom endpoint.
* Custom endpoints tend to – for a client developer – create a clunky, multi-language, multi-environment development process. No matter if the data has been accessed before in a different view, they are required to first change the custom endpoint, then deploy that code to a server accessible from a mobile device, and only then change the client to utilize that data. In GraphQL – unless the data in the view is completely new to the entire system – a product developer adds a field to a GraphQL query and the work on the client continues unabated.
* Much like REST, most systems with custom endpoints do not have a formalized type system, which eliminates the possibility for the tools and guarantees that introspective type systems can provide. Some custom-endpoint-driven systems do use a strongly typed serialization scheme, such as Protocol Buffers, Thrift, or XML. Those do allow for direct parsing of responses into typed classes and eliminating boilerplate shuffling from JSON into handwritten classes. These systems are as not as expressive and flexible as GraphQL, and the other downsides of *ad hoc* endpoints remain.
@@ -28,7 +28,7 @@ If you can’t use `npm` yet, we also provide pre-built browser builds for your
Dev build with warnings: <https://fb.me/react-dom-0.14.0-rc1.js>
Minified build for production: <https://fb.me/react-dom-0.14.0-rc1.min.js>
These builds are also available in the `react` and `react-dom` packages on bower.
These builds are also available in the `react` package on bower.
## Changelog
@@ -57,7 +57,7 @@ These builds are also available in the `react` and `react-dom` packages on bower
ReactDOM.render(<MyComponent />, node);
```
We’ve published the [automated codemod script](https://github.com/facebook/react/blob/master/packages/react-codemod/README.md) we used at Facebook to help you with this transition.
We’ve published the [automated codemod script](https://github.com/reactjs/react-codemod/blob/master/README.md) we used at Facebook to help you with this transition.
The add-ons have moved to separate packages as well: `react-addons-clone-with-props`, `react-addons-create-fragment`, `react-addons-css-transition-group`, `react-addons-linked-state-mixin`, `react-addons-perf`, `react-addons-pure-render-mixin`, `react-addons-shallow-compare`, `react-addons-test-utils`, `react-addons-transition-group`, and `react-addons-update`, plus `ReactDOM.unstable_batchedUpdates` in `react-dom`.
We’re happy to announce the release of React 0.14 today! This release has a few major changes, primarily designed to simplify the code you write every day and to better support environments like React Native.
If you tried the release candidate, thank you – your support is invaluable and we've fixed a few bugs that you reported.
As with all of our releases, we consider this version to be stable enough to use in production and recommend that you upgrade in order to take advantage of our latest improvements.
## Upgrade Guide
Like always, we have a few breaking changes in this release. We know changes can be painful (the Facebook codebase has over 15,000 React components), so we always try to make changes gradually in order to minimize the pain.
If your code is free of warnings when running under React 0.13, upgrading should be easy. We have two new small breaking changes that didn't give a warning in 0.13 (see below). Every new change in 0.14, including the major changes below, is introduced with a runtime warning and will work as before until 0.15, so you don't have to worry about your app breaking with this upgrade.
For the two major changes which require significant code changes, we've included [codemod scripts](https://github.com/reactjs/react-codemod/blob/master/README.md) to help you upgrade your code automatically.
See the changelog below for more details.
## Installation
We recommend using React from `npm` and using a tool like browserify or webpack to build your code into a single bundle. To install the two packages:
*`npm install --save react react-dom`
Remember that by default, React runs extra checks and provides helpful warnings in development mode. When deploying your app, set the `NODE_ENV` environment variable to `production` to use the production build of React which does not include the development warnings and runs significantly faster.
If you can’t use `npm` yet, we provide pre-built browser builds for your convenience, which are also available in the `react` package on bower.
* **React**
Dev build with warnings: <https://fb.me/react-0.14.0.js>
Minified build for production: <https://fb.me/react-0.14.0.min.js>
***React with Add-Ons**
Dev build with warnings: <https://fb.me/react-with-addons-0.14.0.js>
Minified build for production: <https://fb.me/react-with-addons-0.14.0.min.js>
***React DOM** (include React in the page before React DOM)
Dev build with warnings: <https://fb.me/react-dom-0.14.0.js>
Minified build for production: <https://fb.me/react-dom-0.14.0.min.js>
## Changelog
### Major changes
- #### Two Packages: React and React DOM
As we look at packages like [react-native](https://github.com/facebook/react-native), [react-art](https://github.com/reactjs/react-art), [react-canvas](https://github.com/Flipboard/react-canvas), and [react-three](https://github.com/Izzimach/react-three), it has become clear that the beauty and essence of React has nothing to do with browsers or the DOM.
To make this more clear and to make it easier to build more environments that React can render to, we’re splitting the main `react` package into two: `react` and `react-dom`. **This paves the way to writing components that can be shared between the web version of React and React Native.** We don’t expect all the code in an app to be shared, but we want to be able to share the components that do behave the same across platforms.
The `react` package contains `React.createElement`, `.createClass`, `.Component`, `.PropTypes`, `.Children`, and the other helpers related to elements and component classes. We think of these as the [_isomorphic_](http://nerds.airbnb.com/isomorphic-javascript-future-web-apps/) or [_universal_](https://medium.com/@mjackson/universal-javascript-4761051b7ae9) helpers that you need to build components.
The `react-dom` package has `ReactDOM.render`, `.unmountComponentAtNode`, and `.findDOMNode`. In `react-dom/server` we have server-side rendering support with `ReactDOMServer.renderToString` and `.renderToStaticMarkup`.
```js
var React = require('react');
var ReactDOM = require('react-dom');
var MyComponent = React.createClass({
render: function() {
return <div>Hello World</div>;
}
});
ReactDOM.render(<MyComponent />, node);
```
The old names will continue to work with a warning until 0.15 is released, and we’ve published the [automated codemod script](https://github.com/reactjs/react-codemod/blob/master/README.md) we used at Facebook to help you with this transition.
The add-ons have moved to separate packages as well:
- `react-addons-clone-with-props`
- `react-addons-create-fragment`
- `react-addons-css-transition-group`
- `react-addons-linked-state-mixin`
- `react-addons-perf`
- `react-addons-pure-render-mixin`
- `react-addons-shallow-compare`
- `react-addons-test-utils`
- `react-addons-transition-group`
- `react-addons-update`
- `ReactDOM.unstable_batchedUpdates` in `react-dom`.
For now, please use matching versions of `react` and `react-dom` (and the add-ons, if you use them) in your apps to avoid versioning problems.
- #### DOM node refs
The other big change we’re making in this release is exposing refs to DOM components as the DOM node itself. That means: we looked at what you can do with a `ref` to a React DOM component and realized that the only useful thing you can do with it is call `this.refs.giraffe.getDOMNode()` to get the underlying DOM node. Starting with this release, `this.refs.giraffe` _is_ the actual DOM node. **Note that refs to custom (user-defined) components work exactly as before; only the built-in DOM components are affected by this change.**
// Previously: var input = this.refs.giraffe.getDOMNode();
var input = this.refs.giraffe;
alert(input.value);
}
});
```
This change also applies to the return result of `ReactDOM.render` when passing a DOM node as the top component. As with refs, this change does not affect custom components.
With this change, we’re deprecating `.getDOMNode()` and replacing it with `ReactDOM.findDOMNode` (see below). If your components are currently using `.getDOMNode()`, they will continue to work with a warning until 0.15.
- #### Stateless functional components
In idiomatic React code, most of the components you write will be stateless, simply composing other components. We’re introducing a new, simpler syntax for these components where you can take `props` as an argument and return the element you want to render:
```js
// A functional component using an ES2015 (ES6) arrow function:
var Aquarium = (props) => {
var fish = getFish(props.species);
return <Tank>{fish}</Tank>;
};
// Or with destructuring and an implicit return, simply:
var Aquarium = ({species}) => (
<Tank>
{getFish(species)}
</Tank>
);
// Then use: <Aquarium species="rainbowfish" />
```
These components behave just like a React class with only a `render` method defined. Since no component instance is created for a functional component, any `ref` added to one will evaluate to `null`. Functional components do not have lifecycle methods, but you can set `.propTypes` and `.defaultProps` as properties on the function.
This pattern is designed to encourage the creation of these simple components that should comprise large portions of your apps. In the future, we’ll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations.
- #### Deprecation of react-tools
The `react-tools` package and `JSXTransformer.js` browser file [have been deprecated](/react/blog/2015/06/12/deprecating-jstransform-and-react-tools.html). You can continue using version `0.13.3` of both, but we no longer support them and recommend migrating to [Babel](http://babeljs.io/), which has built-in support for React and JSX.
- #### Compiler optimizations
React now supports two compiler optimizations that can be enabled in Babel 5.8.24 and newer. Both of these transforms **should be enabled only in production** (e.g., just before minifying your code) because although they improve runtime performance, they make warning messages more cryptic and skip important checks that happen in development mode, including propTypes.
**Inlining React elements:** The `optimisation.react.inlineElements` transform converts JSX elements to object literals like `{type: 'div', props: ...}` instead of calls to `React.createElement`.
**Constant hoisting for React elements:** The `optimisation.react.constantElements` transform hoists element creation to the top level for subtrees that are fully static, which reduces calls to `React.createElement` and the resulting allocations. More importantly, it tells React that the subtree hasn’t changed so React can completely skip it when reconciling.
### Breaking changes
In almost all cases, we change our APIs gradually and warn for at least one release to give you time to clean up your code. These two breaking changes did not have a warning in 0.13 but should be easy to find and clean up:
- `React.initializeTouchEvents` is no longer necessary and has been removed completely. Touch events now work automatically.
- Add-Ons: Due to the DOM node refs change mentioned above, `TestUtils.findAllInRenderedTree` and related helpers are no longer able to take a DOM component, only a custom component.
These three breaking changes had a warning in 0.13, so you shouldn’t have to do anything if your code is already free of warnings:
- The `props` object is now frozen, so mutating props after creating a component element is no longer supported. In most cases, [`React.cloneElement`](/react/docs/top-level-api.html#react.cloneelement) should be used instead. This change makes your components easier to reason about and enables the compiler optimizations mentioned above.
- Plain objects are no longer supported as React children; arrays should be used instead. You can use the [`createFragment`](/react/docs/create-fragment.html) helper to migrate, which now returns an array.
- Add-Ons: `classSet` has been removed. Use [classnames](https://github.com/JedWatson/classnames) instead.
### New deprecations, introduced with a warning
Each of these changes will continue to work as before with a new warning until the release of 0.15 so you can upgrade your code gradually.
- Due to the DOM node refs change mentioned above, `this.getDOMNode()` is now deprecated and `ReactDOM.findDOMNode(this)` can be used instead. Note that in most cases, calling `findDOMNode` is now unnecessary – see the example above in the “DOM node refs” section.
With each returned DOM node, we've added a `getDOMNode` method for backwards compatibility that will work with a warning until 0.15. If you have a large codebase, you can use our [automated codemod script](https://github.com/reactjs/react-codemod/blob/master/README.md) to change your code automatically.
- `setProps` and `replaceProps` are now deprecated. Instead, call ReactDOM.render again at the top level with the new props.
- ES6 component classes must now extend `React.Component` in order to enable stateless function components. The [ES3 module pattern](/react/blog/2015/01/27/react-v0.13.0-beta-1.html#other-languages) will continue to work.
- Reusing and mutating a `style` object between renders has been deprecated. This mirrors our change to freeze the `props` object.
- Add-Ons: `cloneWithProps` is now deprecated. Use [`React.cloneElement`](/react/docs/top-level-api.html#react.cloneelement) instead (unlike `cloneWithProps`, `cloneElement` does not merge `className` or `style` automatically; you can merge them manually if needed).
- Add-Ons: To improve reliability, `CSSTransitionGroup` will no longer listen to transition events. Instead, you should specify transition durations manually using props such as `transitionEnterTimeout={500}`.
### Notable enhancements
- Added `React.Children.toArray` which takes a nested children object and returns a flat array with keys assigned to each child. This helper makes it easier to manipulate collections of children in your `render` methods, especially if you want to reorder or slice `this.props.children` before passing it down. In addition, `React.Children.map` now returns plain arrays too.
- React uses `console.error` instead of `console.warn` for warnings so that browsers show a full stack trace in the console. (Our warnings appear when you use patterns that will break in future releases and for code that is likely to behave unexpectedly, so we do consider our warnings to be “must-fix” errors.)
- Previously, including untrusted objects as React children [could result in an XSS security vulnerability](http://danlec.com/blog/xss-via-a-spoofed-react-element). This problem should be avoided by properly validating input at the application layer and by never passing untrusted objects around your application code. As an additional layer of protection, [React now tags elements](https://github.com/facebook/react/pull/4832) with a specific [ES2015 (ES6) `Symbol`] (http://www.2ality.com/2014/12/es6-symbols.html) in browsers that support it, in order to ensure that React never considers untrusted JSON to be a valid element. If this extra security protection is important to you, you should add a `Symbol` polyfill for older browsers, such as the one included by [Babel’s polyfill](http://babeljs.io/docs/usage/polyfill/).
- When possible, React DOM now generates XHTML-compatible markup.
- React DOM now supports these standard HTML attributes: `capture`, `challenge`, `inputMode`, `is`, `keyParams`, `keyType`, `minLength`, `summary`, `wrap`. It also now supports these non-standard attributes: `autoSave`, `results`, `security`.
- React DOM now supports these SVG attributes, which render into namespaced attributes: `xlinkActuate`, `xlinkArcrole`, `xlinkHref`, `xlinkRole`, `xlinkShow`, `xlinkTitle`, `xlinkType`, `xmlBase`, `xmlLang`, `xmlSpace`.
- The `image` SVG tag is now supported by React DOM.
- In React DOM, arbitrary attributes are supported on custom elements (those with a hyphen in the tag name or an `is="..."` attribute).
- React DOM now supports these media events on `audio` and `video` tags: `onAbort`, `onCanPlay`, `onCanPlayThrough`, `onDurationChange`, `onEmptied`, `onEncrypted`, `onEnded`, `onError`, `onLoadedData`, `onLoadedMetadata`, `onLoadStart`, `onPause`, `onPlay`, `onPlaying`, `onProgress`, `onRateChange`, `onSeeked`, `onSeeking`, `onStalled`, `onSuspend`, `onTimeUpdate`, `onVolumeChange`, `onWaiting`.
- Many small performance improvements have been made.
- Many warnings show more context than before.
- Add-Ons: A [`shallowCompare`](https://github.com/facebook/react/pull/3355) add-on has been added as a migration path for `PureRenderMixin` in ES6 classes.
- Add-Ons: `CSSTransitionGroup` can now use [custom class names](https://github.com/facebook/react/blob/48942b85/docs/docs/10.1-animation.md#custom-classes) instead of appending `-enter-active` or similar to the transition name.
### New helpful warnings
- React DOM now warns you when nesting HTML elements invalidly, which helps you avoid surprising errors during updates.
- Passing `document.body` directly as the container to `ReactDOM.render` now gives a warning as doing so can cause problems with browser extensions that modify the DOM.
- Using multiple instances of React together is not supported, so we now warn when we detect this case to help you avoid running into the resulting problems.
### Notable bug fixes
- Click events are handled by React DOM more reliably in mobile browsers, particularly in Mobile Safari.
- SVG elements are created with the correct namespace in more cases.
- React DOM now renders `<option>` elements with multiple text children properly and renders `<select>` elements on the server with the correct option selected.
- When two separate copies of React add nodes to the same document (including when a browser extension uses React), React DOM tries harder not to throw exceptions during event handling.
- Using non-lowercase HTML tag names in React DOM (e.g., `React.createElement('DIV')`) no longer causes problems, though we continue to recommend lowercase for consistency with the JSX tag name convention (lowercase names refer to built-in components, capitalized names refer to custom components).
- React DOM understands that these CSS properties are unitless and does not append “px” to their values: `animationIterationCount`, `boxOrdinalGroup`, `flexOrder`, `tabSize`, `stopOpacity`.
- Add-Ons: When using the test utils, `Simulate.mouseEnter` and `Simulate.mouseLeave` now work.
- Add-Ons: ReactTransitionGroup now correctly handles multiple nodes being removed simultaneously.
TL;DR: Slack decided that Reactiflux had too many members and disabled new invites. Reactiflux is moving to Discord. Join us: [http://join.reactiflux.com](http://join.reactiflux.com/)
## What happened with Slack?
A few weeks ago, Reactiflux reached 7,500 members on Slack. Shortly after, Slack decided we were too big and disabled invites. There was no way for new users to join. Many of us were sad and upset. We loved Slack. Our community was built around it.
We reached out to Slack several times, but their decision was firm. Our large community caused performance issues. Slack wants to focus on building a great product for teams, not necessarily large open communities. Losing focus and building for too many use cases always leads to product bloat, and eventually a decrease in quality.
## So… why Discord?
After a [long and thorough debate](https://github.com/reactiflux/volunteers/issues/25), Discord quickly emerged as the most promising service. After just a few days, 400 members had joined the Discord server, and many already loved it.
### Easiest to join
Discord is the easiest platform to join. New users can immediately join our conversations without having to create an account. All they need to do is provide a name. No permission granting, no password, no email confirmation.
This is critically useful for us, and will make Reactiflux even more open and accessible.
### Great apps
Out of all of the services we’ve tried, Discord’s apps are by far the most polished. They are well designed, easy to use, and surprisingly fast. In addition to the web app, they have mobile apps on both iOS and Android as well as desktop apps for OS X and Windows, with Linux support coming soon.
Their desktop apps are built with React and Electron, and their iOS app is built with React Native.
### Moderation tools
So far, we’ve been fortunate not to have to deal with spammers and trolls. As our community continues to grow, that might change. Unsurprisingly, Discord is the only app we’ve seen with legitimate moderation tools. It was built for gaming communities, after all.
### Great multiple Server support
Your Discord account works with every Discord server, which is the equivalent of a Slack team. You don’t need to create a new account every time you join a new team. You can join new servers in one click, and it’s very easy to switch between them. Discord messages also work across servers, so your personal conversations are not scoped to a single server.
Instead of having one huge, crowded Reactiflux server, we can branch off closely related channels into sub-servers. Communities will start overlapping, and it will be easy to interact with non-Reactiflux channels.
### It’s hosted
Self-hosted apps require maintenance. We’re all busy, and we can barely find the time to keep our landing page up to date and running smoothly. More than anything, we need a stable platform, and we don’t have the resources to guarantee that right now.
It’s a much safer bet to offload the hosting to Discord, who is already keeping the lights on for all their users.
### We like the team
And they seem to like us back. They are excited for us to join them, and they’ve been very responsive to our feedback and suggestions.
They implemented code syntax highlighting just a few days after we told them we needed it.
Discord’s team has already built a solid suite of apps, and they have shown us how much they care about their users. We’re excited to see how they will continue to improve their product.
## And what’s the catch?
Choosing the best chat service is subjective. There are a million reasons why Discord *might be* a terrible idea. Here are the ones that we’re most worried about:
### Difficult channel management
Channel management seems to be the biggest issue. There is no way to opt out of channels; you can only mute them. And you can only mute channels one by one. There is no way to star channels, and channels can only be sorted on the server level. Each user will see the list of channels in the same order.
As the number of channels grow, it will be challenging to keep things in order. Branching off sub-servers will help, and we will keep an easily accessible directory of channels across our main server and all of the sub-servers.
We can build simple tools to make channel lookup easier, and the Discord team is working on improvements that should make this more manageable.
### No Search
Lack of search is clearly a bummer, but Discord is working on it. Search is coming!
### Firewall
A couple of users aren’t able to access Discord at work since other corporate filters classify it as a gaming application. This sucks, but it seems to be a rare case. So far, it seems only to affect 0.6% of our current community (3/500).
We hope that these users can get Discord's domains whitelisted, and we’ll try to find a solution if this is a widespread issue. The Discord team is aware of the issue as well.
## Is Discord going to disappear tomorrow?
Probably not tomorrow. They have 14 people [full time](https://discordapp.com/company), and they’ve raised money from some of the best investors in Silicon Valley, including [Benchmark](http://www.benchmark.com/) and [Accel](http://www.accel.com/companies/).
By focusing on gaming communities, Discord has differentiated itself from the many other communication apps. Discord is well received and has a rapidly growing user base. They plan to keep their basic offerings free for unlimited users and hope to make money with premium offerings (themes, add-ons, content, and more).
## Join us!
More than 500 of us have already migrated to the new Reactiflux. Join us, we're one click away: [http://join.reactiflux.com](http://join.reactiflux.com/)
*Note: Jordan Hawker’s thorough [research](http://jhawk.co/team-chat-comparison) made our decision a lot easier.*
After a couple weeks of having more people use v0.14, we're ready to ship a patch release addressing a few issues. Thanks to everybody who has reported issues and written patches!
The release is now available for download:
* **React**
Dev build with warnings: <https://fb.me/react-0.14.1.js>
Minified build for production: <https://fb.me/react-0.14.1.min.js>
***React with Add-Ons**
Dev build with warnings: <https://fb.me/react-with-addons-0.14.1.js>
Minified build for production: <https://fb.me/react-with-addons-0.14.1.min.js>
***React DOM** (include React in the page before React DOM)
Dev build with warnings: <https://fb.me/react-dom-0.14.1.js>
Minified build for production: <https://fb.me/react-dom-0.14.1.min.js>
We've also published version `0.14.1` of the `react`, `react-dom`, and addons packages on npm and the `react` package on bower.
- - -
## Changelog
### React DOM
- Fixed bug where events wouldn't fire in old browsers when using React in development mode
- Fixed bug preventing use of `dangerouslySetInnerHTML` with Closure Compiler Advanced mode
- Added support for `srcLang`, `default`, and `kind` attributes for `<track>` elements
- Added support for `color` attribute
- Ensured legacy `.props` access on DOM nodes is updated on re-renders
### React TestUtils Add-on
- Fixed `scryRenderedDOMComponentsWithClass` so it works with SVG
### React CSSTransitionGroup Add-on
- Fix bug preventing `0` to be used as a timeout value
### React on Bower
- Added `react-dom.js` to `main` to improve compatibility with tooling
React ist eine JavaScript-Bibliothek von Facebook und Instagram für Benutzeroberflächen. Man kann sich React als das **V** in **[MVC](https://de.wikipedia.org/wiki/Model_View_Controller)** vorstellen.
Wir haben React für folgende Aufgabe entwickelt: **umfangreiche Anwendungen zu bauen, deren Daten sich zeitlich ändern**.
## Einfach
Beschreibe, wie sich Deine App zu jedem gewünschten Zeitpunkt präsentieren soll und React kümmert sich um alle Benutzeroberflächen-Änderungen sobald sich die zugrundeliegenden Daten ändern.
## Deklarativ
Bei Datenveränderungen drückt React bildlich die "Aktualisieren"-Taste und versteht sich darauf, nur die veränderten Elemente zu erneuern.
## Baue zusammensetzbare Komponenten
React unterstützt die Entwicklung wiederverwendbarer Komponenten. Tatsächlich machst Du in React nichts anderes, als Komponenten zu bauen. Dank ihrer Kapselung erleichtern Komponenten die Wiederverwendung und das Testen von Code sowie die Trennung der Belange.
## Gib' ihnen fünf Minuten
React hinterfragt eine ganze Reihe konventioneller Standpunkte. Auf den ersten Blick mögen einige Ideen verrückt klingen. [Gib' ihnen fünf Minuten](https://signalvnoise.com/posts/3124-give-it-five-minutes) während Du diese Anleitung liest; diese verrückten Ideen halfen dabei, tausende von Komponenten innerhalb und außerhalb von Facebook und Instagram zu entwickeln.
## Erfahre mehr
Erfahre mehr über unsere Motivation zur Entwicklung von React in [diesem Blogeintrag](/react/blog/2013/06/05/why-react.html).
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)**.
Abbiamo costruito React per risolvere un problema: **costruire applicazioni di grandi dimensioni con dati che cambiano nel tempo**.
## Semplice
Dichiara semplicemente come la tua app debba apparire in ogni istante, e React gestirà automaticamente tutti gli aggiornamenti della UI quando i dati sottostanti cambiano.
## Dichiarativo
Quando i dati cambiano, React preme idealmente il bottone "aggiorna", e sa come aggiornare soltanto le parti che sono cambiate.
## Costruisci Componenti Componibili
React è basato interamente sulla costruzione di componenti riutilizzabili. Infatti, con React l'*unica* cosa che fai è costruire componenti. Dal momento che sono così incapsulati, i componenti facilitano il riutilizzo del codice, la verifica e la separazione dei concetti.
## Dagli Cinque Minuti
React sfida molte convenzioni, e a prima vista alcune delle idee potrebbero sembrare folli. [Dagli cinque minuti](https://signalvnoise.com/posts/3124-give-it-five-minutes) mentre leggi questa guida; quelle idee folli hanno funzionato per costruire migliaia di componenti sia dentro che fuori da Facebook e Instagram.
## Per Approfondire
Puoi approfondire le nostre motivazioni per la costruzione di React leggendo [questo articolo del blog](/react/blog/2013/06/05/why-react.html).
L'attività più basilare che puoi effettuare con una UI è mostrare dei dati. React rende visualizzare dati semplice e mantiene automaticamente l'interfaccia aggiornata quando i dati cambiano.
## Per Cominciare
Diamo un'occhiata ad un esempio davvero semplice. Creiamo un file dal nome `hello-react.html` con il codice seguente:
Nel resto della documentazione, ci concentreremo soltanto sul codice JavaScript e assumeremo che sia inserito in un modello come quello qui sopra. Sostituisci il commento segnaposto qui sopra con il seguente codice JSX:
```javascript
varHelloWorld=React.createClass({
render:function(){
return(
<p>
Ciao,<inputtype="text"placeholder="Scrivi il tuo nome"/>!
Èil{this.props.date.toTimeString()}
</p>
);
}
});
setInterval(function(){
ReactDOM.render(
<HelloWorlddate={newDate()}/>,
document.getElementById('example')
);
},500);
```
## Aggiornamenti Reattivi
Apri `hello-react.html` in un browser web e scrivi il tuo nome nel campo di testo. Osserva che React cambia soltanto la stringa di testo dell'ora nella UI — ogni input che inserisci nel campo di testo rimane, anche se non hai scritto alcun codice che gestisce questo comportamento. React lo capisce da solo al tuo posto e fa la cosa giusta.
La maniera in cui siamo in grado di capirlo è che React non manipola il DOM a meno che non sia necessario. **Utilizza un DOM interno fittizio e veloce per effettuare confronti ed effettuare le mutazioni del DOM più efficienti al tuo posto.**
Gli input di questo componente sono chiamati `props` — breve per "properties". Sono passati come attributi nella sintassi JSX. Puoi pensare ad essi come immutabili nel contesto del componente, ovvero, **non assegnare mai `this.props`**.
## I Componenti Sono Come Funzioni
I componenti React sono molto semplici. Puoi immaginarli come semplici funzioni che ricevono in ingresso `props` e `state` (discusso in seguito) e rendono HTML. Fatta questa premessa, i componenti sono molto semplici da descrivere.
> Nota:
>
> **Una limitazione**: i componenti React possono rendere soltanto un singolo nodo radice. Se desideri restituire nodi multipli, essi *devono* essere avvolti in un singolo nodo radice.
## Sintassi JSX
Crediamo fermamente che i componenti sono la maniera corretta di separare i concetti anziché i "modelli" e la "logica di presentazione." Pensiamo che il markup e il codice che lo genera siano intimamente collegati. Inoltre, la logica di presentazione è solitamente molto complessa e usare un linguaggio di modello per esprimerla risulta dispendioso.
Abbiamo scoperto che la migliore soluzione a questo problema è generare HTML e un albero di componenti direttamente dal codice JavaScript in maniera da poter utilizzare tutta la potenza espressiva di un vero linguaggio di programmazione per costruire UI.
Per rendere il compito più facile, abbiamo aggiunto una semplice e **opzionale** sintassi simile all'HTML per creare questi nodi di albero React.
**JSX ti permette di creare oggetti JavaScript usando una sintassi HTML.** Per generare un collegamento in React usando puro JavaScript puoi scrivere:
Abbiamo scoperto che questo ha reso la costruzione di applicazioni React più semplice e i designer tendono a preferire la sintassi, ma ciascuno ha un diverso flusso di lavoro, quindi **JSX nonè richiesto per utilizzare React.**
JSX è di dimensioni contenute. Per maggiori informazioni, consulta [JSX in profondità](/react/docs/jsx-in-depth-it-IT.html). Oppure osserva la trasformazione in tempo reale sulla [REPL di Babel](https://babeljs.io/repl/).
JSX è simile all'HTML, ma non proprio identico. Consulta la guida [JSX gotchas](/react/docs/jsx-gotchas-it-IT.html) per alcune differenze fondamentali.
[Babel offre una varietà di strumenti per cominciare a usare JSX](http://babeljs.io/docs/setup/), dagli strumenti a riga di comando alle integrazioni in Ruby on Rails. Scegli lo strumento che funziona meglio per te.
## React senza JSX
JSX è completamente opzionale; non è necessario utilizzare JSX con React. Puoi creare elementi React in puro JavaScript usando `React.createElement`, che richiede un nome di tag o di componente, un oggetto di proprietà e un numero variabile di argomenti che rappresentano nodi figli opzionali.
```javascript
varchild1=React.createElement('li',null,'Primo Contenuto di Testo');
varchild2=React.createElement('li',null,'Secondo Contenuto di Testo');
The most basic thing you can do with a UI is display some data. React makes it easy to display data and automatically keeps the interface up-to-date when the data changes.
## Getting Started
Let's look at a really simple example. Create a `hello-react.html` file with the following code:
@@ -20,6 +19,7 @@ Let's look at a really simple example. Create a `hello-react.html` file with the
@@ -48,14 +48,13 @@ var HelloWorld = React.createClass({
});
setInterval(function(){
React.render(
ReactDOM.render(
<HelloWorlddate={newDate()}/>,
document.getElementById('example')
);
},500);
```
## Reactive Updates
Open `hello-react.html` in a web browser and type your name into the text field. Notice that React is only changing the time string in the UI — any input you put in the text field remains, even though you haven't written any code to manage this behavior. React figures it out for you and does the right thing.
@@ -64,7 +63,6 @@ The way we are able to figure this out is that React does not manipulate the DOM
The inputs to this component are called `props` — short for "properties". They're passed as attributes in JSX syntax. You should think of these as immutable within the component, that is, **never write to `this.props`**.
## Components are Just Like Functions
React components are very simple. You can think of them as simple functions that take in `props` and `state` (discussed later) and render HTML. With this in mind, components are easy to reason about.
@@ -73,7 +71,6 @@ React components are very simple. You can think of them as simple functions that
>
> **One limitation**: React components can only render a single root node. If you want to return multiple nodes they *must* be wrapped in a single root.
## JSX Syntax
We strongly believe that components are the right way to separate concerns rather than "templates" and "display logic." We think that markup and the code that generates it are intimately tied together. Additionally, display logic is often very complex and using template languages to express it becomes cumbersome.
@@ -98,7 +95,6 @@ JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/
[Babel exposes a number of ways to get started using JSX](http://babeljs.io/docs/setup/), ranging from command line tools to Ruby on Rails integrations. Choose the tool that works best for you.
## React without JSX
JSX is completely optional; you don't have to use JSX with React. You can create React elements in plain JavaScript using `React.createElement`, which takes a tag name or component, a properties object, and variable number of optional child arguments.
@@ -107,7 +103,7 @@ JSX is completely optional; you don't have to use JSX with React. You can create
varchild1=React.createElement('li',null,'First Text Content');
varchild2=React.createElement('li',null,'Second Text Content');
[JSX](https://facebook.github.io/jsx/) è un'estensione della sintassi JavaScript che somiglia all'XML. Puoi usare una semplice trasformazione sintattica di JSX con React.
## Perché JSX?
Non devi per forza utilizzare JSX con React. Puoi anche usare semplice JS. Tuttavia, raccomandiamo di utilizzare JSX perché usa una sintassi concisa e familiare per definire strutture ad albero dotate di attributi.
È più familiare a sviluppatori occasionali come i designer.
L'XML ha i benefici di tag di apertura e chiusura bilanciati. Ciò rende la lettura di grandi strutture ad albero più semplice di chiamate a funzione o oggetti letterali.
Non altera la semantica di JavaScript.
## Tag HTML o Componenti React
React può sia rendere tag HTML (stringhe) che componenti React (classi).
Per rendere untag HTML, usa nomi di tag minuscoli in JSX:
Il JSX di React utilizza la convenzione maiuscolo o minuscolo per distinguere tra classi di componenti locali e tag HTML.
> Nota:
>
> Poiché JSX è JavaScript, gli identificatori come `class` e `for` sono sconsigliati
> come nomi di attributi XML. Invece, i componenti DOM React si aspettano nomi di proprietà
> come `className` e `htmlFor` rispettivamente.
## La Trasformazione
Il JSX di React viene trasformato da una sintassi XML a JavaScript nativo. Gli elementi XML, gli attributi e i figli sono trasformati in argomenti passati a `React.createElement`.
```javascript
varNav;
// Input (JSX):
varapp=<Navcolor="blue"/>;
// Output (JS):
varapp=React.createElement(Nav,{color:"blue"});
```
Osserva che per utilizzare `<Nav />`, la variabile `Nav` deve essere visibile.
JSX permette anche di specificare i figli usando una sintassi XML:
JSX inferirà il [displayName](/react/docs/component-specs-it-IT.html#displayname) della classe dall'assegnazione delle variabile, quando il valore di displayName è indefinito:
```javascript
// Input (JSX):
varNav=React.createClass({});
// Output (JS):
varNav=React.createClass({displayName:"Nav",});
```
Usa la [REPL di Babel](https://babeljs.io/repl/) per provare il JSX e vedere come viene trasformato
in JavaScript nativo, e il
[convertitore da HTML a JSX](/react/html-jsx.html) per convertire il tuo HTML esistente a
JSX.
Se desideri utilizzare JSX, la guida [Primi Passi](/react/docs/getting-started-it-IT.html) ti mostra come impostare la compilazione.
> Nota:
>
> L'espressione JSX viene sempre valutata come un ReactElement. Le implementazioni
> attuali potrebbero differire. Un modo ottimizzato potrebbe porre il
> ReactElement in linea come un oggetto letterale per evitare il codice di validazione in
> `React.createElement`.
## Namespace dei Componenti
Se stai costruendo un componente che ha parecchi figli, come ad esempio un modulo, potresti facilmente trovarti con una quantità di dichiarazioni di variabili:
```javascript
// Imbarazzante blocco di dichiarazioni di variabili
varForm=MyFormComponent;
varFormRow=Form.Row;
varFormLabel=Form.Label;
varFormInput=Form.Input;
varApp=(
<Form>
<FormRow>
<FormLabel/>
<FormInput/>
</FormRow>
</Form>
);
```
Per rendere tutto ciò più semplice e leggibile, *i componenti con un namespace* ti permettono di usare un componente che dispone di altri componenti come proprietà:
```javascript
varForm=MyFormComponent;
varApp=(
<Form>
<Form.Row>
<Form.Label/>
<Form.Input/>
</Form.Row>
</Form>
);
```
Per fare ciò, devi semplicemente creare i tuoi *"sub-componenti"* come proprietà del componente principale:
```javascript
varMyFormComponent=React.createClass({...});
MyFormComponent.Row=React.createClass({...});
MyFormComponent.Label=React.createClass({...});
MyFormComponent.Input=React.createClass({...});
```
JSX gestirà il tutto correttamente al momento di compilare il tuo codice.
```javascript
varApp=(
React.createElement(Form,null,
React.createElement(Form.Row,null,
React.createElement(Form.Label,null),
React.createElement(Form.Input,null)
)
)
);
```
> Nota:
>
> Questa funzionalità è disponibile nella [v0.11](/react/blog/2014/07/17/react-v0.11.html#jsx) e successive.
## Espressioni JavaScript
### Expressioni come Attributi
Per usare un'espressione JavaScript come valore di un attributo, racchiudi l'espressione in un paio
di parentesi graffe (`{}`) anziché doppi apici (`""`).
Omettere il valore di un attributo fa in modo che JSX lo tratti come `true`. Per passare `false` occorre utilizzare un'espressione come attributo. Ciò capita spesso quando si usano elementi di moduli HTML, con attributi come `disabled`, `required`, `checked` e `readOnly`.
```javascript
// Queste due forme sono equivalenti in JSX per disabilitare un bottone
<inputtype="button"disabled/>;
<inputtype="button"disabled={true}/>;
// E queste due forme sono equivalenti in JSX per non disabilitare un bottone
<inputtype="button"/>;
<inputtype="button"disabled={false}/>;
```
### Expressioni per Figli
Similmente, espressioni JavaScript possono essere utilizzate per rappresentare figli:
È facile aggiungere commenti al tuo codice JSX; sono semplici espressioni JS. Devi soltanto prestare attenzione a porre `{}` attorno ai commenti quando ti trovi dentro la sezione figli di un tag.
```javascript
varcontent=(
<Nav>
{/* commento figlio, racchiuso in {} */}
<Person
/* commento
su più
righe */
name={window.isLoggedIn?window.name:''}// fine del commento su una riga
/>
</Nav>
);
```
> NOTA:
>
> JSX è simile all'HTML, ma non esattamente identico. Consulta la guida [JSX gotchas](/react/docs/jsx-gotchas-it-IT.html) per le differenze fondamentali.
Se sai in anticipo che tutte le proprietà che desideri assegnare ad un componente, usare JSX è facile:
```javascript
varcomponent=<Componentfoo={x}bar={y}/>;
```
## Le Props Mutevoli sono il Male
Se non sai quali proprietà desideri impostare, potresti essere tentato di aggiungerle all'oggetto in seguito:
```javascript
varcomponent=<Component/>;
component.props.foo=x;// male
component.props.bar=y;// altrettanto male
```
Questo è un anti-pattern perché significa che non possiamo aiutarti a verificare i propTypes per tempo. Ciò significa che i tuoi errori di propTypes finiscono per avere uno stack trace indecifrabile.
Le props dovrebbero essere considerate immutabili. Mutare l'oggetto props altrove potrebbe causare conseguenze inattese, quindi a questo punto dovrebbe essere idealmente considerato un oggetto congelato.
## Attributi Spread
Adesso puoi utilizzare una nuova caratteristica di JSX chiamata attributi spread:
```javascript
varprops={};
props.foo=x;
props.bar=y;
varcomponent=<Component{...props}/>;
```
Le proprietà dell'oggetto che passi al componente sono copiate nelle sue props.
Puoi usarlo più volte o combinarlo con altri attributi. L'ordine in cui sono specificati è rilevante. Attributi successivi ridefiniscono quelli precedentemente impostati.
L'operatore `...` (o operatore spread) è già supportato per gli [array in ES6](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). Esiste anche una proposta per ES7 per le proprietà [Spread e Rest di Object](https://github.com/sebmarkbage/ecmascript-rest-spread). Stiamo prendendo spunto da questi standard supportati o in corso di sviluppo per fornire una sintassi più pulita a JSX.
JSX somiglia all'HTML ma ci sono delle differenze importanti da tenere in considerazione.
> Nota:
>
> Per le differenze del DOM, come l'attributo `style` in linea, consulta [here](/react/docs/dom-differences-it-IT.html).
## Entità HTML
Puoi inserire entità HTML nel testo letterale in JSX:
```javascript
<div>Primo·Secondo</div>
```
Se desideri visualizzare un'entità HTML all'interno di un contenuto dinamico, avrai problemi con il doppio escape, poiché React effettua in maniera predefinita l'escape di tutte le stringhe visualizzate per prevenire un'ampia gamma di attacchi XSS.
```javascript
// Male: Mostra "Primo · Secondo"
<div>{'Primo · Secondo'}</div>
```
Esistono molte maniere di aggirare questo problema. La più facile è scrivere i caratteri Unicode direttamente in JavaScript. Dovrai assicurarti che il file sia salvato come UTF-8 e che le appropriate direttive UTF-8 siano impostate in modo che il browser li visualizzi correttamente.
```javascript
<div>{'Primo · Secondo'}</div>
```
Un'alternativa più sicura consiste nel trovare il [codice Unicode corrispondente all'entità](http://www.fileformat.info/info/unicode/char/b7/index.htm) e usarlo all'interno di una stringa JavaScript.
Se passi proprietà che non esistono nella specifica HTML ad elementi HTML nativi, React li ignorerà. Se vuoi usare un attributo personalizzato, devi prefiggerlo con `data-`.
```javascript
<divdata-custom-attribute="foo"/>
```
Gli attributi per [l'Accessibilità del Web](http://www.w3.org/WAI/intro/aria) che iniziano per `aria-` saranno gestiti correttamente.
@@ -27,7 +27,7 @@ If you want to display an HTML entity within dynamic content, you will run into
<div>{'First · Second'}</div>
```
There are various ways to work-around this issue. The easiest one is to write unicode characters directly in JavaScript. You need to make sure that the file is saved as UTF-8 and that the proper UTF-8 directives are set so the browser will display it correctly.
There are various ways to work-around this issue. The easiest one is to write Unicode characters directly in JavaScript. You need to make sure that the file is saved as UTF-8 and that the proper UTF-8 directives are set so the browser will display it correctly.
Hai già [imparato a mostrare dati](/react/docs/displaying-data-it-IT.html) con React. Adesso vediamo come rendere le nostre UI interattive.
## Un Esempio Semplice
```javascript
varLikeButton=React.createClass({
getInitialState:function(){
return{liked:false};
},
handleClick:function(event){
this.setState({liked:!this.state.liked});
},
render:function(){
vartext=this.state.liked?'mi piace':'non mi piace';
return(
<ponClick={this.handleClick}>
You{text}this.Clicktotoggle.
</p>
);
}
});
ReactDOM.render(
<LikeButton/>,
document.getElementById('example')
);
```
## Gestione degli Eventi ed Eventi Sintetici
Con React devi semplicemente passare il tuo gestore di eventi come una proprietà camelCased in modo simile a come faresti nel normale HTML. React si assicura che tutti gli eventi si comportano in maniera identica in IE8 e successivi implementando un sistema di eventi sintetici. Ovvero, React sa come propagare e catturare eventi secondo la specifica, e garantisce che gli eventi passati ai tuoi gestori di eventi siano consistenti con la [specifica W3C](http://www.w3.org/TR/DOM-Level-3-Events/), qualunque browser tu stia utilizzando.
## Dietro le Quinte: Binding Automatico e Delega degli Eventi
Dietro le quinte, React esegue alcune operazioni per mantenere il tuo codice ad alte prestazioni e facile da comprendere.
**Binding automatico:** Quando crei le callback in JavaScript, solitamente devi fare il binding esplicito del metodo alla sua istanza, in modo che il valore di `this` sia corretto. Con React, ogni metodo è automaticamente legato alla propria istanza del componente (eccetto quando si usa la sintassi delle classi ES6). React immagazzina il metodo legato in maniera tale da essere estremamente efficiente in termini di CPU e memoria. Ti permette anche di scrivere meno codice!
**Delega degli eventi:** React non associa realmente i gestori di eventi ai nodi stessi. Quando React si avvia, comincia ad ascoltare tutti gli eventi a livello globale usando un singolo event listener. Quando un componente viene montato o smontato, i gestori di eventi sono semplicemente aggiunti o rimossi da un mapping interno. Quando si verifica un evento, React sa come inoltrarlo utilizzando questo mapping. Quando non ci sono più gestori di eventi rimasti nel mapping, i gestori di eventi di React sono semplici operazioni fittizie. Per saperne di più sul perché questo approccio è veloce, leggi [l'eccellente articolo sul blog di David Walsh](http://davidwalsh.name/event-delegate).
## I Componenti Sono Macchine a Stati Finiti
React considera le UI come semplici macchine a stati finiti. Pensando alla UI come in uno di tanti stati diversi e visualizzando questi stati, è facile mantenere la UI consistente.
In React, aggiorni semplicemente lo stato di un componente, e quindi visualizzi una nuova UI basata su questo nuovo stato. React si occupa di aggiornare il DOM al tuo posto nella maniera più efficiente.
## Come Funziona lo Stato
Una maniera comune di informare React di un cambiamento nei dati è chiamare `setState(data, callback)`. Questo metodo effettua il merge di `data` in `this.state` e ridisegna il componente. Quando il componente ha terminato la fase di ri-rendering, la `callback` opzionale viene invocata. Nella maggior parte dei casi non avrai bisogno di fornire una `callback` dal momento che React si occuperà di mantenere la UI aggiornata per te.
## Quali Componenti Devono Avere uno Stato?
La maggior parte dei tuoi componenti dovrebbero semplicemente ricevere dei dati da `props` e visualizzarli. Tuttavia, a volte hai bisogno di reagire all'input dell'utente, una richiesta al server o il trascorrere del tempo. In questi casi utilizzi lo stato.
**Prova a mantenere il maggior numero possibile dei tuoi componenti privi di stato.** Facendo ciò, isolerai lo stato nel suo luogo logicamente corretto e minimizzerai la ridondanza, rendendo più semplice ragionare sulla tua applicazione.
Un pattern comune è quello di creare diversi componenti privi di stato che mostrano semplicemente dati, e di avere un componente dotato di stato al di sopra di essi nella gerarchia, che passa il proprio stato ai suoi figli tramite le `props`. Il componente dotato di stato incapsula tutta la logica di interazione, mentre i componenti privi di stato si occupano della visualizzazione dei dati in maniera dichiarativa.
## Cosa *Dovrebbe* Contenere lo Stato?
**Lo stato dovrebbe contenere dati che i gestori di eventi del componente possono modificare per scatenare un aggiornamento della UI.** In applicazioni reali, questi dati tendono ad essere molto limitati e serializzabili come JSON. Quando costruisci un componente dotato di stato, pensa alla minima rappresentazione possibile del suo stato, e conserva solo quelle proprietà in `this.state`. All'interno di `render()` calcola quindi ogni altra informazione necessaria basandoti sullo stato. Ti accorgerai che pensare e scrivere applicazioni in questo modo porta alla scrittura dell'applicazione più corretta, dal momento che aggiungere valori ridondanti o calcolati allo stato significherebbe doverli mantenere sincronizzati esplicitamente, anziché affidarti a React perché li calcoli al tuo posto.
## Cosa *Non Dovrebbe* Contenere lo Stato?
`this.state` dovrebbe contenere soltanto la quantità minima di dati indispensabile a rappresentare lo stato della tua UI. In quanto tale, non dovrebbe contenere:
* **Dati calcolati:** Non preoccuparti di precalcolare valori basati sullo stato — è più semplice assicurarti che la tua UI sia consistente se effettui tutti i calcoli all'interno di `render()`. Per esempio, se lo stato contiene un array di elementi di una lista, e vuoi mostrare il numero di elementi come stringa, mostra semplicemente `this.state.listItems.length + ' elementi nella lista'` nel tuo metodo `render()` anziché conservarlo nello stato.
* **Componenti React:** Costruiscili in `render()` basandoti sulle proprietà e sullo stato del componente.
* **Dati duplicati dalle proprietà:** Prova ad utilizzare le proprietà come fonte di verità ove possibile. Un uso valido dello stato per i valori delle proprietà è conservarne il valore precedente quando le proprietà cambiano nel tempo.
You've already [learned how to display data](/react/docs/displaying-data.html) with React. Now let's look at how to make our UIs interactive.
## A Simple Example
```javascript
@@ -29,20 +28,16 @@ var LikeButton = React.createClass({
}
});
React.render(
ReactDOM.render(
<LikeButton/>,
document.getElementById('example')
);
```
## Event Handling and Synthetic Events
With React you simply pass your event handler as a camelCased prop similar to how you'd do it in normal HTML. React ensures that all events behave identically in IE8 and above by implementing a synthetic event system. That is, React knows how to bubble and capture events according to the spec, and the events passed to your event handler are guaranteed to be consistent with [the W3C spec](http://www.w3.org/TR/DOM-Level-3-Events/), regardless of which browser you're using.
If you'd like to use React on a touch device such as a phone or tablet, simply call `React.initializeTouchEvents(true);` to enable touch event handling.
## Under the Hood: Autobinding and Event Delegation
Under the hood, React does a few things to keep your code performant and easy to understand.
@@ -51,19 +46,16 @@ Under the hood, React does a few things to keep your code performant and easy to
**Event delegation:** React doesn't actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping. When an event occurs, React knows how to dispatch it using this mapping. When there are no event handlers left in the mapping, React's event handlers are simple no-ops. To learn more about why this is fast, see [David Walsh's excellent blog post](http://davidwalsh.name/event-delegate).
## Components are Just State Machines
React thinks of UIs as simple state machines. By thinking of a UI as being in various states and rendering those states, it's easy to keep your UI consistent.
In React, you simply update a component's state, and then render a new UI based on this new state. React takes care of updating the DOM for you in the most efficient way.
## How State Works
A common way to inform React of a data change is by calling `setState(data, callback)`. This method merges `data` into `this.state` and re-renders the component. When the component finishes re-rendering, the optional `callback` is called. Most of the time you'll never need to provide a `callback` since React will take care of keeping your UI up-to-date for you.
## What Components Should Have State?
Most of your components should simply take some data from `props` and render it. However, sometimes you need to respond to user input, a server request or the passage of time. For this you use state.
@@ -72,15 +64,14 @@ Most of your components should simply take some data from `props` and render it.
A common pattern is to create several stateless components that just render data, and have a stateful component above them in the hierarchy that passes its state to its children via `props`. The stateful component encapsulates all of the interaction logic, while the stateless components take care of rendering data in a declarative way.
## What *Should* Go in State?
**State should contain data that a component's event handlers may change to trigger a UI update.** In real apps this data tends to be very small and JSON-serializable. When building a stateful component, think about the minimal possible representation of its state, and only store those properties in `this.state`. Inside of `render()` simply compute any other information you need based on this state. You'll find that thinking about and writing applications in this way tends to lead to the most correct application, since adding redundant or computed values to state means that you need to explicitly keep them in sync rather than rely on React computing them for you.
## What *Shouldn’t* Go in State?
## What *Shouldn't* Go in State?
`this.state` should only contain the minimal amount of data needed to represent your UI's state. As such, it should not contain:
* **Computed data:** Don't worry about precomputing values based on state — it's easier to ensure that your UI is consistent if you do all computation within `render()`. For example, if you have an array of list items in state and you want to render the count as a string, simply render `this.state.listItems.length + ' list items'` in your `render()` method rather than storing it on state.
* **React components:** Build them in `render()` based on underlying props and state.
* **Duplicated data from props:** Try to use props as the source of truth where possible. One valid use to store props in state is to be able to know its previous values, because props can change over time.
* **Duplicated data from props:** Try to use props as the source of truth where possible. One valid use to store props in state is to be able to know its previous values, because props may change as the result of a parent component re-rendering.
Finora abbiamo visto come scrivere un singolo componente per mostrare dati e gestire l'input dell'itente. Adesso esaminiamo una delle migliori caratteristiche di React: la componibilità.
## Motivazione: Separazione dei Concetti
Costruendo componenti modulari che riutilizzano altri componenti con interfacce ben definite, ottieni gli stessi benefici che otterresti usando funzioni o classi. Nello specifico, puoi *separare i diversi concetti* della tua applicazione nel modo che preferisci semplicemente costruendo nuovi componenti. Costruendo una libreria di componenti personalizzati per la tua applicazione, stai esprimendo la tua UI in una maniera che si adatta meglio al tuo dominio.
## Esepmio di Composizione
Creiamo un semplice componente Avatar che mostra una foto del profilo e un nome utente usando la Graph API di Facebook.
Nell'esempio precedente, le istanze di `Avatar`*posseggono* instanze di `ProfilePic` e `ProfileLink`. In React, **un proprietario è il componente che imposta le `props` di altri componenti**. Più formalmente, se un componente `X` è creato nel metodo `render()` del componente `Y`, si dice che `X` è *di proprietà di*`Y`. Come discusso in precedenza, un componente non può mutare le sue `props` — sono sempre consistenti con il valore che il suo proprietario ha impostato. Questa invariante fondamentale porta a UI la cui consistenza può essere garantita.
È importante distinguere tra la relazione di proprietario-proprietà e la relazione genitore-figlio. La relazione proprietario-proprietà è specifica di React, mentre la relazione genitore-figlio è semplicemente quella che conosci e ami del DOM. Nell'esempio precedente, `Avatar` possiede il `div`, le istanze di `ProfilePic` e `ProfileLink`, e `div` è il **genitore** (ma non il proprietario) delle istanze di `ProfilePic` e `ProfileLink`.
## Figli
Quando crei un'istanza di un componente React, puoi includere componenti React aggiuntivi o espressioni JavaScript tra i tag di apertura e chiusura come segue:
```javascript
<Parent><Child/></Parent>
```
`Parent` può accedere ai propri figli leggendo la speciale proprietà `this.props.children`. **`this.props.children` è una struttura dati opaca:** usa le [utilità React.Children](/react/docs/top-level-api.html#react.children) per manipolare i figli.
### Riconciliazione dei Figli
**La riconciliazione è il processo per il quale React aggiorna il DOM ad ogni passata di rendering.** In generale, i figli sono riconciliati secondo l'ordine in cui sono mostrati. Per esempio, supponiamo che due passate di rendering generino rispettivamente il markup seguente:
```html
// Prima passata di rendering
<Card>
<p>Paragrafo 1</p>
<p>Paragrafo 2</p>
</Card>
// Seconda passata di rendering
<Card>
<p>Paragrafo 2</p>
</Card>
```
Intuitivamente, `<p>Paragrafo 1</p>` è stato rimosso. Invece, React riconcilierà il DOM cambiando il testo contenuto nel primo figlio e distruggerà l'ultimo figlio. React reconcilia secondo l'*ordine* dei figli.
### Figli Dotati di Stato
Per molti componenti, questo non è un grande problema. Tuttavia, per i componenti dotati di stato che mantengono dati in `this.state` attraverso le diverse passate di rendering, questo può essere problematico.
In molti casi, questo problema può essere aggirato nascondendo gli elementi anziché distruggendoli:
```html
// Prima passata di rendering
<Card>
<p>Paragrafo 1</p>
<p>Paragrafo 2</p>
</Card>
// Seconda passata di rendering
<Card>
<pstyle={{'{{'}}display:'none'}}>Paragrafo 1</p>
<p>Paragrafo 2</p>
</Card>
```
### Figli Dinamici
La situazione si complica quando i figli sono rimescolati (come nei risultati della ricerca) o se nuovi componenti sono aggiunti all'inizio della lista (come negli stream). In questi casi quando l'identità e lo stato di ogni figlio deve essere preservato attraverso passate di rendering, puoi unicamente identificare ciascun figlio assegnandogli una proprietà `key`:
```javascript
render:function(){
varresults=this.props.results;
return(
<ol>
{results.map(function(result){
return<likey={result.id}>{result.text}</li>;
})}
</ol>
);
}
```
Quando React riconcilia i figli dotati di `key`, si assicurerà che ciascun figlio con la proprietà `key` sia riordinato (anziché clobbered) o distrutto (anziché riutilizzato).
La proprietà `key` dovrebbe *sempre* essere fornita direttamente all'elemento del componente nell'array, non al contenitore HTML di ciascun componente dell'array:
Puoi anche assegnare chiavi ai figli passandogli un oggetto ReactFragment. Leggi [Frammenti con Chiave](create-fragment.html) per maggiori dettagli.
## Flusso dei Dati
In React, i dati fluiscono dal proprietario al componente posseduto attraverso le `props` come discusso in precedenza. Questo è a tutti gli effetti un binding di dati unidirezionale: i proprietari legano le proprietà dei componenti di loro proprietà a dei valori che il proprietario stesso ha calcolato in base ai propri `props` o `state`. Dal momento che questo processo avviene ricorsivamente, i cambiamenti dei dati vengono riflessi automaticamente ovunque vengano usati.
## Una Nota sulle Prestazioni
Ti starai chiedendo che cambiare i dati sia un'operazione costosa in presenza di un gran numero di nodi sotto un proprietario. La buona notizia è che JavaScript è veloce e i metodi `render()` tendono ad essere molto semplici, quindi in molte applicazioni questo è un processo estremamente veloce. Inoltre, il collo di bottiglia è quasi sempre la mutazione del DOM e non l'esecuzione di JS. React ottimizzerà tutto per te usando il raggruppamento e osservando i cambiamenti.
Tuttavia, a volte vorrai avere un controllo più raffinato sulle tue prestazioni. In tal caso, ridefinisci il metodo `shouldComponentUpdate()` per restituire false quando vuoi che React salti il trattamento di un sottoalbero. Consulta [la documentazione di riferimento di React](/react/docs/component-specs.html) per maggiori informazioni.
> Nota:
>
> Se `shouldComponentUpdate()` restituisce false quando i dati sono effettivamente cambiati, React non è in grado di mantenere la tua UI in sincronia. Assicurati di usare questa tecnica con cognizione di causa, e soltanto in presenza di problemi percettibili di prestazioni. Non sottovalutare l'estrema velocità di esecuzione di JavaScript se paragonata a quella del DOM.
So far, we've looked at how to write a single component to display data and handle user input. Next let's examine one of React's finest features: composability.
## Motivation: Separation of Concerns
By building modular components that reuse other components with well-defined interfaces, you get much of the same benefits that you get by using functions or classes. Specifically you can *separate the different concerns* of your app however you please simply by building new components. By building a custom component library for your application, you are expressing your UI in a way that best fits your domain.
## Composition Example
Let's create a simple Avatar component which shows a profile picture and username using the Facebook Graph API.
@@ -48,20 +46,18 @@ var ProfileLink = React.createClass({
}
});
React.render(
ReactDOM.render(
<Avatarusername="pwh"/>,
document.getElementById('example')
);
```
## Ownership
In the above example, instances of `Avatar`*own* instances of `ProfilePic` and `ProfileLink`. In React, **an owner is the component that sets the `props` of other components**. More formally, if a component `X` is created in component `Y`'s `render()` method, it is said that `X` is *owned by*`Y`. As discussed earlier, a component cannot mutate its `props` — they are always consistent with what its owner sets them to. This fundamental invariant leads to UIs that are guaranteed to be consistent.
It's important to draw a distinction between the owner-ownee relationship and the parent-child relationship. The owner-ownee relationship is specific to React, while the parent-child relationship is simply the one you know and love from the DOM. In the example above, `Avatar` owns the `div`, `ProfilePic` and `ProfileLink` instances, and `div` is the **parent** (but not owner) of the `ProfilePic` and `ProfileLink` instances.
## Children
When you create a React component instance, you can include additional React components or JavaScript expressions between the opening and closing tags like this:
@@ -72,7 +68,6 @@ When you create a React component instance, you can include additional React com
`Parent` can read its children by accessing the special `this.props.children` prop. **`this.props.children` is an opaque data structure:** use the [React.Children utilities](/react/docs/top-level-api.html#react.children) to manipulate them.
### Child Reconciliation
**Reconciliation is the process by which React updates the DOM with each new render pass.** In general, children are reconciled according to the order in which they are rendered. For example, suppose two render passes generate the following respective markup:
@@ -91,7 +86,6 @@ When you create a React component instance, you can include additional React com
Intuitively, `<p>Paragraph 1</p>` was removed. Instead, React will reconcile the DOM by changing the text content of the first child and destroying the last child. React reconciles according to the *order* of the children.
### Stateful Children
For most components, this is not a big deal. However, for stateful components that maintain data in `this.state` across render passes, this can be very problematic.
@@ -111,7 +105,6 @@ In most cases, this can be sidestepped by hiding elements instead of destroying
</Card>
```
### Dynamic Children
The situation gets more complicated when the children are shuffled around (as in search results) or if new components are added onto the front of the list (as in streams). In these cases where the identity and state of each child must be maintained across render passes, you can uniquely identify each child by assigning it a `key`:
@@ -178,7 +171,6 @@ You can also key children by passing a ReactFragment object. See [Keyed Fragment
In React, data flows from owner to owned component through `props` as discussed above. This is effectively one-way data binding: owners bind their owned component's props to some value the owner has computed based on its `props` or `state`. Since this process happens recursively, data changes are automatically reflected everywhere they are used.
## A Note on Performance
You may be thinking that it's expensive to change data if there are a large number of nodes under an owner. The good news is that JavaScript is fast and `render()` methods tend to be quite simple, so in most applications this is extremely fast. Additionally, the bottleneck is almost always the DOM mutation and not JS execution. React will optimize this for you by using batching and change detection.
Quando disegni interfacce, separa gli elementi comuni di design (bottoni, campi dei moduli, componenti di layout, etc.) in componenti riutilizzabili con interfacce ben definite. In questo modo, la prossima volta che dovrai costruire una nuova UI, puoi scrivere molto meno codice. Ciò significa tempi di sviluppo più brevi, meno bachi, e meno byte trasferiti sulla rete.
## Validazione delle Proprietà
Mentre la tua applicazione cresce, è utile assicurarsi che i tuoi componenti vengano usati correttamente. Ciò viene fatto permettendoti di specificare i `propTypes`. `React.PropTypes` esporta una gamma di validatori che possono essere usati per assicurarsi che i dati che ricevi siano validi. Quando ad una proprietà è assegnato un valore non valido, sarà mostrato un avvertimento nella console JavaScript. Nota che per motivi di prestazioni, `propTypes` è utilizzato soltanto nella modalità di sviluppo. Di seguito trovi un esempio che documenta i diversi validatori che vengono forniti:
```javascript
React.createClass({
propTypes:{
// Puoi dichiarare che una proprietà è uno specifico tipo primitivo JS. In
// maniera predefinita, questi sono tutti opzionali.
optionalArray:React.PropTypes.array,
optionalBool:React.PropTypes.bool,
optionalFunc:React.PropTypes.func,
optionalNumber:React.PropTypes.number,
optionalObject:React.PropTypes.object,
optionalString:React.PropTypes.string,
// Tutto ciò che può essere mostrato: numeri, stringhe, elementi, o un array
// (o frammento) contenente questi tipi.
optionalNode:React.PropTypes.node,
// Un elemento React.
optionalElement:React.PropTypes.element,
// Puoi anche dichiarare che una proprietà è un'istanza di una classe. Questo
React ti permette di definire valori predefiniti per le tue `props` in una maniera molto dichiarativa:
```javascript
varComponentWithDefaultProps=React.createClass({
getDefaultProps:function(){
return{
value:'valore predefinito'
};
}
/* ... */
});
```
Il risultato di `getDefaultProps()` sarà conservato e usato per assicurarsi che `this.props.value` avrà sempre un valore se non è stato specificato dal componente proprietario. Ciò ti permette di utilizzare in sicurezza le tue proprietà senza dover scrivere codice fragile e ripetitivo per gestirlo da te.
## Trasferire le Proprietà: Una Scorciatoia
Un tipo comune di componente React è uno che estende un elemento basico HTML in maniera semplice. Spesso vorrai copiare qualsiasi attributo HTML passato al tuo componente all'elemento HTML sottostante per risparmiare del codice. Puoi usare la sintassi _spread_ di JSX per ottenerlo:
```javascript
varCheckLink=React.createClass({
render:function(){
// Questo prende ciascuna proprietà passata a CheckLink e la copia su <a>
Con `React.PropTypes.element` puoi specificare che solo un figlio unico possa essere passato come figli ad un componente.
```javascript
varMyComponent=React.createClass({
propTypes:{
children:React.PropTypes.element.isRequired
},
render:function(){
return(
<div>
{this.props.children}// Questo deve essere esattamente un elemento oppure lancerà un'eccezione.
</div>
);
}
});
```
## Mixin
I componenti sono la maniera migliore di riutilizzare il codice in React, ma a volte componenti molto diversi possono condividere funzionalità comune. Questi sono a volte chiamate [responsabilità trasversali](https://en.wikipedia.org/wiki/Cross-cutting_concern). React fornisce i `mixin` per risolvere questo problema.
Un caso d'uso comune è un componente che desidera aggiornarsi ad intervalli di tempo. È facile usare `setInterval()`, ma è anche importante cancellare la chiamata ripetuta quando non è più necessaria per liberare memoria. React fornisce dei [metodi del ciclo di vita](/react/docs/working-with-the-browser.html#component-lifecycle) che ti permettono di sapere quando un componente sta per essere creato o distrutto. Creiamo un semplice mixin che usa questi metodi per fornire una facile funzione `setInterval()` che sarà automaticamente rimossa quando il tuo componente viene distrutto.
Una caratteristica interessante dei mixin è che, se un componente usa molteplici mixin e diversi mixin definiscono lo stesso metodo del ciclo di vita (cioè diversi mixin desiderano effettuare una pulizia quando il componente viene distrutto), viene garantito che tutti i metodi del ciclo di vita verranno chiamati. I metodi definiti nei mixin vengono eseguiti nell'ordine in cui i mixin sono elencati, seguiti da una chiamata al metodo definito nel componente.
## Classi ES6
Puoi anche definire le tue classi React come pure classi JavaScript. Per esempio, usando la sintassi delle classi ES6:
L'API è simile a `React.createClass` con l'eccezione del metodo `getInitialState`. Anziché fornire un metodo `getInitialState` a parte, imposti la tua proprietà `state` nel costruttore.
Un'altra differenza è che `propTypes` e `defaultProps` sono definite come proprietà del costruttore anziché nel corpo della classe.
I metodi seguono la stessa semantica delle classi ES6 regolari, ciò significa che non effettuano il binding automatico di `this` all'istanza. Dovrai pertanto usare esplicitamente `.bind(this)` oppure [le funzioni freccia](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) `=>`.
### Niente Mixin
Sfortunatamente, ES6 è stato lanciato senza alcun supporto per i mixin. Di conseguenza non vi è alcun supporto per i mixin quando usi React con le classi ES6. Stiamo lavorando per rendere più semplice il supporto dei relativi casi d'uso senza ricorrere ai mixin.
## Funzioni Prive di Stato
Puoi anche definire le tue classi React come semplici funzioni JavaScript. Ad esempio usando la sintassi della funzione priva di stato:
Questa API semplificata dei componenti è intesa per i componenti che sono pure funzioni dele proprietà. Questi componenti non devono trattenere stato interno, non hanno istanze di supporto, e non posseggono metodi di ciclo di vita. Sono pure trasformate funzionali del loro input, con zero codice boilerplate.
> NOTA:
>
> Poiché le funzioni prive di stato non hanno un'istanza di supporto, non puoi assegnare un ref a un componente creato con una funzione priva di stato. Normalmente questo non è un problema, poiché le funzioni prive di stato non forniscono un'API imperativa. Senza un'API imperativa, non puoi comunque fare molto con un'istanza. Tuttavia, se un utente desidera trovare il nodo DOM di un componente creato con una funzione priva di stato, occorre avvolgere il componente in un altro componente dotato di stato (ad es. un componente classe ES6) e assegnare il ref al componente dotato di stato.
In un mondo ideale, la maggior parte dei tuoi componenti sarebbero funzioni prive di stato poiché questi componenti privi di stato seguono un percorso più rapido all'interno del core di React. Questo è un pattern raccomandato, quando possibile.
When designing interfaces, break down the common design elements (buttons, form fields, layout components, etc.) into reusable components with well-defined interfaces. That way, the next time you need to build some UI, you can write much less code. This means faster development time, fewer bugs, and fewer bytes down the wire.
## Prop Validation
As your app grows it's helpful to ensure that your components are used correctly. We do this by allowing you to specify `propTypes`. `React.PropTypes` exports a range of validators that can be used to make sure the data you receive is valid. When an invalid value is provided for a prop, a warning will be shown in the JavaScript console. Note that for performance reasons `propTypes` is only checked in development mode. Here is an example documenting the different validators provided:
@@ -26,7 +25,7 @@ React.createClass({
optionalString:React.PropTypes.string,
// Anything that can be rendered: numbers, strings, elements or an array
// containing these types.
// (or fragment) containing these types.
optionalNode:React.PropTypes.node,
// A React element.
@@ -79,7 +78,6 @@ React.createClass({
});
```
## Default Prop Values
React lets you define default values for your `props` in a very declarative way:
@@ -97,10 +95,9 @@ var ComponentWithDefaultProps = React.createClass({
The result of `getDefaultProps()` will be cached and used to ensure that `this.props.value` will have a value if it was not specified by the parent component. This allows you to safely just use your props without having to write repetitive and fragile code to handle that yourself.
## Transferring Props: A Shortcut
A common type of React component is one that extends a basic HTML element in a simple way. Often you'll want to copy any HTML attributes passed to your component to the underlying HTML element to save typing. You can use the JSX _spread_ syntax to achieve this:
A common type of React component is one that extends a basic HTML element in a simple way. Often you'll want to copy any HTML attributes passed to your component to the underlying HTML element. To save typing, you can use the JSX _spread_ syntax to achieve this:
```javascript
varCheckLink=React.createClass({
@@ -110,7 +107,7 @@ var CheckLink = React.createClass({
The API is similar to `React.createClass` with the exception of `getInitialState`. Instead of providing a separate `getInitialState` method, you set up your own `state` property in the constructor.
@@ -232,3 +229,29 @@ Methods follow the same semantics as regular ES6 classes, meaning that they don'
### No Mixins
Unfortunately ES6 launched without any mixin support. Therefore, there is no support for mixins when you use React with ES6 classes. Instead, we're working on making it easier to support such use cases without resorting to mixins.
## Stateless Functions
You may also define your React classes as a plain JavaScript function. For example using the stateless function syntax:
This simplified component API is intended for components that are pure functions of their props. These components must not retain internal state, do not have backing instances, and do not have the component lifecycle methods. They are pure functional transforms of their input, with zero boilerplate.
> NOTE:
>
> Because stateless functions don't have a backing instance, you can't attach a ref to a stateless function component. Normally this isn't an issue, since stateless functions do not provide an imperative API. Without an imperative API, there isn't much you could do with an instance anyway. However, if a user wants to find the DOM node of a stateless function component, they must wrap the component in a stateful component (eg. ES6 class component) and attach the ref to the stateful wrapper component.
In an ideal world, most of your components would be stateless functions because these stateless components can follow a faster code path within the React core. This is the recommended pattern, when possible.
方法遵循正式的ES6 class的语义,意味着它们不会自动绑定`this`到实例上。你必须显示的使用`.bind(this)` or [箭头函数](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions) `=>`.
Un pattern comune in React è l'uso di un'astrazione per esporre un componente. Il componente esterno espone una semplice proprietà per effettuare un'azione che può richiedere un'implementazione più complessa.
Puoi usare gli [attributi spread di JSX](/react/docs/jsx-spread.html) per unire le vecchie props con valori aggiuntivi:
```javascript
<Component{...this.props}more="values"/>
```
Se non usi JSX, puoi usare qualsiasi helper come l'API `Object.assign` di ES6, o il metodo `_.extend` di Underscore:
Nel resto di questo tutorial vengono illustrate le best practices, usando JSX e sintassi sperimentale di ES7.
## Trasferimento Manuale
Nella maggior parte dei casi dovresti esplicitamente passare le proprietà. Ciò assicura che venga esposto soltanto un sottoinsieme dell'API interna, del cui funzionamento si è certi.
E se aggiungessimo una proprietà `name`? O una proprietà `title`? O `onMouseOver`?
## Trasferire con `...` in JSX
> NOTA:
>
> La sintassi `...` fa parte della proposta Object Rest Spread. Questa proposta è in processo di diventare uno standard. Consulta la sezione [Proprietà Rest e Spread ...](/react/docs/transferring-props.html#rest-and-spread-properties-...) di seguito per maggiori dettagli.
A volte passare manualmente ciascuna proprietà può essere noioso e fragile. In quei casi puoi usare l'[assegnamento destrutturante](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) con le proprietà residue per estrarre un insieme di proprietà sconosciute.
Elenca tutte le proprietà che desideri consumare, seguite da `...other`.
```javascript
var{checked,...other}=this.props;
```
Ciò assicura che vengano passate tutte le proprietà TRANNE quelle che stai consumando tu stesso.
> Nell'esempio precedente, la proprietà `checked` è anche un attributo DOM valido. Se non utilizzassi la destrutturazione in questo modo, potresti inavvertitamente assegnarlo al `div`.
Usa sempre il pattern di destrutturazione quando trasferisci altre proprietà sconosciute in `other`.
// ANTI-PATTERN: `checked` sarebbe passato al componente interno
return(
<div{...this.props}className={fancyClass}/>
);
}
});
```
## Consumare e Trasferire la Stessa Proprietà
Se il tuo componente desidera consumare una proprietà, ma anche passarla ad altri, puoi passarla esplicitamente mediante `checked={checked}`. Questo è preferibile a passare l'intero oggetto `this.props` dal momento che è più facile effettuarne il linting e il refactoring.
> L'ordine è importante. Mettendo il `{...other}` prima delle tue proprietà JSX ti assicuri che il consumatore del tuo componente non possa ridefinirle. Nell'esempio precedente, abbiamo garantito che l'elemento input sarà del tipo `"checkbox"`.
## Proprietà Rest e Spread `...`
Le proprietà Rest ti permettono di estrarre le proprietà residue di un oggetto in un nuovo oggetto. Vengono escluse tutte le altre proprietà elencate nel pattern di destrutturazione.
Questa è un'implementazione sperimentale di una [proposta ES7](https://github.com/sebmarkbage/ecmascript-rest-spread).
```javascript
var{x,y,...z}={x:1,y:2,a:3,b:4};
x;// 1
y;// 2
z;// { a: 3, b: 4 }
```
> Nota:
>
> Questa proposta ha raggiunto lo stadio 2 ed è attivata in modo predefinito in Babel. Vecchie versioni di Babel potrebbero richiedere l'abilitazione esplicita di questa trasformazione con `babel --optional es7.objectRestSpread`
## Trasferire con Underscore
Se non usi JSX, puoi usare una libreria per ottenere il medesimo pattern. Underscore supporta `_.omit` per omettere delle proprietà ed `_.extend` per copiare le proprietà in un nuovo oggetto.
> 아래의 예제에서는 실험적인 ES7 문법이 사용되었기 때문에 `--harmony ` 플래그가 필요합니다. 브라우저에서 JSX 변환기를 사용 중이라면, `<script type="text/jsx;harmony=true">`를 사용해 스크립트를 작성하세요. 자세히 알아보려면 아래의 [잔여 프로퍼티와 스프레드 프로퍼티 ...](/react/docs/transferring-props-ko-KR.html#rest-and-spread-properties-...)를 확인하세요.
때로는 모든 프로퍼티를 일일이 전달 하는것은 지루하고 덧없는 작업입니다. 이 경우 [구조 해체 할당(destructuring assignment)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)을 다른 프로퍼티를 함께 사용해 미상의 프로퍼티를 추출할 수 있습니다.
@@ -74,7 +74,7 @@ var FancyCheckbox = React.createClass({
I componenti dei moduli come `<input>`, `<textarea>` e `<option>` differiscono dagli altri componenti nativi poiché possono essere alterati tramite interazione dell'utente. Questi componenti forniscono interfacce che rendono più semplice gestire i moduli in risposta all'interazione dell'utente.
Per maggiori informazioni sugli eventi dell'elemento `<form>` consulta [Eventi dei Moduli](/react/docs/events.html#form-events).
## Proprietà Interattive
I componenti dei moduli supportano un numero di proprietà che vengono modificate dall'interazione dell'utente:
*`value`, supportato dai elementi `<input>` e `<textarea>`.
*`checked`, supportato dagli elementi `<input>` dal tipo `checkbox` o `radio`.
*`selected`, supportato dagli elementi `<option>`.
In HTML, in valore di `<textarea>` è impostato tramite un nodo di testo figlio. In React, devi invece usare la proprietà `value`.
I componenti dei moduli ti permettono di reagire ai cambiamenti impostando una callback come proprietà `onChange`. La proprietà `onChange` funziona in tutti i browser e viene scatenata in risposta all'interazione dell'utente quando:
* Il `value` di `<input>` o `<textarea>` cambia.
* Lo stato `checked` di `<input>` cambia.
* Lo stato `selected` di `<option>` cambia.
Come tutti gli eventi DOM, la proprietà `onChange` è supportata su tutti i componenti nativi e può essere usata per gestire la propagazione di eventi di cambiamento.
> Nota:
>
> Per `<input>` e `<textarea>`, `onChange` rimpiazza — e dovrebbe generalmente essere utilizzata in sostituzione — il gestore di eventi [`oninput`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput) nativo del DOM.
## Componenti Controllati
Un `<input>` il cui `value` è impostato è un componente *controllato*. In un `<input>` controllato, il valore dell'elemento visualizzato si riflette sempre nella sua proprietà `value`. Ad esempio:
```javascript
render:function(){
return<inputtype="text"value="Ciao!"/>;
}
```
Ciò visualizzerà un input che ha sempre il valore di `value` impostato a `Ciao!`. Ciascuna immissione dell'utente non avrà effetto sull'elemento visualizzato poiché React ha dichiarato il suo `value` pari a `Ciao!`. Se volessi aggiornare il `value` in risposta all'input dell'utente, puoi usare l'evento `onChange`:
In questo esempio, stiamo semplicemente accettando il valore più recente fornito dall'utente e aggiornando la proprietà `value` del componente `<input>`. Questo pattern semplifica l'implementazione di interfacce che rispondono o validano l'interazione dell'utente. Ad esempio:
Così si può accettare l'input dell'utente ma ne tronca il valore ai primi 140 caratteri.
### Potenziali Problemi con Checkbox e Radio Button
Fai attenzione che, allo scopo di normalizzare la gestione del cambiamento degli elementi checkbox e radio button, React usa un evento `click` al posto di un evento `change`. Nella maggior parte dei casi questo funziona nel modo previsto, tranne quando viene usato `preventDefault` in un gestore dell'evento `change`. `preventDefault` impedisce al browser di aggiornare visualmente l'input, anche se `checked` cambia il suo valore. Questo può essere evitato rimuovendo la chiamata a `preventDefault`, oppure effettuando il cambio del valore di `checked` tramite `setTimeout`.
## Componenti Non Controllati
Un `<input>` che non fornisce un `value` (o lo imposta a `null`) è un componente *non controllato*. In un `<input>` non controllato, il valore dell'elemento visualizzato rifletterà l'input dell'utente. Ad esempio:
```javascript
render:function(){
return<inputtype="text"/>;
}
```
Questo visualizzerà un campo di input il cui valore iniziale è vuoto. Ciascun input dell'utente si rifletterà immediatamente nell'elemento visualizzato. Se desideri reagire ai cambiamenti del valore, puoi usare il gestore di eventi `onChange` proprio come con i componenti controllati.
### Valore Predefinito
Se desideri inizializzare il componente con un valore non vuoto, puoi fornire una proprietà `defaultValue`. Ad esempio:
```javascript
render:function(){
return<inputtype="text"defaultValue="Ciao!"/>;
}
```
Questo esempio funzionerà in maniera simile all'esempio precedente sui **Componenti Controllati**.
Similmente, `<input>` supporta `defaultChecked` e `<select>` supporta `defaultValue`.
> Nota:
>
> Le proprietà `defaultValue` e `defaultChecked` sono usate soltanto durante il rendering iniziale. Se devi aggiornare il valore in un rendering successivo, dovrai usare un [componente controllato](#controlled-components).
## Argomenti Avanzati
### Perché Componenti Controllati?
Usare componenti di moduli come `<input>` in React presenta una difficoltà aggiuntiva, assente quando si scrive un modulo tradizionale in HTML. Ad esempio, in HTML:
Questo visualizza un campo di input *inizializzato* con il valore `Senza titolo`. Quando l'utente modifica il campo, la *proprietà*`value` del nodo cambierà. Tuttavia, `node.getAttribute('value')` restituirà ancora il valore usato durante l'inizializzazione, `Senza titolo`.
Diversamente dall'HTML, i componenti React devono rappresentare lo stato della vista in ciascun momento e non soltanto durante l'inizializzazione. Ad esempio, in React:
Dal momento che questo metodo descrive la vista in ogni momento, il valore del campo di testo deve *sempre* essere `Senza titolo`.
### Perché il Valore della Textarea?
In HTML, il valore di `<textarea>` è solitamente impostato usando un nodo di testo figlio:
```html
<!-- antipattern: NON FARLO! -->
<textareaname="description">Questa è la descrizione.</textarea>
```
Per l'HTML, questo approccio permette agli sviluppatori di fornire facilmente valori su più righe. Tuttavia, dal momento che React è JavaScript, non abbiamo limitazioni sulle stringhe e possiamo usare `\n` se desideriamo andare a capo. In un mondo in cui abbiamo `value` e `defaultValue`, il ruolo giocato dal nodo figlio è ambiguo. Per questa ragione, non dovresti utilizzare il nodo figlio quando imposti il valore delle `<textarea>`:
```javascript
<textareaname="description"value="Questa è la descrizione."/>
```
Se tuttavia decidi di *usare* il nodo di testo figlio, questo si comporterà come `defaultValue`.
### Perché il Value di Select?
L'elemento `<option>` selezionato in un elemento HTML `<select>` è normalmente specificato attraverso l'attributo `selected` dell'opzione stessa. In React, allo scopo di rendere i componenti più semplici da manipolare, viene invece adottato il formato seguente:
```javascript
<selectvalue="B">
<optionvalue="A">Arancia</option>
<optionvalue="B">Banana</option>
<optionvalue="C">Ciliegia</option>
</select>
```
Per creare un componente non controllato, viene invece usato `defaultValue`.
> Nota:
>
> Puoi passare un array come valore dell'attributo `value`, se desideri selezionare più opzioni in un tag `select` a scelta multipla: `<select multiple={true} value={['B', 'C']}>`.
@@ -32,7 +32,6 @@ Like all DOM events, the `onChange` prop is supported on all native components a
>
> For `<input>` and `<textarea>`, `onChange` supersedes — and should generally be used instead of — the DOM's built-in [`oninput`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput) event handler.
## Controlled Components
An `<input>` with `value` set is a *controlled* component. In a controlled `<input>`, the value of the rendered element will always reflect the `value` prop. For example:
@@ -68,6 +67,9 @@ In this example, we are simply accepting the newest value provided by the user a
This would accept user input but truncate the value to the first 140 characters.
### Potential Issues With Checkboxes and Radio Buttons
Be aware that, in an attempt to normalize change handling for checkbox and radio inputs, React uses a `click` event in place of a `change` event. For the most part this behaves as expected, except when calling `preventDefault` in a `change` handler. `preventDefault` stops the browser from visually updating the input, even if `checked` gets toggled. This can be worked around either by removing the call to `preventDefault`, or putting the toggle of `checked` in a `setTimeout`.
## Uncontrolled Components
@@ -91,7 +93,7 @@ If you want to initialize the component with a non-empty value, you can supply a
}
```
This example will function much like the **Controlled Components** example above.
This example will function much like the **Uncontrolled Components** example above.
Likewise, `<input>` supports `defaultChecked` and `<select>` supports `defaultValue`.
> The `defaultValue` and `defaultChecked` props are only used during initial render. If you need to update the value in a subsequent render, you will need to use a [controlled component](#controlled-components).
## Advanced Topics
### Why Controlled Components?
Using form components such as `<input>` in React presents a challenge that is absent when writing traditional form HTML. For example, in HTML:
@@ -123,7 +123,6 @@ Unlike HTML, React components must represent the state of the view at any point
Since this method describes the view at any point in time, the value of the text input should *always* be `Untitled`.
### Why Textarea Value?
In HTML, the value of `<textarea>` is usually set using its children:
@@ -141,7 +140,6 @@ For HTML, this easily allows developers to supply multiline values. However, sin
If you *do* decide to use children, they will behave like `defaultValue`.
### Why Select Value?
The selected `<option>` in an HTML `<select>` is normally specified through that option's `selected` attribute. In React, in order to make components easier to manipulate, the following format is adopted instead:
React offre potenti astrazioni che ti liberano in molti casi dal compito di manipolare direttamente il DOM, ma a volte potresti avere bisogno di accedere alle API sottostanti, ad esempio per lavorare con una libreria di terze parti o altro codice preesistente.
## Il DOM Virtuale
React è così veloce perché non interagisce direttamente con il DOM. React gestisce una rappresentazione veloce del DOM in memoria. I metodi `render()` restituiscono una *descrizione* del DOM, e React può confrontare questa descrizione con la rappresentazione in memoria per calcolare la maniera più veloce di aggiornare il browser.
In aggiunta, React implementa un intero sistema di eventi sintetici che fa in modo che tutti gli oggetti evento siano conformi alle specifiche W3C nonostante le incompatibilità dei browser, e ciascun evento si propaga in maniera consistente ed efficiente in ogni browser. Puoi anche utilizzare alcuni eventi HTML5 in IE8!
Nella maggior parte dei casi è sufficiente rimanere nel mondo del "browser fittizio" di React poiché più efficiente e facile da concepire. Tuttavia, a volte potresti aver bisogno di accedere alle API sottostanti, ad esempio per lavorare con una libreria di terze parti come un plugin jQuery. React fornisce convenienti vie di fuga perché tu possa utilizzare direttamente le API DOM sottostanti.
## I Ref e findDOMNode()
Per interagire con il browser, avrai bisogno di un riferimento a un nodo DOM. Puoi assegnare un attributo `ref` a ciascun elemento, ciò ti permette di fare riferimento all'**istanza di supporto** del componente. Questo è utile se devi invocare funzioni imperative sul componente, oppure desideri accedere ai nodi DOM sottostanti. Per saperne di piu sui ref, incluso la maniera di usarli con efficacia, leggi la nostra documentazione [riferimenti a componenti](/react/docs/more-about-refs-it-IT.html).
## Ciclo di Vita del Componente
I componenti hanno tree fasi principali del ciclo di vita:
* **Montaggio:** Un componente sta venendo inserito nel DOM.
* **Aggiornamento:** Viene effettuato nuovamente il rendering del componente per determinare se il DOM vada aggiornato.
* **Smontaggio:** Un componente sta venendo rimosso dal DOM.
React offre metodi del ciclo di vita che puoi specificare per inserirti in questo processo. Offriamo dei metodi il cui nome inizia per **will**, chiamati immediatamente prima che qualcosa accada, o per **did** che sono chiamati immediatamente dopo che qualcosa è accaduto.
### Montaggio
*`getInitialState(): object` è invocato prima che un componente viene montato. Componenti dotati di stato dovrebbero implementare questo metodo e restituire lo stato iniziale.
*`componentWillMount()` è invocato immediatamente prima che si effettui il montaggio.
*`componentDidMount()` è invocato immediatamente dopo che il montaggio è avvenuto. L'inizializzazione che richiede l'esistenza di nodi DOM dovrebbe avvenire in questo metodo.
### Aggiornamento
*`componentWillReceiveProps(object nextProps)` è invocato quando un componente montato riceve nuove proprietà. Questo metodo dovrebbe essere utilizzato per confrontare `this.props` e `nextProps` per effettuare transizioni di stato utilizzando `this.setState()`.
*`shouldComponentUpdate(object nextProps, object nextState): boolean` è invocato quando un componente decide se i cambiamenti debbano risultare in un aggiornamento del DOM. Implementa questo metodo come un'ottimizzazione per confrontare `this.props` con `nextProps` e `this.state` con `nextState`, e restituisci `false` se React debba rimandare l'aggiornamento.
*`componentWillUpdate(object nextProps, object nextState)` è invocato immediatamente prima che l'aggiornamento avvenga. Non puoi chiamare `this.setState()` al suo interno.
*`componentDidUpdate(object prevProps, object prevState)` è invocato immediatamente dopo che l'aggiornamento è avvenuto.
### Smontaggio
*`componentWillUnmount()` è invocato immediatamente prima che un componente venga smontato e distrutto. Puoi effettuare operazioni di pulizia al suo interno.
### Metodi Montati
Componenti compositi _montati_ supportano anche i seguenti metodi:
*`findDOMNode(): DOMElement` può essere invocato su ciascun componente montato per ottenere un riferimento al suo nodo DOM.
*`forceUpdate()` può essere invocato su ciascun componente montato quando siè certi che un aspetto interno del componente è cambiato senza usare `this.setState()`.
## Supporto per i Browser e Polyfill
A Facebook supportiamo vecchi browser, incluso IE8. Abbiamo impiegato per un lungo tempo i polyfill per consentirci di scrivere JS con un occhio al futuro. Ciò significa che non abbiamo una quantità di hack sparsi nel nostro codice e possiamo tuttavia aspettarci che il nostro codice "semplicemente funzioni". Ad esempio, anziché usare `+new Date()`, possiamo scrivere `Date.now()`. Dal momento che la versione open source di React è la stessa che usiamo internamente, vi abbiamo applicato la stessa filosofia di scrivere JS guardando avanti.
In aggiunta a questa filosofia, abbiamo anche deciso, in qualità di autori di una libreria JS, non dovremmo fornire i polyfill assieme alla nostra libreria. Se ciascuna libreria facesse ciò, con buona probabilità invieresti lo stesso polyfill diverse volte, cosa che potrebbe risultare in una rilevante quantità di codice inutilizzato. Se il tuo prodotto deve supportare vecchi browser, con buona probabilità stai già usando qualcosa come [es5-shim](https://github.com/es-shims/es5-shim).
### Polyfill Richiesti per Supportare Vecchi Browser
`es5-shim.js` tratto da [es5-shim di kriskowal](https://github.com/es-shims/es5-shim) fornisce le seguenti API indispensabili a 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`
`es5-sham.js`, anch'esso tratto da [es5-shim di kriskowal](https://github.com/es-shims/es5-shim), provides the following that React needs:
*`Object.create`
*`Object.freeze`
La build non minificata di React richiede le seguenti API tratte da [console-polyfill di paulmillr](https://github.com/paulmillr/console-polyfill).
*`console.*`
Quando si usano elementi HTML5 in IE8 incluso `<section>`, `<article>`, `<nav>`, `<header>` e `<footer>`, è inoltre necessario includere [html5shiv](https://github.com/aFarkas/html5shiv) o uno script equivalente.
### Problemi Cross-browser
Nonostante React sia molto buono ad astrarre le differenze tra browser, alcuni browser sono limitati o presentano comportamenti scorretti per i quali non abbiamo potuto trovare un rimedio.
#### Evento onScroll su IE8
Su IE8 l'evento `onScroll` non viene propagato, e IE8 non possiede una API per definire gestori di eventi nella fase di cattura dell'evento, con il risultato che React non ha alcun modo di reagire a questi eventi.
Al momento i gestori di questo evento vengono ignorati su IE8.
Leggi la issue [onScroll doesn't work in IE8](https://github.com/facebook/react/issues/631) su GitHub per maggiori informazioni.
React provides powerful abstractions that free you from touching the DOM directly in most cases, but sometimes you simply need to access the underlying API, perhaps to work with a third-party library or existing code.
## The Virtual DOM
React is so fast because it never talks to the DOM directly. React maintains a fast in-memory representation of the DOM. `render()` methods return a *description* of the DOM, and React can diff this description with the in-memory representation to compute the fastest way to update the browser.
React is very fast because it never talks to the DOM directly. React maintains a fast in-memory representation of the DOM. `render()` methods actually return a *description* of the DOM, and React can compare this description with the in-memory representation to compute the fastest way to update the browser.
Additionally, React implements a full synthetic event system such that all event objects are guaranteed to conform to the W3C spec despite browser quirks, and everything bubbles consistently and efficiently across browsers. You can even use some HTML5 events in IE8!
Most of the time you should stay within React's "faked browser" world since it's more performant and easier to reason about. However, sometimes you simply need to access the underlying API, perhaps to work with a third-party library like a jQuery plugin. React provides escape hatches for you to use the underlying DOM API directly.
## Refs and findDOMNode()
To interact with the browser, you'll need a reference to a DOM node. React has a `React.findDOMNode(component)` function which you can call to get a reference to the component's DOM node.
> Note:
>
> `findDOMNode()` only works on mounted components (that is, components that have been placed in the DOM). If you try to call this on a component that has not been mounted yet (like calling `findDOMNode()` in `render()` on a component that has yet to be created) an exception will be thrown.
In order to get a reference to a React component, you can either use `this` to get the current React component, or you can use refs to refer to a component you own. They work like this:
```javascript
varMyComponent=React.createClass({
handleClick:function(){
// Explicitly focus the text input using the raw DOM API.
React.findDOMNode(this.refs.myTextInput).focus();
},
render:function(){
// The ref attribute adds a reference to the component to
// this.refs when the component is mounted.
return(
<div>
<inputtype="text"ref="myTextInput"/>
<input
type="button"
value="Focus the text input"
onClick={this.handleClick}
/>
</div>
);
}
});
React.render(
<MyComponent/>,
document.getElementById('example')
);
```
## More About Refs
To learn more about refs, including ways to use them effectively, see our [more about refs](/react/docs/more-about-refs.html) documentation.
To interact with the browser, you'll need a reference to a DOM node. You can attach a `ref` to any element, which allows you to reference the **backing instance** of the component. This is useful if you need to invoke imperative functions on the component, or want to access the underlying DOM nodes. To learn more about refs, including ways to use them effectively, see our [refs to components](/react/docs/more-about-refs.html) documentation.
## Component Lifecycle
@@ -72,14 +30,12 @@ Components have three main parts of their lifecycle:
React provides lifecycle methods that you can specify to hook into this process. We provide **will** methods, which are called right before something happens, and **did** methods which are called right after something happens.
### Mounting
*`getInitialState(): object` is invoked before a component is mounted. Stateful components should implement this and return the initial state data.
*`componentWillMount()` is invoked immediately before mounting occurs.
*`componentDidMount()` is invoked immediately after mounting occurs. Initialization that requires DOM nodes should go here.
### Updating
*`componentWillReceiveProps(object nextProps)` is invoked when a mounted component receives new props. This method should be used to compare `this.props` and `nextProps` to perform state transitions using `this.setState()`.
@@ -87,19 +43,15 @@ React provides lifecycle methods that you can specify to hook into this process.
*`componentWillUpdate(object nextProps, object nextState)` is invoked immediately before updating occurs. You cannot call `this.setState()` here.
*`componentDidUpdate(object prevProps, object prevState)` is invoked immediately after updating occurs.
### Unmounting
*`componentWillUnmount()` is invoked immediately before a component is unmounted and destroyed. Cleanup should go here.
### Mounted Methods
_Mounted_ composite components also support the following methods:
*`findDOMNode(): DOMElement` can be invoked on any mounted component in order to obtain a reference to its rendered DOM node.
*`forceUpdate()` can be invoked on any mounted component when you know that some deeper aspect of the component's state has changed without using `this.setState()`.
_Mounted_ composite components also support the following method:
*`component.forceUpdate()` can be invoked on any mounted component when you know that some deeper aspect of the component's state has changed without using `this.setState()`.
## Browser Support and Polyfills
@@ -107,7 +59,6 @@ At Facebook, we support older browsers, including IE8. We've had polyfills in pl
In addition to that philosophy, we've also taken the stance that we, as authors of a JS library, should not be shipping polyfills as a part of our library. If every library did this, there's a good chance you'd be sending down the same polyfill multiple times, which could be a sizable chunk of dead code. If your product needs to support older browsers, chances are you're already using something like [es5-shim](https://github.com/es-shims/es5-shim).
### Polyfills Needed to Support Older Browsers
`es5-shim.js` from [kriskowal's es5-shim](https://github.com/es-shims/es5-shim) provides the following that React needs:
@@ -134,12 +85,10 @@ The unminified build of React needs the following from [paulmillr's console-poly
When using HTML5 elements in IE8 including `<section>`, `<article>`, `<nav>`, `<header>`, and `<footer>`, it's also necessary to include [html5shiv](https://github.com/aFarkas/html5shiv) or a similar script.
### Cross-browser Issues
Although React is pretty good at abstracting browser differences, some browsers are limited or present quirky behaviors that we couldn't find a workaround for.
#### onScroll event on IE8
On IE8 the `onScroll` event doesn't bubble and IE8 doesn't have an API to define handlers to the capturing phase of an event, meaning there is no way for React to listen to these events.
Dopo aver costruito il tuo componente, potresti trovarti nella situazione di volere invocare dei metodi sulle istanze di componenti restituite da `render()`. Nella maggior parte dei casi, questo non è necessario poiché il flusso di dati reattivo assicura sempre che le proprietà più recenti siano assegnate a ciascun figlio prodotto da `render()`. Tuttavia, esistono dei casi in cui potrebbe essere necessario o desiderabile, quindi React fornisce una via d'uscita conosciuta come `refs`. Queste `refs` (riferimenti) sono particolarmente utili quando vuoi: trovare il markup DOM prodotto da un componente (ad esempio, per posizionarlo in modo assoluto), usare componenti React in una più ampia applicazione non-React, oppure effettuare la transizione del tuo codice a React.
Vediamo come ottenere un ref, e quindi passiamo ad un esempio completo.
## Il ref restituito da ReactDOM.render
Da non confondersi con il metodo `render()` che definisci sul tuo componente (il quale restituisce un elemento DOM virtuale), [ReactDOM.render()](/react/docs/top-level-api-it-IT.html#reactdom.render) restituisce un riferimento all'**istanza di supporto** del tuo componente (o `null` per i [componenti privi di stato](/react/docs/reusable-components.html#stateless-functions)).
Tieni a mente, tuttavia, che JSX non restituisce un'istanza di un componente! È solo un **ReactElement**: una rappresentazione leggera che istruisce React su come il componente montato debba apparire.
```js
varmyComponentElement=<MyComponent/>;// Questo è un semplice ReactElement.
> Questo deve essere usato soltanto al livello più alto. All'interno dei componenti, lascia che i tuoi `props` e `state` gestiscano la comunicazione con i componenti figli, oppure utilizza uno degli altri metodi per ottenere un ref (attributo stringa o callback).
## L'Attributo ref Come Callback
React supporta un attributo speciale che puoi assegnare a qualsiasi componente. L'attributo `ref` può essere una funzione callback, che sarà eseguita immediatamente dopo che il componente viene montato. Il componente referenziato sarà passato come parametro, e la funzione callback può utilizzare il componente immediatamente, oppure conservarne un riferimento per un uso successivo, o entrambe.
È semplice come aggiungere un attributo `ref` a qualsiasi cosa restituita da `render` usando una funzione freccia di ES6:
```js
render:function(){
return(
<TextInput
ref={function(input){
if(input!=null){
input.focus();
}
}}/>
);
},
```
oppure usando una funzione freccia ES6:
```js
render:function(){
return<TextInputref={(c)=>this._input=c}/>;
},
componentDidMount:function(){
this._input.focus();
},
```
Nota che quando il componente referenziato viene smontato e quando il valore di ref cambia, ref sarà chiamata con `null` come argomento. Ciò impedisce i memory leak nel caso in cui l'istanza venga conservata, come nel primo esempio. Nota che quando assegni il valore di ref a un'espressione di funzione in linea come negli esempi precedenti, React vede un oggetto funzione diverso ogni volta e pertanto in occasione di ciascun aggiornamento, ref verrà chiamata con `null` immediatamente prima di essere chiamata con l'istanza del componente.
Puoi accedere al nodo DOM del componente direttamente chiamando `ReactDOM.findDOMNode(argomentoDellaTuaCallback)`.
## L'Attributo ref Come Stringa
React supporta anche l'uso di una stringa (anziché una callback) come proprietà ref su qualsiasi componente, sebbene allo stato attuale questo approccio sia quasi esclusivamente superato.
1. Assegna un attributo `ref` a qualsiasi cosa restituita da `render` come:
```html
<input ref="myInput" />
```
2. Altrove nel codice (tipicamente in un gestore di eventi), accedi all'**istanza di supporto** tramite `this.refs` come segue:
```javascript
this.refs.myInput
```
Puoi accedere direttamente al nodo DOM del componente chiamando `ReactDOM.findDOMNode(this.refs.myInput)`.
## Un Esempio Completo
Per ottenere un riferimento a un componente React, puoi usare `this` per ottenere il componente React attuale, oppure usare un ref per ottenere un riferimento a un componente di tua proprietà. Il funzionamento è il seguente:
```javascript
var MyComponent = React.createClass({
handleClick: function() {
// Assegna il focus esplicitamente al campo di testo usando l'API DOM nativa.
this.myTextInput.focus();
},
render: function() {
// L'attributo ref aggiunge un riferimento al componente a this.refs quando
In questo esempio, otteniamo un riferimento all'**istanza di supporto** del campo di testo e vi invochiamo il metodo `focus()` quando il bottone viene cliccato.
Per componenti compositi, il riferimento si riferisce a un'istanza della classe del componente, quindi puoi invocare ogni metodo definito in tale classe. Se devi accedere al nodo DOM sottostante per il componente, puoi usare [ReactDOM.findDOMNode](/react/docs/top-level-api-it-IT.html#reactdom.finddomnode).
## Riassunto
I riferimenti `ref` sono la maniera corretta di inviare un messaggio a una precisa istanza di un figlio in una maniera che sarebbe impraticabile attraverso le normali proprietà `props` e `state` di React. Tuttavia, esse non dovrebbero essere la tua astrazione principale per far fluire i dati attraverso la tua applicazione. In modo predefinito, usa il flusso dati di React e utilizza i `ref` per casi d'uso che sono intrinsecamente non reattivi.
### Benefici:
- Puoi definire ogni metodo pubblico nelle classi dei tuoi componenti (come un metodo per reimpostare un Typeahead) e chiamare tali metodi pubblici attraverso i riferimenti (come ad esempio `this.refs.myTypeahead.reset()`).
- Effettuare misure sul DOM richiede quasi sempre l'accesso ad un componente "nativo" come `<input />` accedendo il suo nodo DOM sottostante attraverso `ReactDOM.findDOMNode(this.refs.myInput)`. I riferimenti sono uno degli unici metodi praticabili per fare ciò in maniera affidabile.
- I riferimenti sono gestiti automaticamente per te! Se un figlio è distrutto, anche il suo riferimento è distrutto. Pertanto non preoccuparti del consumo di memoria (a meno che tu non faccia qualcosa di folle per conservare un riferimento).
### Precauzioni:
- *Non accedere mai* ai riferimenti dentro il metodo render di un componente - oppure mentre il metodo render di qualsiasi componente è in esecuzione ovunque nella pila di chiamate.
- Se vuoi preservare la resilienza al Crushing del compilatore Google Closure Compiler, assicurati di non accedere mai come proprietà a ciò che è stato specificato come stringa. Ciò significa che devi accedere come `this.refs['myRefString']` se il tuo ref è stato definito come `ref="myRefString"`.
- Se non hai ancora programmato parecchie applicazioni con React, la tua prima inclinazione è solitamente di provare a utilizzare i riferimenti per "fare succedere qualcosa" nella tua applicazione. Se questo è il tuo caso, fermati un momento e pensa in maniera critica al luogo corretto nella gerarchia dei componenti in cui lo `state` debba trovarsi. Spesso ti accorgerai che il luogo corretto per "possedere" lo stato si trova a un livello più alto nella gerarchia. Posizionare lì lo stato spesso elimina ogni necessità di usare i `ref` per "fare accadere qualcosa" – al contrario, il flusso dei dati solitamente otterrà lo scopo desiderato.
- I ref non possono essere assegnati a [funzioni prive di stato](/react/docs/reusable-components-it-IT.html#stateless-functions), poiché il componente non possiede un'istanza di supporto. Puoi tuttavia racchiudere un componente privo di stato in un componente composito standard e assegnare il ref al componente composito.
- 컴포넌트 클래스에 public 메소드(ex. Typeahead의 reset)를 선언할 수 있으며 refs를 통해 그를 호출할 수 있습니다. (ex. `this.refs.myTypeahead.reset()`)
- DOM을 측정하기 위해서는 거의 항상 `<input />` 같은 "기본" 컴포넌트를 다루고 `React.findDOMNode(this.refs.myInput)`를 통해 그 기저의 DOM 노드에 접근해야 합니다. Refs는 이 일을 확실하게 수행하는 몇 안 되는 실용적인 방법의 하나입니다.
- DOM을 측정하기 위해서는 거의 항상 `<input />` 같은 "기본" 컴포넌트를 다루고 `this.refs.myInput`를 통해 그 기저의 DOM 노드에 접근해야 합니다. Refs는 이 일을 확실하게 수행하는 몇 안 되는 실용적인 방법의 하나입니다.
- Refs는 자동으로 관리합니다! 자식이 파괴되면, 그의 ref도 마찬가지로 파괴됩니다. 참조를 유지하기 위해 뭔가 미친 짓을 하지 않는 한, 메모리 걱정은 하지 않아도 됩니다.
After returning the structure of your UI from the render method, you may find yourself wanting to "reach out" and invoke methods on component instances returned from `render()`. Often, doing something like this isn't necessary for making data flow through your application, 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.
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.
Consider the case, when you wish to tell an `<input />` element (that exists within your instances sub-hierarchy) to focus after you update its value to be the empty string, `''`.
Let's look at how to get a ref, and then dive into a complete example.
```javascript
varApp=React.createClass({
getInitialState:function(){
return{userInput:''};
},
handleChange:function(e){
this.setState({userInput:e.target.value});
},
clearAndFocusInput:function(){
this.setState({userInput:''});// Clear the input
// We wish to focus the <input /> now!
},
render:function(){
return(
<div>
<divonClick={this.clearAndFocusInput}>
ClicktoFocusandReset
</div>
<input
value={this.state.userInput}
onChange={this.handleChange}
/>
</div>
);
}
});
## The ref returned from ReactDOM.render
Not to be confused with the `render()` function that you define on your component (and which returns a virtual DOM element), [ReactDOM.render()](/react/docs/top-level-api.html#reactdom.render) will return a reference to your component's **backing instance** (or `null` for [stateless components](/react/docs/reusable-components.html#stateless-functions)).
Keep in mind, however, that the JSX doesn't return a component instance! It's just a **ReactElement**: a lightweight representation that tells React what the mounted component should look like.
Notice how, in this example, we want to "tell" the input something - something that it cannot infer from its props over time. In this case we want to "tell" it that it should now become focused. However, there are some challenges. What is returned from `render()` is not your actual composition of "child" components, but rather it is a *description* of the children at a particular instance in time - a snapshot.
```js
varmyComponentElement=<MyComponent/>;// This is just a ReactElement.
> Remember, what you return from `render()` is not your *actual* rendered children instances. What you return from `render()` is merely a *description* of the children instances in your component's sub-hierarchy at a particular moment in time.
This means that you should never "hold onto" something that you return from `render()` and then expect it to be anything meaningful.
```javascript
// antipattern: This won't work.
render:function(){
varmyInput=<input/>;// I'm going to try to call methods on this
this.rememberThisInput=myInput;// input at some point in the future! YAY!
return(
<div>
<div>...</div>
{myInput}
</div>
);
}
```
In this example, the `<input />` is merely a *description* of an `<input />`. This description is used to create a *real***backing instance** for the `<input />`.
So how do we talk to the *real* backing instance of the input?
## The ref String Attribute
React supports a very special property that you can attach to any component that is output from `render()`. This special property allows you to refer to the corresponding **backing instance** of anything returned from `render()`. It is always guaranteed to be the proper instance, at any point in time.
It's as simple as:
1. Assign a `ref` attribute to anything returned from `render` such as:
```html
<input ref="myInput" />
```
2. In some other code (typically event handler code), access the **backing instance** via `this.refs` as in:
```javascript
this.refs.myInput
```
You can access the component's DOM node directly by calling `React.findDOMNode(this.refs.myInput)`.
> This should only ever be used at the top level. Inside components, let your `props` and `state` handle communication with child components, or use one of the other methods of getting a ref (string attribute or callbacks).
## The ref Callback Attribute
The `ref` attribute can be a callback function instead of a name. This callback will be executed immediately after the component is mounted. The referenced component will be passed in as a parameter, and the callback function may use the component immediately, or save the reference for future use (or both).
React supports a special attribute that you can attach to any component. The `ref` attribute can be a callback function, and this callback will be executed immediately after the component is mounted. The referenced component will be passed in as a parameter, and the callback function may use the component immediately, or save the reference for future use (or both).
It's as simple as adding a `ref` attribute to anything returned from `render` by using an ES6 arrow function:
It's as simple as adding a `ref` attribute to anything returned from `render`:
Note that when the referenced component is unmounted and whenever the ref changes, the old ref will be called with `null` as an argument. This prevents memory leaks in the case that the instance is stored, as in the first example. Note that when writing refs with inline function expressions as in the examples here, React sees a different function object each time so on every update, ref will be called with `null` immediately before it's called with the component instance.
## Completing the Example
```javascript
var App = React.createClass({
getInitialState: function() {
return {userInput: ''};
},
handleChange: function(e) {
this.setState({userInput: e.target.value});
},
clearAndFocusInput: function() {
// Clear the input
this.setState({userInput: ''}, function() {
// This code executes after the component is re-rendered
In this example, our render function returns a description of an `<input />` instance. But the true instance is accessed via `this.refs.theInput`. As long as a child component with `ref="theInput"` is returned from `render`, `this.refs.theInput` will access the proper instance. This even works on higher level (non-DOM) components such as `<Typeahead ref="myTypeahead" />`.
When attaching a ref to a DOM component like `<div />`, you get the DOM node back; when attaching a ref to a composite component like `<TextInput />`, you'll get the React class instance. In the latter case, you can call methods on that component if any are exposed in its class definition.
Note that when the referenced component is unmounted and whenever the ref changes, the old ref will be called with `null` as an argument. This prevents memory leaks in the case that the instance is stored, as in the first example. Also note that when writing refs with inline function expressions as in the examples here, React sees a different function object each time so on every update, ref will be called with `null` immediately before it's called with the component instance.
## The ref String Attribute
React also supports using a string (instead of a callback) as a ref prop on any component, although this approach is mostly legacy at this point.
1. Assign a `ref` attribute to anything returned from `render` such as:
```html
<input ref="myInput" />
```
2. In some other code (typically event handler code), access the **backing instance** via `this.refs` as in:
```javascript
var input = this.refs.myInput;
var inputValue = input.value;
var inputRect = input.getBoundingClientRect();
```
## A Complete Example
In order to get a reference to a React component, you can either use `this` to get the current React component, or you can use a ref to get a reference to a component you own. They work like this:
```javascript
var MyComponent = React.createClass({
handleClick: function() {
// Explicitly focus the text input using the raw DOM API.
this.myTextInput.focus();
},
render: function() {
// The ref attribute adds a reference to the component to
In this example, we get a reference to the text input **backing instance** and we call `focus()` when the button is clicked.
For composite components, the reference will refer to an instance of the component class so you can invoke any methods that are defined on that class. If you need access to the underlying DOM node for that component, you can use [ReactDOM.findDOMNode](/react/docs/top-level-api.html#reactdom.finddomnode) as an "escape hatch" but we don't recommend it since it breaks encapsulation and in almost every case there's a clearer way to structure your code within the React model.
## Summary
@@ -162,12 +125,13 @@ Refs are a great way to send a message to a particular child instance in a way t
### Benefits:
- You can define any public method on your component classes (such as a reset method on a Typeahead) and call those public methods through refs (such as `this.refs.myTypeahead.reset()`).
- Performing DOM measurements almost always requires reaching out to a "native" component such as `<input />` and accessing its underlying DOM node via `React.findDOMNode(this.refs.myInput)`. Refs are one of the only practical ways of doing this reliably.
- You can define any public method on your component classes (such as a reset method on a Typeahead) and call those public methods through refs (such as `this.refs.myTypeahead.reset()`). In most cases, it's clearer to use the built-in React data flow instead of using refs imperatively.
- Performing DOM measurements almost always requires reaching out to a "native" component such as `<input />` and accessing its underlying DOM node using a ref. Refs are one of the only practical ways of doing this reliably.
- Refs are automatically managed for you! If that child is destroyed, its ref is also destroyed for you. No worrying about memory here (unless you do something crazy to retain a reference yourself).
### Cautions:
- *Never* access refs inside of any component's render method - or while any component's render method is even running anywhere in the call stack.
- If you want to preserve Google Closure Compiler Crushing resilience, make sure to never access as a property what was specified as a string. This means you must access using `this.refs['myRefString']` if your ref was defined as `ref="myRefString"`.
- If you want to preserve Google Closure Compiler advanced-mode crushing resilience, make sure to never access as a property what was specified as a string. This means you must access using `this.refs['myRefString']` if your ref was defined as `ref="myRefString"`.
- If you have not programmed several apps with React, your first inclination is usually going to be to try to use refs to "make things happen" in your app. If this is the case, take a moment and think more critically about where `state` should be owned in the component hierarchy. Often, it becomes clear that the proper place to "own" that state is at a higher level in the hierarchy. Placing the state there often eliminates any desire to use `ref`s to "make things happen" – instead, the data flow will usually accomplish your goal.
- Refs may not be attached to a [stateless function](/react/docs/reusable-components.html#stateless-functions), because the component does not have a backing instance. You can always wrap a stateless component in a standard composite component and attach a ref to the composite component.
Ciascun progetto utilizza un sistema differente per la build e il deploy di JavaScript. Abbiamo provato a rendere React il più possibile indipendente dall'ambiente di sviluppo.
## React
### React hosted su un CDN
Offriamo versioni di React su CDN [nella nostra pagina dei download](/react/downloads.html). Questi file precompilati usano il formato dei moduli UMD. Inserirli con un semplice tag `<script>` inietterà una variabile globale `React` nel tuo ambiente. Questo approccio dovrebbe funzionare senza alcuna configurazione in ambienti CommonJS ed AMD.
### Usare il ramo master
Abbiamo istruzioni per compilare dal ramo `master` [nel nostro repositorio GitHub](https://github.com/facebook/react). Costruiamo un albero di moduli CommonJS sotto `build/modules` che puoi inserire in ogni ambiente o strumento di packaging che supporta CommonJS.
## JSX
### Trasformazione di JSX nel browser
Se preferisci usare JSX, Babel fornisce un [trasformatore ES6 e JSX nel browser per lo sviluppo](http://babeljs.io/docs/usage/browser/) chiamato browser.js che può essere incluso da una release npm `babel-core` oppure da [CDNJS](http://cdnjs.com/libraries/babel-core). Includi un tag `<script type="text/babel">` per scatenare il trasformatore JSX.
> Nota:
>
> Il trasformatore JSX nel browserè piuttosto grande e risulta in calcoli aggiuntivi lato client che possono essere evitati. Non utilizzare in produzione — vedi la sezione successiva.
### In Produzione: JSX Precompilato
Se hai [npm](https://www.npmjs.com/), puoi eseguire `npm install -g babel`. Babel include il supporto per React v0.12 e v0.13. I tag sono automaticamente trasformati negli equivalenti `React.createElement(...)`, `displayName` è automaticamente desunto e aggiunto a tutte le classi React.createClass.
Questo strumento tradurrà i file che usano la sintassi JSX a file in semplice JavaScript che possono essere eseguiti direttamente dal browser. Inoltre, osserverà le directory per te e trasformerà automaticamente i file quando vengono modificati; ad esempio: `babel --watch src/ --out-dir lib/`.
In maniera predefinita, vengono trasformati i file JSX con un'estensione `.js`. Esegui `babel --help` per maggiori informazioni su come usare Babel.
La comunità open source ha creato strumenti che integrano JSX con diversi editor e sistemi di build. Consulta [integrazioni JSX ](https://github.com/facebook/react/wiki/Complementary-Tools#jsx-integrations) per una lista completa.
@@ -12,8 +12,7 @@ Every project uses a different system for building and deploying JavaScript. We'
### CDN-hosted React
We provide CDN-hosted versions of React [on our download page](/react/downloads.html). These prebuilt files use the UMD module format. Dropping them in with a simple `<script>` tag will inject a `React` global into your environment. It should also work out-of-the-box in CommonJS and AMD environments.
We provide CDN-hosted versions of React [on our download page](/react/downloads.html). These pre-built files use the UMD module format. Dropping them in with a simple `<script>` tag will inject a `React` global into your environment. It should also work out-of-the-box in CommonJS and AMD environments.
### Using master
@@ -29,7 +28,6 @@ If you like using JSX, Babel provides an [in-browser ES6 and JSX transformer for
>
> The in-browser JSX transformer is fairly large and results in extraneous computation client-side that can be avoided. Do not use it in production — see the next section.
### Productionizing: Precompiled JSX
If you have [npm](https://www.npmjs.com/), you can run `npm install -g babel`. Babel has built-in support for React v0.12 and v0.13. Tags are automatically transformed to their equivalent `React.createElement(...)`, `displayName` is automatically inferred and added to all React.createClass calls.
@@ -48,7 +46,7 @@ var HelloMessage = React.createClass({
The open-source community has built tools that integrate JSX with several editors and build systems. See [JSX integrations](https://github.com/facebook/react/wiki/Complementary-Tools#jsx-integrations) for the full list.
`React.addons` è il luogo in cui parcheggiamo utili strumenti per costruire applicazioni React. **Questi strumenti devono essere considerati sperimentali** ma saranno eventualmente inclusi nel nucleo o una libreria ufficiale di utilities:
- [`TransitionGroup` e `CSSTransitionGroup`](animation-it-IT.html), per gestire animazioni e transizioni che sono solitamente difficili da implementare, come ad esempio prima della rimozione di un componente.
- [`LinkedStateMixin`](two-way-binding-helpers-it-IT.html), per semplificare la coordinazione tra lo stato del componente e l'input dell'utente in un modulo.
- [`cloneWithProps`](clone-with-props-it-IT.html), per eseguire una copia superficiale di componenti React e cambiare le loro proprietà.
- [`createFragment`](create-fragment-it-IT.html), per creare un insieme di figli con chiavi esterne.
- [`update`](update-it-IT.html), una funzione di utilità che semplifica la gestione di dati immutabili in JavaScript.
- [`PureRenderMixin`](pure-render-mixin-it-IT.html), un aiuto per incrementare le prestazioni in certe situazioni.
Gli add-ons elencati di seguito si trovano esclusivamente nella versione di sviluppo (non minificata) di React:
- [`TestUtils`](test-utils-it-IT.html), semplici helper per scrivere dei test case (soltanto nella build non minificata).
- [`Perf`](perf-it-IT.html), per misurare le prestazioni e fornirti suggerimenti per l'ottimizzazione.
Per ottenere gli add-on, usa `react-with-addons.js` (e la sua controparte non minificata) anziché il solito `react.js`.
Quandi si usa il pacchetto react di npm, richiedi semplicemente `require('react/addons')` anziché `require('react')` per ottenere React con tutti gli add-on.
`React.addons` is where we park some useful utilities for building React apps. **These should be considered experimental**but will eventually be rolled into core or a blessed utilities library:
The Reactadd-ons are a collection of useful utility modules for building React apps. **These should be considered experimental**and tend to change more often than the core.
- [`TransitionGroup` and `CSSTransitionGroup`](animation.html), for dealing with animations and transitions that are usually not simple to implement, such as before a component's removal.
- [`LinkedStateMixin`](two-way-binding-helpers.html), to simplify the coordination between user's form input data and the component's state.
@@ -14,13 +14,10 @@ next: animation.html
- [`createFragment`](create-fragment.html), to create a set of externally-keyed children.
- [`update`](update.html), a helper function that makes dealing with immutable data in JavaScript easier.
- [`PureRenderMixin`](pure-render-mixin.html), a performance booster under certain situations.
- (DEPRECATED) [`classSet`](class-name-manipulation.html), for manipulating the DOM `class` string a bit more cleanly.
The add-ons below are in the development (unminified) version of React only:
- [`TestUtils`](test-utils.html), simple helpers for writing test cases (unminified build only).
- [`Perf`](perf.html), for measuring performance and giving you hint where to optimize.
To get the add-ons, use `react-with-addons.js` (and its minified counterpart) rather than the common `react.js`.
When using the react package from npm, simply `require('react/addons')` instead of `require('react')` to get React with all of the add-ons.
To get the add-ons, install them individually from npm (e.g., `npm install react-addons-pure-render-mixin`). We don't support using the addons if you're not using npm.
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.