mirror of
https://github.com/facebook/react.git
synced 2026-11-18 20:15:56 +00:00
Merge branch '15-stable' into 15-dev
This commit is contained in:
commit
ae17ce5b03
294 files changed
+2299
-1298
No files matched your search
+4
-1
@@ -1,8 +1,11 @@
|
||||
---
|
||||
sudo: required
|
||||
dist: trusty
|
||||
language: node_js
|
||||
node_js:
|
||||
- 4
|
||||
sudo: false
|
||||
rvm:
|
||||
- 2.2.3
|
||||
cache:
|
||||
directories:
|
||||
- docs/vendor/bundle
|
||||
|
||||
@@ -1,3 +1,34 @@
|
||||
## 15.3.0 (July 29, 2016)
|
||||
|
||||
### React
|
||||
- Add `React.PureComponent` - a new base class to extend, replacing `react-addons-pure-render-mixin` now that mixins don't work with ES2015 classes. ([@spicyj](https://github.com/spicyj) in [#7195](https://github.com/facebook/react/pull/7195))
|
||||
- Add new warning when modifying `this.props.children`. ([@jimfb](https://github.com/jimfb) in [#7001](https://github.com/facebook/react/pull/7001))
|
||||
- Fixed issue with ref resolution order. ([@gaearon](https://github.com/gaearon) in [#7101](https://github.com/facebook/react/pull/7101))
|
||||
- Warn when mixin is undefined. ([@swaroopsm](https://github.com/swaroopsm) in [#6158](https://github.com/facebook/react/pull/6158))
|
||||
- Downgrade "unexpected batch number" invariant to a warning. ([@spicyj](https://github.com/spicyj) in [#7133](https://github.com/facebook/react/pull/7133))
|
||||
- Validate arguments to `oneOf` and `oneOfType` PropTypes sooner. ([@troydemonbreun](https://github.com/troydemonbreun) in [#6316](https://github.com/facebook/react/pull/6316))
|
||||
- Warn when calling PropTypes directly. ([@Aweary](https://github.com/Aweary) in [#7132](https://github.com/facebook/react/pull/7132), [#7194](https://github.com/facebook/react/pull/7194))
|
||||
- Improve warning when using Maps as children. ([@keyanzhang](https://github.com/keyanzhang) in [#7260](https://github.com/facebook/react/pull/7260))
|
||||
- Add additional type information to the `PropTypes.element` warning. ([@alexzherdev](https://github.com/alexzherdev) in [#7319](https://github.com/facebook/react/pull/7319))
|
||||
- Improve component identification in no-op `setState` warning. ([@keyanzhang](https://github.com/keyanzhang) in [#7326](https://github.com/facebook/react/pull/7326))
|
||||
|
||||
### React DOM
|
||||
- Fix issue with nested server rendering. ([@Aweary](https://github.com/Aweary) in [#7033](https://github.com/facebook/react/pull/7033))
|
||||
- Add `xmlns`, `xmlnsXlink` to supported SVG attributes. ([@salzhrani](https://github.com/salzhrani) in [#6471](https://github.com/facebook/react/pull/6471))
|
||||
- Add `referrerPolicy` to supported HTML attributes. ([@Aweary](https://github.com/Aweary) in [#7274](https://github.com/facebook/react/pull/7274))
|
||||
- Fix issue resulting in `<input type="range">` initial value being rounded. ([@troydemonbreun](https://github.com/troydemonbreun) in [#7251](https://github.com/facebook/react/pull/7251))
|
||||
|
||||
### React Test Renderer
|
||||
- Initial public release of package allowing more focused testing. Install with `npm install react-test-renderer`. ([@spicyj](https://github.com/spicyj) in [#6944](https://github.com/facebook/react/pull/6944), [#7258](https://github.com/facebook/react/pull/7258), [@iamdustan](https://github.com/iamdustan) in [#7362](https://github.com/facebook/react/pull/7362))
|
||||
|
||||
### React Perf Add-on
|
||||
- Fix issue resulting in excessive warnings when encountering an internal measurement error. ([@sassanh](https://github.com/sassanh) in [#7299](https://github.com/facebook/react/pull/7299))
|
||||
|
||||
### React TestUtils Add-on
|
||||
- Implement `type` property on for events created via `TestUtils.Simulate.*`. ([@yaycmyk](https://github.com/yaycmyk) in [#6154](https://github.com/facebook/react/pull/6154))
|
||||
- Fix crash when running TestUtils with the production build of React. ([@gaearon](https://github.com/gaearon) in [#7246](https://github.com/facebook/react/pull/7246))
|
||||
|
||||
|
||||
## 15.2.1 (July 8, 2016)
|
||||
|
||||
### React
|
||||
|
||||
@@ -31,16 +31,16 @@ You'll notice that we used an HTML-like syntax; [we call it JSX](https://faceboo
|
||||
|
||||
## Installation
|
||||
|
||||
The fastest way to get started is to serve JavaScript from the CDN (also available on [cdnjs](https://cdnjs.com/libraries/react) and [jsdelivr](https://www.jsdelivr.com/projects/react)):
|
||||
The fastest way to get started is to serve JavaScript from a CDN. We're using [npmcdn](https://npmcdn.com/) below but React is also available on [cdnjs](https://cdnjs.com/libraries/react) and [jsdelivr](https://www.jsdelivr.com/projects/react):
|
||||
|
||||
```html
|
||||
<!-- The core React library -->
|
||||
<script src="https://fb.me/react-15.2.1.js"></script>
|
||||
<script src="https://npmcdn.com/react@15.3.0/dist/react.js"></script>
|
||||
<!-- The ReactDOM Library -->
|
||||
<script src="https://fb.me/react-dom-15.2.1.js"></script>
|
||||
<script src="https://npmcdn.com/react-dom@15.3.0/dist/react-dom.js"></script>
|
||||
```
|
||||
|
||||
We've also built a [starter kit](https://facebook.github.io/react/downloads/react-15.2.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.
|
||||
We've also built a [starter kit](https://facebook.github.io/react/downloads/react-15.3.0.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
|
||||
|
||||
If you'd like to use [bower](http://bower.io), it's as easy as:
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
layout: single
|
||||
title: Page Not Found
|
||||
permalink: 404.html
|
||||
---
|
||||
|
||||
We couldn't find what you were looking for.
|
||||
|
||||
+13
-3
@@ -3,11 +3,12 @@ source 'https://rubygems.org'
|
||||
gem 'rake'
|
||||
|
||||
# jekyll, which builds it all
|
||||
# 2.0 includes sass processing
|
||||
gem 'jekyll', '~>2.0'
|
||||
# 3.0 includes sass processing
|
||||
gem 'jekyll', '~>3.1'
|
||||
|
||||
# Auto redirect pages
|
||||
# Jekyll extensions
|
||||
gem 'jekyll-redirect-from'
|
||||
gem 'jekyll-paginate'
|
||||
|
||||
# JSON
|
||||
gem 'json'
|
||||
@@ -17,3 +18,12 @@ gem 'rb-fsevent'
|
||||
|
||||
# For markdown header cleanup
|
||||
gem 'sanitize', '~>2.0'
|
||||
|
||||
# Markdown
|
||||
gem 'redcarpet'
|
||||
|
||||
# Syntax highlighting
|
||||
gem 'pygments.rb'
|
||||
|
||||
# Avoid having to poll for changes on Windows
|
||||
gem 'wdm', '>= 0.1.0' if Gem.win_platform?
|
||||
+45
-60
@@ -1,85 +1,70 @@
|
||||
GEM
|
||||
remote: https://rubygems.org/
|
||||
specs:
|
||||
blankslate (2.1.2.4)
|
||||
celluloid (0.15.2)
|
||||
timers (~> 1.1.0)
|
||||
classifier (1.3.4)
|
||||
fast-stemmer (>= 1.0.0)
|
||||
coffee-script (2.3.0)
|
||||
coffee-script-source
|
||||
execjs
|
||||
coffee-script-source (1.7.1)
|
||||
colorator (0.1)
|
||||
execjs (2.2.1)
|
||||
fast-stemmer (1.0.2)
|
||||
ffi (1.9.3)
|
||||
jekyll (2.2.0)
|
||||
classifier (~> 1.3)
|
||||
ffi (1.9.14)
|
||||
ffi (1.9.14-x64-mingw32)
|
||||
jekyll (3.1.6)
|
||||
colorator (~> 0.1)
|
||||
jekyll-coffeescript (~> 1.0)
|
||||
jekyll-gist (~> 1.0)
|
||||
jekyll-paginate (~> 1.0)
|
||||
jekyll-sass-converter (~> 1.0)
|
||||
jekyll-watch (~> 1.0)
|
||||
jekyll-watch (~> 1.1)
|
||||
kramdown (~> 1.3)
|
||||
liquid (~> 2.6.1)
|
||||
liquid (~> 3.0)
|
||||
mercenary (~> 0.3.3)
|
||||
pygments.rb (~> 0.6.0)
|
||||
redcarpet (~> 3.1)
|
||||
rouge (~> 1.7)
|
||||
safe_yaml (~> 1.0)
|
||||
toml (~> 0.1.0)
|
||||
jekyll-coffeescript (1.0.0)
|
||||
coffee-script (~> 2.2)
|
||||
jekyll-gist (1.1.0)
|
||||
jekyll-paginate (1.0.0)
|
||||
jekyll-redirect-from (0.5.0)
|
||||
jekyll (~> 2.0)
|
||||
jekyll-sass-converter (1.2.0)
|
||||
sass (~> 3.2)
|
||||
jekyll-watch (1.1.0)
|
||||
listen (~> 2.7)
|
||||
json (1.8.1)
|
||||
kramdown (1.4.1)
|
||||
liquid (2.6.1)
|
||||
listen (2.7.9)
|
||||
celluloid (>= 0.15.2)
|
||||
rb-fsevent (>= 0.9.3)
|
||||
rb-inotify (>= 0.9)
|
||||
mercenary (0.3.4)
|
||||
mini_portile (0.6.0)
|
||||
nokogiri (1.6.3.1)
|
||||
mini_portile (= 0.6.0)
|
||||
parslet (1.5.0)
|
||||
blankslate (~> 2.0)
|
||||
posix-spawn (0.3.9)
|
||||
pygments.rb (0.6.0)
|
||||
jekyll-paginate (1.1.0)
|
||||
jekyll-redirect-from (0.11.0)
|
||||
jekyll (>= 2.0)
|
||||
jekyll-sass-converter (1.4.0)
|
||||
sass (~> 3.4)
|
||||
jekyll-watch (1.4.0)
|
||||
listen (~> 3.0, < 3.1)
|
||||
json (2.0.1)
|
||||
kramdown (1.11.1)
|
||||
liquid (3.0.6)
|
||||
listen (3.0.8)
|
||||
rb-fsevent (~> 0.9, >= 0.9.4)
|
||||
rb-inotify (~> 0.9, >= 0.9.7)
|
||||
mercenary (0.3.6)
|
||||
mini_portile2 (2.1.0)
|
||||
nokogiri (1.6.8)
|
||||
mini_portile2 (~> 2.1.0)
|
||||
pkg-config (~> 1.1.7)
|
||||
nokogiri (1.6.8-x64-mingw32)
|
||||
mini_portile2 (~> 2.1.0)
|
||||
pkg-config (~> 1.1.7)
|
||||
pkg-config (1.1.7)
|
||||
posix-spawn (0.3.11)
|
||||
pygments.rb (0.6.3)
|
||||
posix-spawn (~> 0.3.6)
|
||||
yajl-ruby (~> 1.1.0)
|
||||
rake (10.3.2)
|
||||
rb-fsevent (0.9.4)
|
||||
rb-inotify (0.9.5)
|
||||
yajl-ruby (~> 1.2.0)
|
||||
rake (11.2.2)
|
||||
rb-fsevent (0.9.7)
|
||||
rb-inotify (0.9.7)
|
||||
ffi (>= 0.5.0)
|
||||
redcarpet (3.1.2)
|
||||
redcarpet (3.3.4)
|
||||
rouge (1.11.1)
|
||||
safe_yaml (1.0.4)
|
||||
sanitize (2.0.6)
|
||||
sanitize (2.1.0)
|
||||
nokogiri (>= 1.4.4)
|
||||
sass (3.3.14)
|
||||
timers (1.1.0)
|
||||
toml (0.1.1)
|
||||
parslet (~> 1.5.0)
|
||||
yajl-ruby (1.1.0)
|
||||
sass (3.4.22)
|
||||
yajl-ruby (1.2.1)
|
||||
|
||||
PLATFORMS
|
||||
ruby
|
||||
x64-mingw32
|
||||
|
||||
DEPENDENCIES
|
||||
jekyll (~> 2.0)
|
||||
jekyll (~> 3.1)
|
||||
jekyll-paginate
|
||||
jekyll-redirect-from
|
||||
json
|
||||
pygments.rb
|
||||
rake
|
||||
rb-fsevent
|
||||
redcarpet
|
||||
sanitize (~> 2.0)
|
||||
|
||||
BUNDLED WITH
|
||||
1.10.1
|
||||
1.11.2
|
||||
+29
-12
@@ -5,21 +5,37 @@ url: https://facebook.github.io
|
||||
baseurl: "/react"
|
||||
permalink: "/blog/:year/:month/:day/:title.html"
|
||||
paginate_path: "/blog/page:num/"
|
||||
relative_permalinks: true
|
||||
paginate: 5
|
||||
timezone: America/Los_Angeles
|
||||
highlighter: pygments
|
||||
defaults:
|
||||
- scope:
|
||||
path: ''
|
||||
type: post
|
||||
type: posts
|
||||
values:
|
||||
layout: post
|
||||
sectionid: blog
|
||||
- scope:
|
||||
path: blog
|
||||
type: pages
|
||||
values:
|
||||
sectionid: blog
|
||||
- scope:
|
||||
path: docs
|
||||
type: page
|
||||
type: pages
|
||||
values:
|
||||
layout: docs
|
||||
sectionid: docs
|
||||
- scope:
|
||||
path: tips
|
||||
type: pages
|
||||
values:
|
||||
sectionid: docs
|
||||
- scope:
|
||||
path: contributing
|
||||
type: pages
|
||||
values:
|
||||
sectionid: docs
|
||||
exclude:
|
||||
- Gemfile
|
||||
- Gemfile.lock
|
||||
@@ -36,13 +52,14 @@ sass:
|
||||
sass_dir: _css
|
||||
gems:
|
||||
- jekyll-redirect-from
|
||||
react_version: 15.2.1
|
||||
- jekyll-paginate
|
||||
react_version: 15.3.0
|
||||
react_hashes:
|
||||
dev: g2900ZIpFKhyIsz+bnx4YDEfAISugYRU58ljeAgI8TZ0A0AkRLGUCN7OmjF16Cj+
|
||||
prod: ICzDcvbNpMy31akJ8WzksHoK9tl1iRIUPRCaBRN+sn/k40TNGjs9IvgPN0SekkDT
|
||||
addons_dev: js+Yc2Nd259A4+UPokRNVOXJdipY9oIrkkDdFJAZzZxgryRJLkWYDrJVgM97aweF
|
||||
addons_prod: DaNE8gIDQr8RWDoa4y9HX/70fzdOBzpV/e+7RJtMN1MnXEiCMpiIFtutJml6mvPC
|
||||
dom_dev: LD1cH7LXOdrrq5dOOiE2N/HdgCyrw3nmUMq6oPFCJKUfWO3i7AozvBKz7G3maMHt
|
||||
dom_prod: 1dLXeik7kFcDPXbz3rX9dibLTGh/D8dpAOL5X2Ml09pH8wpQlpL+JOgOnzAMCO4T
|
||||
dom_server_dev: WJt1y2JljJEQ1OgpupP2ly0GgIwi7Aodp+n+/fv2bakpgWpXMnLklj5rSouRJt59
|
||||
dom_server_prod: Y6UDASOvQhWWBwXy/Ccp4vSAt0YAp+ymuRXBX4hffy+pMlOgjXzryIjbiceIB6GF
|
||||
dev: R8v794QN9hrNjnivoQ3Mf7nMGVwFIHBkUmBanB40ZBIMttZbBEUatXNosjytvPUC
|
||||
prod: asiNTW+3f/iCKtm+05EX+4V4n6R5R1fyAY9M8Md0DLHodFResXMSBlt8ns9iJaPK
|
||||
addons_dev: iR3HmJX+5siYwRvy6ZXWWN/dNP4IuItUsfk0JJmwxaBIYtWHZhK/2N7wrAcxmpS8
|
||||
addons_prod: A/63GcxBS05SAxTWB0+wQKyQl8RVEH3nOuBuxwg/WV6yI5qpfEy4ksn90bqJdFJY
|
||||
dom_dev: PKr8yTHUBD0chzmoJ6ZYtB1nB87GTEWPmuDlDV7iARDrYGki2fmVB0ae3vf3LX0O
|
||||
dom_prod: TBEslZF7tpwiuBgt/ajgWUKvDGuCExkmEoWygscHE/OOajWS24BLAaf2/z7lj/9n
|
||||
dom_server_dev: UxEqwIE5+BLQKOqKHnPfJBOrSDo7HyocIl6sTb6taLayrVmDuhQ5VM4iauS54BbK
|
||||
dom_server_prod: hOLRkO2HGPRi0d73qKZWueHZyDD/6BID0CJax9kNUNaAvMR4atbNIcYfk2BoM8T3
|
||||
@@ -0,0 +1,4 @@
|
||||
- title: Contributing
|
||||
items:
|
||||
- id: design-principles
|
||||
title: Design Principles
|
||||
@@ -35,4 +35,18 @@
|
||||
</ul>
|
||||
</div>
|
||||
{% endfor %}
|
||||
|
||||
<!-- Contributing Nav -->
|
||||
{% for section in site.data.nav_contributing %}
|
||||
<div class="nav-docs-section">
|
||||
<h3>{{ section.title }}</h3>
|
||||
<ul>
|
||||
{% for item in section.items %}
|
||||
<li>
|
||||
<a href="/react/contributing/{{ item.id }}.html"{% if page.id == item.id %} class="active"{% endif %}>{{ item.title }}</a>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
layout: default
|
||||
sectionid: contributing
|
||||
---
|
||||
|
||||
<section class="content wrap documentationContent">
|
||||
{% include nav_docs.html %}
|
||||
|
||||
<div class="inner-content">
|
||||
<h1>{{ page.title }}</h1>
|
||||
<div class="subHeader">{{ page.description }}</div>
|
||||
{{ content }}
|
||||
|
||||
<div class="docs-prevnext">
|
||||
{% if page.prev %}
|
||||
<a class="docs-prev" href="/react/contributing/{{ page.prev }}">← Prev</a>
|
||||
{% endif %}
|
||||
{% if page.next %}
|
||||
<a class="docs-next" href="/react/contributing/{{ page.next }}">Next →</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -50,7 +50,7 @@
|
||||
React
|
||||
</a>
|
||||
<ul class="nav-site nav-site-internal">
|
||||
<li><a href="/react/docs/getting-started.html"{% if page.sectionid == 'docs' or page.sectionid == 'tips' %} class="active"{% endif %}>Docs</a></li>
|
||||
<li><a href="/react/docs/getting-started.html"{% if page.sectionid == 'docs' or page.sectionid == 'tips' or page.sectionid == 'contributing' %} class="active"{% endif %}>Docs</a></li>
|
||||
<li><a href="/react/support.html"{% if page.id == 'support' %} class="active"{% endif %}>Support</a></li>
|
||||
<li><a href="/react/downloads.html"{% if page.id == 'downloads' %} class="active"{% endif %}>Download</a></li>
|
||||
<li><a href="/react/blog/"{% if page.sectionid == 'blog' %} class="active"{% endif %}>Blog</a></li>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
module Authors
|
||||
class Generator < Jekyll::Generator
|
||||
def generate(site)
|
||||
site.posts.each do |post|
|
||||
site.posts.docs.each do |post|
|
||||
authors = []
|
||||
if post['author'].kind_of?(Array)
|
||||
for author in post['author']
|
||||
|
||||
@@ -489,6 +489,8 @@ var RouterMixin = {
|
||||
};
|
||||
|
||||
var Link = React.createClass({
|
||||
mixins: [RouterMixin],
|
||||
|
||||
handleClick: function(e) {
|
||||
e.stopPropagation();
|
||||
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
---
|
||||
title: "Create Apps with No Configuration"
|
||||
author: gaearon
|
||||
---
|
||||
|
||||
**[Create React App](https://github.com/facebookincubator/create-react-app)** is a new officially supported way to create single-page React applications. It offers a modern build setup with no configuration.
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Installation
|
||||
|
||||
First, install the global package:
|
||||
|
||||
```sh
|
||||
npm install -g create-react-app
|
||||
```
|
||||
|
||||
Node.js 4.x or higher is required.
|
||||
|
||||
### Creating an App
|
||||
|
||||
Now you can use it to create a new app:
|
||||
|
||||
```sh
|
||||
create-react-app hello-world
|
||||
```
|
||||
|
||||
This will take a while as npm installs the transitive dependencies, but once it’s done, you will see a list of commands you can run in the created folder:
|
||||
|
||||

|
||||
|
||||
### Starting the Server
|
||||
|
||||
Run `npm start` to launch the development server. The browser will open automatically with the created app’s URL.
|
||||
|
||||

|
||||
|
||||
Create React App uses both Webpack and Babel under the hood.
|
||||
The console output is tuned to be minimal to help you focus on the problems:
|
||||
|
||||

|
||||
|
||||
ESLint is also integrated so lint warnings are displayed right in the console:
|
||||
|
||||

|
||||
|
||||
We only picked a small subset of lint rules that often lead to bugs.
|
||||
|
||||
### Building for Production
|
||||
|
||||
To build an optimized bundle, run `npm run build`:
|
||||
|
||||

|
||||
|
||||
It is minified, correctly envified, and the assets include content hashes for caching.
|
||||
|
||||
### One Dependency
|
||||
|
||||
Your `package.json` contains only a single build dependency and a few scripts:
|
||||
|
||||
```js
|
||||
{
|
||||
"name": "hello-world",
|
||||
"dependencies": {
|
||||
"react": "^15.2.1",
|
||||
"react-dom": "^15.2.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"react-scripts": "0.1.0"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"eject": "react-scripts eject"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
We take care of updating Babel, ESLint, and Webpack to stable compatible versions so you can update a single dependency to get them all.
|
||||
|
||||
### Zero Configuration
|
||||
|
||||
It is worth repeating: there are no configuration files or complicated folder structures. The tool only generates the files you need to build your app.
|
||||
|
||||
```
|
||||
hello-world/
|
||||
README.md
|
||||
index.html
|
||||
favicon.ico
|
||||
node_modules/
|
||||
package.json
|
||||
src/
|
||||
App.css
|
||||
App.js
|
||||
index.css
|
||||
index.js
|
||||
logo.svg
|
||||
```
|
||||
|
||||
All the build settings are preconfigured and can’t be changed. Some features, such as testing, are currently missing. This is an intentional limitation, and we recognize it might not work for everybody. And this brings us to the last point.
|
||||
|
||||
### No Lock-In
|
||||
|
||||
We first saw this feature in [Enclave](https://github.com/eanplatter/enclave), and we loved it. We talked to [Ean](https://twitter.com/EanPlatter), and he was excited to collaborate with us. He already sent a few pull requests!
|
||||
|
||||
“Ejecting” lets you leave the comfort of Create React App setup at any time. You run a single command, and all the build dependencies, configs, and scripts are moved right into your project. At this point you can customize everything you want, but effectively you are forking our configuration and going your own way. If you’re experienced with build tooling and prefer to fine-tune everything to your taste, this lets you use Create React App as a boilerplate generator.
|
||||
|
||||
We expect that at early stages, many people will “eject” for one reason or another, but as we learn from them, we will make the default setup more and more compelling while still providing no configuration.
|
||||
|
||||
## Try It Out!
|
||||
|
||||
You can find [**Create React App**](https://github.com/facebookincubator/create-react-app) with additional instructions on GitHub.
|
||||
|
||||
This is an experiment, and only time will tell if it becomes a popular way of creating and building React apps, or fades into obscurity.
|
||||
|
||||
We welcome you to participate in this experiment. Help us build the React tooling that more people can use. We are always [open to feedback](https://github.com/facebookincubator/create-react-app/issues/11).
|
||||
|
||||
## The Backstory
|
||||
|
||||
React was one of the first libraries to embrace transpiling JavaScript. As a result, even though you can [learn React without any tooling](https://github.com/facebook/react/blob/3fd582643ef3d222a00a0c756292c15b88f9f83c/examples/basic-jsx/index.html), the React ecosystem has commonly become associated with an overwhelming explosion of tools.
|
||||
|
||||
Eric Clemmons called this phenomenon the “[JavaScript Fatigue](https://medium.com/@ericclemmons/javascript-fatigue-48d4011b6fc4)”:
|
||||
|
||||
>Ultimately, the problem is that by choosing React (and inherently JSX), you’ve unwittingly opted into a confusing nest of build tools, boilerplate, linters, & time-sinks to deal with before you ever get to create anything.
|
||||
|
||||
It is tempting to write code in ES2015 and JSX. It is sensible to use a bundler to keep the codebase modular, and a linter to catch the common mistakes. It is nice to have a development server with fast rebuilds, and a command to produce optimized bundles for production.
|
||||
|
||||
Combining these tools requires some experience with each of them. Even so, it is far too easy to get dragged into fighting small incompatibilities, unsatisfied peerDependencies, and illegible configuration files.
|
||||
|
||||
Many of those tools are plugin platforms and don’t directly acknowledge each other’s existence. They leave it up to the users to wire them together. The tools mature and change independently, and tutorials quickly get out of date.
|
||||
|
||||
<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">Marc was almost ready to implement his "hello world" React app <a href="https://t.co/ptdg4yteF1">pic.twitter.com/ptdg4yteF1</a></p>— Thomas Fuchs (@thomasfuchs) <a href="https://twitter.com/thomasfuchs/status/708675139253174273">March 12, 2016</a></blockquote>
|
||||
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
|
||||
|
||||
This doesn’t mean those tools aren’t great. To many of us, they have become indispensable, and we very much appreciate the effort of their maintainers. They already have too much on their plates to worry about the state of the React ecosystem.
|
||||
|
||||
Still, we knew it was frustrating to spend days setting up a project when all you wanted was to learn React. We wanted to fix this.
|
||||
|
||||
## Could We Fix This?
|
||||
|
||||
We found ourselves in an unusual dilemma.
|
||||
|
||||
So far, [our strategy](/react/contributing/design-principles.html#dogfooding) has been to only release the code that we are using at Facebook. This helped us ensure that every project is battle-tested and has clearly defined scope and priorities.
|
||||
|
||||
However, tooling at Facebook is different than at many smaller companies. Linting, transpilation, and packaging are all handled by powerful remote development servers, and product engineers don’t need to configure them. While we wish we could give a dedicated server to every user of React, even Facebook cannot scale that well!
|
||||
|
||||
The React community is very important to us. We knew that we couldn’t fix the problem within the limits of our open source philosophy. This is why we decided to make an exception, and to ship something that we didn’t use ourselves, but that we thought would be useful to the community.
|
||||
|
||||
## The Quest for a React <abbr title="Command Line Interface">CLI</abbr>
|
||||
|
||||
Having just attended [EmberCamp](http://embercamp.com/) a week ago, I was excited about [Ember CLI](https://ember-cli.com/). Ember users have a great “getting started” experience thanks to a curated set of tools united under a single command-line interface. I have heard similar feedback about [Elm Reactor](https://github.com/elm-lang/elm-reactor).
|
||||
|
||||
Providing a cohesive curated experience is valuable by itself, even if the user could in theory assemble those parts themselves. Kathy Sierra [explains it best](http://seriouspony.com/blog/2013/7/24/your-app-makes-me-fat):
|
||||
|
||||
>If your UX asks the user to make *choices*, for example, even if those choices are both clear and useful, the act of *deciding* is a cognitive drain. And not just *while* they’re deciding... even *after* we choose, an unconscious cognitive background thread is slowly consuming/leaking resources, “Was *that* the right choice?”
|
||||
|
||||
I never tried to write a command-line tool for React apps, and neither has [Christopher](https://twitter.com/vjeux). We were chatting on Messenger about this idea, and we decided to work together on it for a week as a hackathon project.
|
||||
|
||||
We knew that such projects traditionally haven’t been very successful in the React ecosystem. Christopher told me that multiple “React CLI” projects have started and failed at Facebook. The community tools with similar goals also exist, but so far they have not yet gained enough traction.
|
||||
|
||||
Still, we decided it was worth another shot. Christopher and I created a very rough proof of concept on the weekend, and [Kevin](https://twitter.com/lacker) soon joined us.
|
||||
|
||||
We invited some of the community members to collaborate with us, and we have spent this week working on this tool. We hope that you’ll enjoy using it! [Let us know what you think.](https://github.com/facebookincubator/create-react-app/issues/11)
|
||||
|
||||
We would like to express our gratitude to [Max Stoiber](https://twitter.com/mxstbr), [Jonny Buchanan](https://twitter.com/jbscript), [Ean Platter](https://twitter.com/eanplatter), [Tyler McGinnis](https://github.com/tylermcginnis), [Kent C. Dodds](https://github.com/kentcdodds), and [Eric Clemmons](https://twitter.com/ericclemmons) for their early feedback, ideas, and contributions.
|
||||
@@ -0,0 +1,81 @@
|
||||
---
|
||||
title: "Relay: State of the State"
|
||||
author: josephsavona
|
||||
---
|
||||
|
||||
This month marks a year since we released Relay and we'd like to share an update on the project and what's next.
|
||||
|
||||
## A Year In Review
|
||||
|
||||
A year after launch, we're incredibly excited to see an active community forming around Relay and that companies such as Twitter are [using Relay in production](https://fabric.io/blog/building-fabric-mission-control-with-graphql-and-relay):
|
||||
|
||||
> For a project like mission control, GraphQL and Relay were a near-perfect solution, and the cost of building it any other way justified the investment.
|
||||
>
|
||||
> -- <cite>Fin Hopkins</cite>
|
||||
|
||||
This kind of positive feedback is really encouraging (I'll admit to re-reading that post far too many times), and great motivation for us to keep going and make Relay even better.
|
||||
|
||||
With the community's help we've already come a long way since the technical preview. Here are some highlights:
|
||||
|
||||
- In March we added support for server-side rendering and for creating multiple instances of Relay on a single page. This was a coordinated effort over the course of several months by community members [Denis Nedelyaev](https://github.com/denvned) and [Gerald Monaco](https://github.com/devknoll) (now at Facebook).
|
||||
- Also in March we added support for React Native. While we use Relay and React Native together internally, they didn't quite work together in open-source out of the box. We owe a big thanks to [Adam Miskiewicz](https://github.com/skevy), [Tom Burns](https://github.com/boourns), [Gaëtan Renaudeau](https://github.com/gre), [David Aurelio](https://github.com/davidaurelio), [Martín Bigio](https://github.com/martinbigio), [Paul O’Shannessy](https://github.com/zpao), [Ben Alpert](https://github.com/spicyj), and many others who helped track down and resolve issues. Finally, thanks to [Steven Luscher](https://github.com/steveluscher) for coordinating this effort and building the first Relay/ReactNative example app.
|
||||
|
||||
We've also seen some great open-source projects spring up around Relay:
|
||||
|
||||
- [Denis Nedelyaev](https://github.com/denvned) created [isomorphic-relay](https://github.com/denvned/isomorphic-relay/), a package that helps developers build server-rendered Relay apps where data is prepared on the server and then used to bootstrap the app on the client.
|
||||
- [Jimmy Jia](https://github.com/taion) created [react-router-relay](https://github.com/relay-tools/react-router-relay) to integrate Relay data-fetching into React Router.
|
||||
- [Pavel Chertorogov](https://github.com/nodkz) released [relay-network-layer](https://github.com/nodkz/react-relay-network-layer), which adds features such as batching query requests, middleware, authentication, logging, and more.
|
||||
|
||||
This is just a small sampling of the community's contributions. So far we've merged over 300 PRs - about 25% of our commits - from over 80 of you. These PRs have improved everything from the website and docs down the very core of the framework. We're humbled by these outstanding contributions and excited to keep working with each of you!
|
||||
|
||||
# Retrospective & Roadmap
|
||||
|
||||
Earlier this year we paused to reflect on the state of the project. What was working well? What could be improved? What features should we add, and what could we remove? A few themes emerged: performance on mobile, developer experience, and empowering the community.
|
||||
|
||||
## Mobile Perf
|
||||
|
||||
First, Relay was built to serve the needs of product developers at Facebook. In 2016, that means helping developers to build apps that work well on [mobile devices connecting on slower networks](https://newsroom.fb.com/news/2015/10/news-feed-fyi-building-for-all-connectivity/). For example, people in developing markets commonly use [2011 year-class phones](https://code.facebook.com/posts/307478339448736/year-class-a-classification-system-for-android/) and connect via [2G class networks](https://code.facebook.com/posts/952628711437136/classes-performance-and-network-segmentation-on-android/). These scenarios present their own challenges.
|
||||
|
||||
Therefore, one of our primary goals this year is to optimize Relay for performance on low-end mobile devices *first*, knowing that this can translate to improved performance on high-end devices as well. In addition to standard approaches such as benchmarking, profiling, and optimizations, we're also working on big-picture changes.
|
||||
|
||||
For example, in today's Relay, here's what happens when an app is opened. First, React Native starts initializing the JavaScript context (loading and parsing your code and then running it). When this finishes, the app executes and Relay sees that you need data. It constructs and prints the query, uploads the query text to the server, processes the response, and renders your app. (Note that this process applies on the web, except that the code has to be *downloaded* instead of loaded from the device.)
|
||||
|
||||
Ideally, though, we could begin fetching data as soon as the native code had loaded - in parallel with the JS context initialization. By the time your JS code was ready to run, the data-fetching would already be under way. To do this we would need a way to determine *statically* - at build time - what query an application would send.
|
||||
|
||||
The key is that GraphQL is already static - we just need to fully embrace this fact. More on this later.
|
||||
|
||||
## Developer Experience
|
||||
|
||||
Next, we've paid attention to the community's feedback and know that, to put it simply, Relay could be "easier" to use (and "simpler" too). This isn't entirely surprising to us - Relay was originally designed as a routing library and gradually morphed into a data-fetching library. Concepts like Relay "routes", for example, no longer serve as critical a role and are just one more concept that developers have to learn about. Another example is mutations: while writes *are* inherently more complex than reads, our API doesn't make the simple things simple enough.
|
||||
|
||||
Alongside our focus on mobile performance, we've also kept the developer experience in mind as we evolve Relay core.
|
||||
|
||||
## Empowering the Community
|
||||
|
||||
Finally, we want to make it easier for people in the community to develop useful libraries that work with Relay. By comparison, React's small surface area - components - allows developers to build cool things like routing, higher-order components, or reusable text editors. For Relay, this would mean having the framework provide core primitives that users can build upon. We want it to be possible for the community to integrate Relay with view libraries other than React, or to build real-time subscriptions as a complementary library.
|
||||
|
||||
# What's Next
|
||||
|
||||
These were big goals, and also a bit scary; we knew that incremental improvements would only allow us to move so fast. So in April we started a project to build a new implementation of Relay core targeting low-end mobile devices from the start.
|
||||
|
||||
As you can guess since we're writing this, the experiment was a success. The result is a new core that retains the best parts of Relay today - colocated components & data-dependencies, automatic data/view consistency, declarative data-fetching - while improving performance on mobile devices and addressing several common areas of confusion.
|
||||
|
||||
We're currently focused on shipping the first applications using the new core: ironing out bugs, refining the API changes and developer experience, and adding any missing features. We're excited to bring these changes to open source, and will do so once we've proven them in production. We'll go into more detail in some upcoming talks - links below - but for now here's an overview:
|
||||
|
||||
- **Static Queries**: By adding a couple of Relay-specific directives, we've been able to retain the expressivity of current Relay queries using static syntax (concretely: you know what query an app will execute just by looking at the source text, without having to run that code). For starters this will allow Relay apps to start fetching data in parallel with JavaScript initialization. But it also unlocks other possibilities: knowing the query ahead of time means that we can generate optimized code for handling query responses, for example, or for reading query data from an offline cache.
|
||||
- **Expressive Mutations**: We'll continue to support a higher-level mutation API for common cases, but will also provide a lower-level API that allows "raw" data access where necessary. If you need to order a list of cached elements, for example, there will be a way to `sort()` it.
|
||||
- **Route-less Relay**: Routes will be gone in open source. Instead of a route with multiple query definitions, you'll just provide a single query with as many root fields as you want.
|
||||
- **Cache Eviction/Garbage Collection**: The API and architecture is designed from the start to allow removing cached data that is no longer referenced by a mounted view.
|
||||
|
||||
Stepping back, we recognize that any API changes will require an investment on your part. To make the transition easier, though, *we will continue to support the current API for the foreseeable future* (we're still using it too). And as much as possible we will open-source the tools that we use to migrate our own code. Ideas that we're exploring include codemods, an interoperability layer for the old/new APIs, and tutorials & guides to ease migration.
|
||||
|
||||
Ultimately, we're making these changes because we believe they make Relay better all around: simpler for developers building apps and faster for the people using them.
|
||||
|
||||
# Conclusion
|
||||
|
||||
If you made it this far, congrats and thanks for reading! We'll be sharing more information about these changes in some upcoming talks:
|
||||
|
||||
- [Greg Hurrell](https://github.com/wincent) will presenting a Relay "Deep Dive" at the [Silicon Valley ReactJS Meetup](http://www.meetup.com/Silicon-Valley-ReactJS-Meetup/events/232236845/) on August 17th.
|
||||
- I ([@josephsavona](https://github.com/josephsavona)) will be speaking about Relay at [React Rally](http://www.reactrally.com) on August 25th.
|
||||
|
||||
We can't wait to share the new code with you and are working as fast as we can to do so!
|
||||
@@ -2,6 +2,7 @@
|
||||
id: acknowledgements
|
||||
title: Acknowledgements
|
||||
layout: single
|
||||
permalink: acknowledgements.html
|
||||
---
|
||||
|
||||
We'd like to thank all of our contributors:
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
---
|
||||
id: design-principles
|
||||
title: Design Principles
|
||||
layout: contributing
|
||||
permalink: contributing/design-principles.html
|
||||
---
|
||||
|
||||
After using React in a couple of applications, you might be interested in contributing to React. Before [diving into specifics](https://github.com/facebook/react/blob/master/CONTRIBUTING.md), we think it's important to establish a few design principles guiding our decisions about changes in React.
|
||||
|
||||
We wrote this document so that you have a better idea of how we decide what React does and what React doesn't do, and what our development philosophy is like. While we are excited to see community contributions, we are not likely to choose a path that violates one or more of these principles.
|
||||
|
||||
>**Note:**
|
||||
>
|
||||
>This document assumes a strong understanding of React. It describes the design principles of *React itself*, not React components or applications.
|
||||
>
|
||||
>For an introduction to React, check out [Thinking in React](/react/docs/thinking-in-react.html) instead.
|
||||
|
||||
### Composition
|
||||
|
||||
The key feature of React is composition of components. Components written by different people should work well together. It is important to us that you can add functionality to a component without causing rippling changes throughout the codebase.
|
||||
|
||||
For example, it should be possible to introduce some local state into a component without changing any of the components using it. Similarly, it should be possible to add some initialization and teardown code to any component when necessary.
|
||||
|
||||
There is nothing "bad" about using state or lifecycle hooks in components. Like any powerful features, they should be used in moderation, but we have no intention to remove them. On the contrary, we think they are integral parts of what makes React useful. We might enable [more functional patterns](https://github.com/reactjs/react-future/tree/master/07%20-%20Returning%20State) in the future, but both local state and lifecycle hooks will be a part of that model.
|
||||
|
||||
Components are often described as "just functions" but in our view they need to be more than that to be useful. In React, components describe any composable behavior, and this includes rendering, lifecycle, and state. Some external libraries like [Relay](http://facebook.github.io/relay/) augment components with other responsibilities such as describing data dependencies. It is possible that those ideas might make it back into React too in some form.
|
||||
|
||||
### Common Abstraction
|
||||
|
||||
In general we [resist adding features](https://www.youtube.com/watch?v=4anAwXYqLG8) that can be implemented in userland. We don't want to bloat your apps with useless library code. However, there are exceptions to this.
|
||||
|
||||
For example, if React didn't provide support for local state or lifecycle hooks, people would create custom abstractions for them. When there are multiple abstractions competing, React can't enforce or take advantage of the properties of either of them. It has to work with the lowest common denominator.
|
||||
|
||||
This is why sometimes we add features to React itself. If we notice that many components implement a certain feature in incompatible or inefficient ways, we might prefer to bake it into React. We don't do it lightly. When we do it, it's because we are confident that raising the abstraction level benefits the whole ecosystem. State, lifecycle hooks, cross-browser event normalization are good examples of this.
|
||||
|
||||
We always discuss such improvement proposals with the community. You can find some of those discussions by the [“big picture”](https://github.com/facebook/react/issues?q=is%3Aopen+is%3Aissue+label%3A%22big+picture%22) label on the React issue tracker.
|
||||
|
||||
### Escape Hatches
|
||||
|
||||
React is pragmatic. It is driven by the needs of the products written at Facebook. While it is influenced by some paradigms that are not yet fully mainstream such as functional programming, staying accessible to a wide range of developers with different skills and experience levels is an explicit goal of the project.
|
||||
|
||||
If we want to deprecate a pattern that we don't like, it is our responsibility to consider all existing use cases for it and [educate the community about the alternatives](/react/blog/2016/07/13/mixins-considered-harmful.html) before we deprecate it. If some pattern that is useful for building apps is hard to express in a declarative way, we will [provide an imperative API](/react/docs/more-about-refs.html) for it. If we can't figure out a perfect API for something that we found necessary in many apps, we will [provide a temporary subpar working API](/react/docs/context.html) as long as it is possible to get rid of it later and it leaves the door open for future improvements.
|
||||
|
||||
### Stability
|
||||
|
||||
We value API stability. At Facebook, we have more than 20 thousand components using React. Many other companies, including [Twitter](https://twitter.com/) and [Airbnb](https://www.airbnb.com/), are also heavy users of React. This is why we are usually reluctant to change public APIs or behavior.
|
||||
|
||||
However we think stability in the sense of "nothing changes" is overrated. It quickly turns into stagnation. Instead, we prefer the stability in the sense of "It is heavily used in production, and when something changes, there is a clear (and preferably automated) migration path."
|
||||
|
||||
When we deprecate a pattern, we study its internal usage at Facebook and add deprecation warnings. They let us assess the impact of the change. Sometimes we back out if we see that it is too early, and we need to think more strategically about getting the codebases to the point where they are ready for this change.
|
||||
|
||||
If we are confident that the change is not too disruptive and the migration strategy is viable for all use cases, we release the deprecation warning to the open source community. We are closely in touch with many users of React outside of Facebook, and we monitor popular open source projects and guide them in fixing those deprecations.
|
||||
|
||||
Given the sheer size of the Facebook React codebase, successful internal migration is often a good indicator that other companies won't have problems either. Nevertheless sometimes people point out additional use cases we haven't thought of, and we add escape hatches for them or rethink our approach.
|
||||
|
||||
We don't deprecate anything without a good reason. We recognize that sometimes deprecations warnings cause frustration but we add them because deprecations clean up the road for the improvements and new features that we and many people in the community consider valuable.
|
||||
|
||||
For example, we added a [warning about unknown DOM props](/react/warnings/unknown-prop.html) in React 15.2.0. Many projects were affected by this. However fixing this warning is important so that we can introduce the support for [custom attributes](https://github.com/facebook/react/issues/140) to React. There is a reason like this behind every deprecation that we add.
|
||||
|
||||
When we add a deprecation warning, we keep it for the rest of the current major version, and [change the behavior in the next major version](/react/blog/2016/02/19/new-versioning-scheme.html). If there is a lot of repetitive manual work involved, we release a [codemod](https://www.youtube.com/watch?v=d0pOgY8__JM) script that automates most of the change. Codemods enable us to move forward without stagnation in a massive codebase, and we encourage you to use them as well.
|
||||
|
||||
You can find the codemods that we released in the [react-codemod](https://github.com/reactjs/react-codemod) repository.
|
||||
|
||||
### Interoperability
|
||||
|
||||
We place high value in interoperability with existing systems and gradual adoption. Facebook has a massive non-React codebase. Its website uses a mix of a server-side component system called XHP, internal UI libraries that came before React, and React itself. It is important to us that any product team can [start using React for a small feature](https://www.youtube.com/watch?v=BF58ZJ1ZQxY) rather than rewrite their code to bet on it.
|
||||
|
||||
This is why React provides escape hatches to work with mutable models, and tries to work well together with other UI libraries. You can wrap an existing imperative UI into a declarative component, and vice versa. This is crucial for gradual adoption.
|
||||
|
||||
### Scheduling
|
||||
|
||||
Even when your components are described as functions, when you use React you don't call them directly. Every component returns a [description of what needs to be rendered](/react/blog/2015/12/18/react-components-elements-and-instances.html#elements-describe-the-tree), and that description may include both user-written components like `<LikeButton>` and platform-specific components like `<div>`. It is up to React to "unroll" `<LikeButton>` at some point in the future and actually apply changes to the UI tree according to the render results of the components recursively.
|
||||
|
||||
This is a subtle distinction but a powerful one. Since you don't call that component function but let React call it, it means React has the power to delay calling it if necessary. In its current implementation React walks the tree recursively and calls render functions of the whole updated tree during a single tick. However in the future it might start [delaying some updates to avoid dropping frames](https://github.com/facebook/react/issues/6170).
|
||||
|
||||
This is a common theme in React design. Some popular libraries implement the "push" approach where computations are performed when the new data is available. React, however, sticks to the "pull" approach where computations can be delayed until necessary.
|
||||
|
||||
React is not a generic data processing library. It is a library for building user interfaces. We think that it is uniquely positioned in an app to know which computations are relevant right now and which are not.
|
||||
|
||||
If something is offscreen, we can delay any logic related to it. If data is arriving faster than the frame rate, we can coalesce and batch updates. We can prioritize work coming from user interactions (such as an animation caused by a button click) over less important background work (such as rendering new content just loaded from the network) to avoid dropping frames.
|
||||
|
||||
To be clear, we are not taking advantage of this right now. However the freedom to do something like this is why we prefer to have control over scheduling, and why `setState()` is asynchronous. Conceptually, we think of it as "scheduling an update".
|
||||
|
||||
The control over scheduling would be harder for us to gain if we let the user directly compose views with a "push" based paradigm common in some variations of [Functional Reactive Programming](https://en.wikipedia.org/wiki/Functional_reactive_programming). We want to own the "glue" code.
|
||||
|
||||
It is a key goal for React that the amount of the user code that executes before yielding back into React is minimal. This ensures that React retains the capability to schedule and split work in chunks according to what it knows about the UI.
|
||||
|
||||
There is an internal joke in the team that React should have been called "Schedule" because React does not want to be fully "reactive".
|
||||
|
||||
### Developer Experience
|
||||
|
||||
Providing a good developer experience is important to us.
|
||||
|
||||
For example, we maintain [React DevTools](https://github.com/facebook/react-devtools) which let you inspect the React component tree in Chrome and Firefox. We have heard that it brings a big productivity boost both to the Facebook engineers and to the community.
|
||||
|
||||
We also try to go an extra mile to provide helpful developer warnings. For example, React warns you in development if you nest tags in a way that the browser doesn't understand, or if you make a common typo in the API. Developer warnings and the related checks are the main reason why the development version of React is slower than the production version.
|
||||
|
||||
The usage patterns that we see internally at Facebook help us understand what the common mistakes are, and how to prevent them early. When we add new features, we try to anticipate the common mistakes and warn about them.
|
||||
|
||||
We are always looking out for ways to improve the developer experience. We love to hear your suggestions and accept your contributions to make it even better.
|
||||
|
||||
### Debugging
|
||||
|
||||
When something goes wrong, it is important that you have breadcrumbs to trace the mistake to its source in the codebase. In React, props and state are those breadcrumbs.
|
||||
|
||||
If you see something wrong on the screen, you can open React DevTools, find the component responsible for rendering, and then see if the props and state are correct. If they are, you know that the problem is in the component’s `render()` function, or some function that is called by `render()`. The problem is isolated.
|
||||
|
||||
If the state is wrong, you know that the problem is caused by one of the `setState()` calls in this file. This, too, is relatively simple to locate and fix because usually there are only a few `setState()` calls in a single file.
|
||||
|
||||
If the props are wrong, you can traverse the tree up in the inspector, looking for the component that first "poisoned the well" by passing bad props down.
|
||||
|
||||
This ability to trace any UI to the data that produced it in the form of current props and state is very important to React. It is an explicit design goal that state is not "trapped" in closures and combinators, and is available to React directly.
|
||||
|
||||
While the UI is dynamic, we believe that synchronous `render()` functions of props and state turn debugging from guesswork into a boring but finite procedure. We would like to preserve this constraint in React even though it makes some use cases, like complex animations, harder.
|
||||
|
||||
### Configuration
|
||||
|
||||
We find global runtime configuration options to be problematic.
|
||||
|
||||
For example, it is occasionally requested that we implement a function like `React.configure(options)` or `React.register(component)`. However this poses multiple problems, and we are not aware of good solutions to them.
|
||||
|
||||
What if somebody calls such a function from a third-party component library? What if one React app embeds another React app, and their desired configurations are incompatible? How can a third-party component specify that it requires a particular configuration? We think that global configuration doesn't work well with composition. Since composition is central to React, we don't provide global configuration in code.
|
||||
|
||||
We do, however, provide some global configuration on the build level. For example, we provide separate development and production builds. We may also [add a profiling build](https://github.com/facebook/react/issues/6627) in the future, and we are open to considering other build flags.
|
||||
|
||||
### Beyond the DOM
|
||||
|
||||
We see the value of React in the way it allows us to write components that have less bugs and compose together well. DOM is the original rendering target for React but [React Native](http://facebook.github.io/react-native/) is just as important both to Facebook and the community.
|
||||
|
||||
Being renderer-agnostic is an important design constraint of React. It adds some overhead in the internal representations. On the other hand, any improvements to the core translate across platforms.
|
||||
|
||||
Having a single programming model lets us form engineering teams around products instead of platforms. So far the tradeoff has been worth it for us.
|
||||
|
||||
### Implementation
|
||||
|
||||
We try to provide elegant APIs where possible. We are much less concerned with the implementation being elegant. The real world is far from perfect, and to a reasonable extent we prefer to put the ugly code into the library if it means the user does not have to write it. When we evaluate new code, we are looking for an implementation that is correct, performant and affords a good developer experience. Elegance is secondary.
|
||||
|
||||
We prefer boring code to clever code. Code is disposable and often changes. So it is important that it [doesn't introduce new internal abstractions unless absolutely necessary](https://youtu.be/4anAwXYqLG8?t=13m9s). Verbose code that is easy to move around, change and remove is preferred to elegant code that is prematurely abstracted and hard to change.
|
||||
|
||||
### Optimized for Tooling
|
||||
|
||||
Some commonly used APIs have verbose names. For example, we use `componentDidMount()` instead of `didMount()` or `onMount()`. This is [intentional](https://github.com/reactjs/react-future/issues/40#issuecomment-142442124). The goal is to make the points of interaction with the library highly visible.
|
||||
|
||||
In a massive codebase like Facebook, being able to search for uses of specific APIs is very important. We value distinct verbose names, and especially for the features that should be used sparingly. For example, `dangerouslySetInnerHTML` is hard to miss in a code review.
|
||||
|
||||
Optimizing for search is also important because of our reliance on [codemods](https://www.youtube.com/watch?v=d0pOgY8__JM) to make breaking changes. We want it to be easy and safe to apply vast automated changes across the codebase, and unique verbose names help us achieve this. Similarly, distinctive names make it easy to write custom [lint rules](https://github.com/yannickcr/eslint-plugin-react) about using React without worrying about potential false positives.
|
||||
|
||||
[JSX](/react/docs/displaying-data.html#jsx-syntax) plays a similar role. While it is not required with React, we use it extensively at Facebook both for aesthetic and pragmatic reasons.
|
||||
|
||||
In our codebase, JSX provides an unambigious hint to the tools that they are dealing with a React element tree. This makes it possible to add build-time optimizations such as [hoisting constant elements](http://babeljs.io/docs/plugins/transform-react-constant-elements/), safely lint and codemod internal component usage, and [include JSX source location](https://github.com/facebook/react/pull/6771) into the warnings.
|
||||
|
||||
### Dogfooding
|
||||
|
||||
We try our best to address the problems raised by the community. However we are likely to prioritize the issues that people are *also* experiencing internally at Facebook. Perhaps counter-intuitively, we think this is the main reason why the community can bet on React.
|
||||
|
||||
Heavy internal usage gives us the confidence that React won't disappear tomorrow. React was created at Facebook to solve its problems. It brings tangible business value to the company and is used in many of its products. [Dogfooding](https://en.wikipedia.org/wiki/Eating_your_own_dog_food) it means that our vision stays sharp and we have a focused direction going forward.
|
||||
|
||||
This doesn't mean that we ignore the issues raised by the community. For example, we added support for [web components](/react/docs/webcomponents.html) and [SVG](https://github.com/facebook/react/pull/6243) to React even though we don't rely on either of them internally. We are actively [listening to your pain points](https://github.com/facebook/react/issues/2686) and [address them](/react/blog/2016/07/11/introducing-reacts-error-code-system.html) to the best of our ability. The community is what makes React special to us, and we are honored to contribute back.
|
||||
|
||||
After releasing many open source projects at Facebook, we have learned that trying to make everyone happy at the same time produced projects with poor focus that didn't grow well. Instead, we found that picking a small audience and focusing on making them happy brings a positive net effect. That's exactly what we did with React, and so far solving the problems encountered by Facebook product teams has translated well to the open source community.
|
||||
|
||||
The downside of this approach is that sometimes we fail to give enough focus to the things that Facebook teams don't have to deal with, such as the "getting started" experience. We are acutely aware of this, and we are thinking of how to improve in a way that would benefit everyone in the community without making the same mistakes we did with open source projects before.
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: why-react-de-DE
|
||||
title: Warum React?
|
||||
permalink: why-react-de-DE.html
|
||||
permalink: docs/why-react-de-DE.html
|
||||
---
|
||||
React ist eine JavaScript-Bibliothek von Facebook und Instagram für Benutzeroberflächen. Man kann sich React als das **V** in **[MVC](https://de.wikipedia.org/wiki/Model_View_Controller)** vorstellen.
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: why-react-it-IT
|
||||
title: Perché React?
|
||||
permalink: why-react-it-IT.html
|
||||
permalink: docs/why-react-it-IT.html
|
||||
next: displaying-data-it-IT.html
|
||||
---
|
||||
React è una libreria JavaScript per creare interfacce utente scritta da Facebook e Instagram. A molti piace pensare a React come alla **V** di **[MVC](https://it.wikipedia.org/wiki/Model-View-Controller)**.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: why-react-ja-JP
|
||||
title: なぜReactを使うのでしょうか?
|
||||
permalink: why-react-ja-JP.html
|
||||
permalink: docs/why-react-ja-JP.html
|
||||
next: displaying-data-ja-JP.html
|
||||
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: why-react-ko-KR
|
||||
title: 왜 React인가?
|
||||
permalink: why-react-ko-KR.html
|
||||
permalink: docs/why-react-ko-KR.html
|
||||
next: displaying-data-ko-KR.html
|
||||
---
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: why-react
|
||||
title: Why React?
|
||||
permalink: why-react.html
|
||||
permalink: docs/why-react.html
|
||||
next: displaying-data.html
|
||||
---
|
||||
React is a JavaScript library for creating user interfaces by Facebook and Instagram. Many people choose to think of React as the **V** in **[MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)**.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: why-react-ru-RU
|
||||
title: Почему именно React?
|
||||
permalink: why-react-ru-RU.html
|
||||
permalink: docs/why-react-ru-RU.html
|
||||
next: displaying-data-ru-RU.html
|
||||
---
|
||||
React — библиотека JavaScript для создания интерфейсов от команд Facebook и Instagram. Многие ассоциируют React с понятием **View** в паттерне **[MVC](https://ru.wikipedia.org/wiki/Model-View-Controller)**.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: why-react-zh-CN
|
||||
title: 为什么使用 React?
|
||||
permalink: why-react-zh-CN.html
|
||||
permalink: docs/why-react-zh-CN.html
|
||||
next: displaying-data-zh-CN.html
|
||||
---
|
||||
React 是一个 Facebook 和 Instagram 用来创建用户界面的 JavaScript 库。很多人选择将 React 认为是 **[MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)** 中的 **V**(视图)。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: why-react-zh-TW
|
||||
title: Why React?
|
||||
permalink: why-react-zh-TW.html
|
||||
permalink: docs/why-react-zh-TW.html
|
||||
next: displaying-data.html
|
||||
---
|
||||
React是Facebook和Instagram用來建立使用者介面的JavaScript函式庫. 很多人認為React就是處理 **[MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)**架構中 **V** 的部份.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: displaying-data-it-IT
|
||||
title: Visualizzare Dati
|
||||
permalink: displaying-data-it-IT.html
|
||||
permalink: docs/displaying-data-it-IT.html
|
||||
prev: why-react-it-IT.html
|
||||
next: jsx-in-depth-it-IT.html
|
||||
---
|
||||
@@ -19,8 +19,9 @@ Diamo un'occhiata ad un esempio davvero semplice. Creiamo un file dal nome `hell
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Hello React</title>
|
||||
<script src="https://fb.me/react-{{site.react_version}}.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
|
||||
<script src="https://npmcdn.com/react@{{site.react_version}}/dist/react.js"></script>
|
||||
<script src="https://npmcdn.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
|
||||
<script src="https://npmcdn.com/babel-core@5.8.38/browser.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="example"></div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: displaying-data-ja-JP
|
||||
title: データを表示する
|
||||
permalink: displaying-data-ja-JP.html
|
||||
permalink: docs/displaying-data-ja-JP.html
|
||||
prev: why-react-ja-JP.html
|
||||
next: jsx-in-depth-ja-JP.html
|
||||
|
||||
@@ -19,8 +19,9 @@ UIについて、最も基本的なことは、いくつかのデータを表示
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Hello React</title>
|
||||
<script src="https://fb.me/react-{{site.react_version}}.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
|
||||
<script src="https://npmcdn.com/react@{{site.react_version}}/dist/react.js"></script>
|
||||
<script src="https://npmcdn.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
|
||||
<script src="https://npmcdn.com/babel-core@5.8.38/browser.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="example"></div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: displaying-data-ko-KR
|
||||
title: 데이터를 표시하기
|
||||
permalink: displaying-data-ko-KR.html
|
||||
permalink: docs/displaying-data-ko-KR.html
|
||||
prev: why-react-ko-KR.html
|
||||
next: jsx-in-depth-ko-KR.html
|
||||
---
|
||||
@@ -18,9 +18,9 @@ UI를 가지고 할 수 있는 가장 기초적인 것은 데이터를 표시하
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Hello React</title>
|
||||
<script src="https://fb.me/react-{{site.react_version}}.js"></script>
|
||||
<script src="https://fb.me/react-dom-{{site.react_version}}.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
|
||||
<script src="https://npmcdn.com/react@{{site.react_version}}/dist/react.js"></script>
|
||||
<script src="https://npmcdn.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
|
||||
<script src="https://npmcdn.com/babel-core@5.8.38/browser.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="example"></div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: displaying-data
|
||||
title: Displaying Data
|
||||
permalink: displaying-data.html
|
||||
permalink: docs/displaying-data.html
|
||||
prev: why-react.html
|
||||
next: jsx-in-depth.html
|
||||
---
|
||||
@@ -18,9 +18,9 @@ Let's look at a really simple example. Create a `hello-react.html` file with the
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Hello React</title>
|
||||
<script src="https://fb.me/react-{{site.react_version}}.js"></script>
|
||||
<script src="https://fb.me/react-dom-{{site.react_version}}.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
|
||||
<script src="https://npmcdn.com/react@{{site.react_version}}/dist/react.js"></script>
|
||||
<script src="https://npmcdn.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
|
||||
<script src="https://npmcdn.com/babel-core@5.8.38/browser.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="example"></div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: displaying-data-ru-RU
|
||||
title: Отображение данных
|
||||
permalink: displaying-data-ru-RU.html
|
||||
permalink: docs/displaying-data-ru-RU.html
|
||||
prev: why-react-ru-RU.html
|
||||
next: jsx-in-depth.html
|
||||
---
|
||||
@@ -18,9 +18,9 @@ next: jsx-in-depth.html
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Hello React</title>
|
||||
<script src="https://fb.me/react-{{site.react_version}}.js"></script>
|
||||
<script src="https://fb.me/react-dom-{{site.react_version}}.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
|
||||
<script src="https://npmcdn.com/react@{{site.react_version}}/dist/react.js"></script>
|
||||
<script src="https://npmcdn.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
|
||||
<script src="https://npmcdn.com/babel-core@5.8.38/browser.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="example"></div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: displaying-data-zh-CN
|
||||
title: 显示数据
|
||||
permalink: displaying-data-zh-CN.html
|
||||
permalink: docs/displaying-data-zh-CN.html
|
||||
prev: why-react-zh-CN.html
|
||||
next: jsx-in-depth-zh-CN.html
|
||||
---
|
||||
@@ -18,9 +18,9 @@ next: jsx-in-depth-zh-CN.html
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Hello React</title>
|
||||
<script src="https://fb.me/react-{{site.react_version}}.js"></script>
|
||||
<script src="https://fb.me/react-dom-{{site.react_version}}.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
|
||||
<script src="https://npmcdn.com/react@{{site.react_version}}/dist/react.js"></script>
|
||||
<script src="https://npmcdn.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
|
||||
<script src="https://npmcdn.com/babel-core@5.8.38/browser.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="example"></div>
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
---
|
||||
id: displaying-data-zh-TW
|
||||
title: Displaying Data
|
||||
permalink: docs/displaying-data-zh-TW.html
|
||||
prev: why-react-zh-TW.html
|
||||
next: jsx-in-depth-zh-TW.html
|
||||
---
|
||||
|
||||
在使用者介面所能做最基本的事情就是呈現資料. React讓呈現資料變得更加容易並且當資料有所變動時也能自動地讓使用者介面保持呈現最新的資料.
|
||||
|
||||
## 入門(Getting Started)
|
||||
|
||||
我們從一個相當簡單的範例開始. 建立一個名為 `hello-react.html` 的檔案裡面包含下列程式碼:
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Hello React</title>
|
||||
<script src="https://npmcdn.com/react@{{site.react_version}}/dist/react.js"></script>
|
||||
<script src="https://npmcdn.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script>
|
||||
<script src="https://npmcdn.com/babel-core@5.8.38/browser.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="example"></div>
|
||||
<script type="text/babel">
|
||||
|
||||
// ** 將你的程式碼放在這裡! **
|
||||
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
這份文件其他部份,我們將只會專注在JavaScript程式碼解說上,並且假設程式碼會被放置在如上述模板的註解區塊內. 用下列的JSX程式碼取代上述註解區塊:
|
||||
|
||||
```javascript
|
||||
var HelloWorld = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
<p>
|
||||
Hello, <input type="text" placeholder="Your name here" />!
|
||||
It is {this.props.date.toTimeString()}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
setInterval(function() {
|
||||
ReactDOM.render(
|
||||
<HelloWorld date={new Date()} />,
|
||||
document.getElementById('example')
|
||||
);
|
||||
}, 500);
|
||||
```
|
||||
|
||||
## 反應性更新(Reactive Updates)
|
||||
|
||||
在一個瀏覽器上開啟檔案 `hello-react.html` 並且在文字區塊填入你的名字. 請注意React僅僅改變UI上的時間字串 — 你在文字區塊輸入的任何文字依舊存在, 即使你並沒有寫任何程式碼來管理這個行為.React可以為你分辨出這樣的行為並且做出正確的回應.
|
||||
|
||||
之所以能夠分辨出這樣的行為是因為React除非在真正有必要的情況下,否則不會對DOM做任何操作. **它使用一個快速的, 內部虛擬的DOM(internal mock DOM)來為你施行比較和計算最有效率的DOM變動(DOM mutation)**
|
||||
|
||||
輸入到元件(component)的內容我們稱為`props` — 是屬性("properties")的簡稱. 他們在JSX語法中作為傳遞屬性之用. 你應該把這些屬性當做元件中不可被改變的, 也就是說, **永遠不要對 `this.props` 做寫入的行為**.
|
||||
|
||||
## 元件就是函數(Components are Just Like Functions)
|
||||
|
||||
React元件(components)是非常簡單的. 你能把它們想成是簡單的函數帶入`props`和`state`(後面會討論這部份)並且呈送給HTML(render HTML). 在心中保持住這個想法, 就能容易理解元件(components).
|
||||
React components are very simple. You can think of them as simple functions that take in `props` and `state` (discussed later) and render HTML. With this in mind, components are easy to reason about.
|
||||
|
||||
> 注意(Note):
|
||||
>
|
||||
> **一個局限性**: React元件(components)只能呈送(render)給一個單一根節點(root node). 如果你想要回傳多個節點(multiple nodes)他們*必須*被包裹在單一根節點內.
|
||||
|
||||
## JSX語法
|
||||
|
||||
我們深信元件(components)才是分離關注點(separate concerns)的正確方法, 而並非傳統的模板("templates")和顯示邏輯("display logic")觀念. 我們認為標記(markup)和產生它的程式碼應當緊密的綁在一起. 另外, 顯示邏輯(display logic)常常是非常複雜的, 若使用模板語言(template languages)來詮釋它就顯得笨重或累贅.
|
||||
|
||||
我們找到解決這個問題的最佳解答就是直接在JavaScript程式內產生HTML和元件樹(component trees)如此一來你就能使用真正的程式語言的表達能力(expressive power)來建立使用者介面(UIs).
|
||||
|
||||
為了能更輕鬆實現, 我們增加了一個非常簡單, **可選擇性使用的** 類似HTML的語法(HTML-like syntax) 來創建這些React樹節點(React tree nodes).
|
||||
|
||||
**JSX能讓你使用HTML語法來創建JavaScript物件.** 在React裡使用純JavaScript來產生一個鏈接(link)你可以這樣寫:
|
||||
|
||||
`React.createElement('a', {href: 'https://facebook.github.io/react/'}, 'Hello!')`
|
||||
|
||||
使用JSX語法則變成:
|
||||
|
||||
`<a href="https://facebook.github.io/react/">Hello!</a>`
|
||||
|
||||
我們發現這麼做能讓建立React apps更加容易並且設計師往往喜歡語法, 但是每個人都有他們自己的工作流程, 所以**在使用React時JSX並非必要.**
|
||||
|
||||
JSX非常簡單易懂. 若想要學習更多關於JSX, 請參閱 [JSX in depth](/react/docs/jsx-in-depth.html). 或是可以使用線上及時轉換工具 [the Babel REPL](https://babeljs.io/repl/).
|
||||
|
||||
JSX類似於HTML, 但不盡然完全相同. 參閱 [JSX gotchas](/react/docs/jsx-gotchas.html) 來比較一些主要的差異點.
|
||||
|
||||
[Babel exposes a number of ways to get started using JSX](http://babeljs.io/docs/setup/), 涵蓋從命令列工具到Ruby on Rails整合. 可以從中選擇最適合你的工具.
|
||||
|
||||
## React不使用JSX的範例(React without JSX)
|
||||
|
||||
JSX完全是可選擇性使用的; 你可以不拿JSX跟React一起使用. 你能在純粹的JavaScript環境中使用`React.createElement`來創建React元素(React elements), 它搭配一個標籤名(tag name)或是元件(component), 一個屬性物件(properties object), 和數個選擇性子參數(child arguments).
|
||||
|
||||
```javascript
|
||||
var child1 = React.createElement('li', null, 'First Text Content');
|
||||
var child2 = React.createElement('li', null, 'Second Text Content');
|
||||
var root = React.createElement('ul', { className: 'my-list' }, child1, child2);
|
||||
ReactDOM.render(root, document.getElementById('example'));
|
||||
```
|
||||
|
||||
為了方便起見, 你能創建速記factory函式(short-hand factory functions)然後從自訂元件(custom components)建立元素(elements).
|
||||
|
||||
```javascript
|
||||
var Factory = React.createFactory(ComponentClass);
|
||||
...
|
||||
var root = Factory({ custom: 'prop' });
|
||||
ReactDOM.render(root, document.getElementById('example'));
|
||||
```
|
||||
|
||||
針對一般的HTML標籤React已經有內建的factories函式:
|
||||
|
||||
```javascript
|
||||
var root = React.DOM.ul({ className: 'my-list' },
|
||||
React.DOM.li(null, 'Text Content')
|
||||
);
|
||||
```
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: jsx-in-depth-it-IT
|
||||
title: JSX in Profondità
|
||||
permalink: jsx-in-depth-it-IT.html
|
||||
permalink: docs/jsx-in-depth-it-IT.html
|
||||
prev: displaying-data-it-IT.html
|
||||
next: jsx-spread-it-IT.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: jsx-in-depth
|
||||
title: JSXの深層
|
||||
permalink: jsx-in-depth-ja-JP.html
|
||||
permalink: docs/jsx-in-depth-ja-JP.html
|
||||
prev: displaying-data-ja-JP.html
|
||||
next: jsx-spread-ja_JP.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: jsx-in-depth-ko-KR
|
||||
title: JSX 깊이보기
|
||||
permalink: jsx-in-depth-ko-KR.html
|
||||
permalink: docs/jsx-in-depth-ko-KR.html
|
||||
prev: displaying-data-ko-KR.html
|
||||
next: jsx-spread-ko-KR.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: jsx-in-depth
|
||||
title: JSX in Depth
|
||||
permalink: jsx-in-depth.html
|
||||
permalink: docs/jsx-in-depth.html
|
||||
prev: displaying-data.html
|
||||
next: jsx-spread.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: jsx-in-depth-zh-CN
|
||||
title: 深入 JSX
|
||||
permalink: jsx-in-depth-zh-CN.html
|
||||
permalink: docs/jsx-in-depth-zh-CN.html
|
||||
prev: displaying-data-zh-CN.html
|
||||
next: jsx-spread-zh-CN.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: jsx-spread-it-IT
|
||||
title: Attributi Spread JSX
|
||||
permalink: jsx-spread-it-IT.html
|
||||
permalink: docs/jsx-spread-it-IT.html
|
||||
prev: jsx-in-depth-it-IT.html
|
||||
next: jsx-gotchas-it-IT.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: jsx-spread
|
||||
title: JSXの拡張属性
|
||||
permalink: jsx-spread-ja-JP.html
|
||||
permalink: docs/jsx-spread-ja-JP.html
|
||||
prev: jsx-in-depth-ja-JP.html
|
||||
next: jsx-gotchas-ja-JP.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: jsx-spread-ko-KR
|
||||
title: JSX 스프레드 어트리뷰트
|
||||
permalink: jsx-spread-ko-KR.html
|
||||
permalink: docs/jsx-spread-ko-KR.html
|
||||
prev: jsx-in-depth-ko-KR.html
|
||||
next: jsx-gotchas-ko-KR.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: jsx-spread
|
||||
title: JSX Spread Attributes
|
||||
permalink: jsx-spread.html
|
||||
permalink: docs/jsx-spread.html
|
||||
prev: jsx-in-depth.html
|
||||
next: jsx-gotchas.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: jsx-spread-zh-CN
|
||||
title: JSX 展开属性
|
||||
permalink: jsx-spread-zh-CN.html
|
||||
permalink: docs/jsx-spread-zh-CN.html
|
||||
prev: jsx-in-depth-zh-CN.html
|
||||
next: jsx-gotchas-zh-CN.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: jsx-gotchas-it-IT
|
||||
title: JSX Gotchas
|
||||
permalink: jsx-gotchas-it-IT.html
|
||||
permalink: docs/jsx-gotchas-it-IT.html
|
||||
prev: jsx-spread-it-IT.html
|
||||
next: interactivity-and-dynamic-uis-it-IT.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: jsx-gotchas
|
||||
title: JSXの理解
|
||||
permalink: jsx-gotchas-ja-JP.html
|
||||
permalink: docs/jsx-gotchas-ja-JP.html
|
||||
prev: jsx-spread-ja-JP.html
|
||||
next: interactivity-and-dynamic-uis-ja-JP.html
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: jsx-gotchas-ko-KR
|
||||
title: JSX Gotchas
|
||||
permalink: jsx-gotchas-ko-KR.html
|
||||
permalink: docs/jsx-gotchas-ko-KR.html
|
||||
prev: jsx-spread-ko-KR.html
|
||||
next: interactivity-and-dynamic-uis-ko-KR.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: jsx-gotchas
|
||||
title: JSX Gotchas
|
||||
permalink: jsx-gotchas.html
|
||||
permalink: docs/jsx-gotchas.html
|
||||
prev: jsx-spread.html
|
||||
next: interactivity-and-dynamic-uis.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: jsx-gotchas-zh-CN
|
||||
title: JSX 陷阱
|
||||
permalink: jsx-gotchas-zh-CN.html
|
||||
permalink: docs/jsx-gotchas-zh-CN.html
|
||||
prev: jsx-spread-zh-CN.html
|
||||
next: interactivity-and-dynamic-uis-zh-CN.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: interactivity-and-dynamic-uis-it-IT
|
||||
title: Interattività e UI Dinamiche
|
||||
permalink: interactivity-and-dynamic-uis-it-IT.html
|
||||
permalink: docs/interactivity-and-dynamic-uis-it-IT.html
|
||||
prev: jsx-gotchas-it-IT.html
|
||||
next: multiple-components-it-IT.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: interactivity-and-dynamic-uis
|
||||
title: 相互作用と動的なUI
|
||||
permalink: interactivity-and-dynamic-uis-ja-JP.html
|
||||
permalink: docs/interactivity-and-dynamic-uis-ja-JP.html
|
||||
prev: jsx-gotchas-ja-JP.html
|
||||
next: multiple-components-ja-JP.html
|
||||
---
|
||||
@@ -20,7 +20,7 @@ var LikeButton = React.createClass({
|
||||
this.setState({liked: !this.state.liked});
|
||||
},
|
||||
render: function() {
|
||||
var text = this.state.liked ? 'like' : 'haven\'t liked';
|
||||
var text = this.state.liked ? 'liked' : 'haven\'t liked';
|
||||
return (
|
||||
<p onClick={this.handleClick}>
|
||||
You {text} this. Click to toggle.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: interactivity-and-dynamic-uis-ko-KR
|
||||
title: 상호 작용 및 동적 UI
|
||||
permalink: interactivity-and-dynamic-uis-ko-KR.html
|
||||
permalink: docs/interactivity-and-dynamic-uis-ko-KR.html
|
||||
prev: jsx-gotchas-ko-KR.html
|
||||
next: multiple-components-ko-KR.html
|
||||
---
|
||||
@@ -19,7 +19,7 @@ var LikeButton = React.createClass({
|
||||
this.setState({liked: !this.state.liked});
|
||||
},
|
||||
render: function() {
|
||||
var text = this.state.liked ? 'like' : 'haven\'t liked';
|
||||
var text = this.state.liked ? 'liked' : 'haven\'t liked';
|
||||
return (
|
||||
<p onClick={this.handleClick}>
|
||||
You {text} this. Click to toggle.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: interactivity-and-dynamic-uis
|
||||
title: Interactivity and Dynamic UIs
|
||||
permalink: interactivity-and-dynamic-uis.html
|
||||
permalink: docs/interactivity-and-dynamic-uis.html
|
||||
prev: jsx-gotchas.html
|
||||
next: multiple-components.html
|
||||
---
|
||||
@@ -23,7 +23,7 @@ class LikeButton extends React.Component {
|
||||
this.setState({liked: !this.state.liked});
|
||||
}
|
||||
render() {
|
||||
const text = this.state.liked ? 'like' : 'haven\'t liked';
|
||||
const text = this.state.liked ? 'liked' : 'haven\'t liked';
|
||||
return (
|
||||
<div onClick={this.handleClick}>
|
||||
You {text} this. Click to toggle.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: interactivity-and-dynamic-uis-ru-RU
|
||||
title: Интерактивные и динамические интерфейсы
|
||||
permalink: interactivity-and-dynamic-uis-ru-RU.html
|
||||
permalink: docs/interactivity-and-dynamic-uis-ru-RU.html
|
||||
prev: jsx-gotchas.html
|
||||
next: multiple-components.html
|
||||
---
|
||||
@@ -19,7 +19,7 @@ var LikeButton = React.createClass({
|
||||
this.setState({liked: !this.state.liked});
|
||||
},
|
||||
render: function() {
|
||||
var text = this.state.liked ? 'like' : 'haven\'t liked';
|
||||
var text = this.state.liked ? 'liked' : 'haven\'t liked';
|
||||
return (
|
||||
<p onClick={this.handleClick}>
|
||||
You {text} this. Click to toggle.
|
||||
@@ -63,10 +63,10 @@ React считает интерфейсы обыкновенными конеч
|
||||
**Старайтесь делать компоненты без состояния.** Следуя этому правилу, вы будете выносить работу с состоянием с уровня представления в другие, более подходящие места. Тем самым, вы снизите сложность приложения, упрощая его понимание.
|
||||
|
||||
Основной принцип такой: создаются несколько компонентов без состояния, которые формируют дерево. Они будут заниматься только отрисовкой данных. А все данные для них будут у родительского компонента, который будет на вершине этого дерева компонентов. Он и будет передавать данные дочерним узлам через `props`. Этот компонент с общим состоянием содержит в себе всю логику взаимодействия, а дочерние компоненты будут только отрисовывать данные, которые будут у них в `props`.
|
||||
|
||||
|
||||
## Какие данные *надо* помещать в состояние?
|
||||
|
||||
**Состояние должно содержать данные, которые нужны для обновления интерфейса.** В реальных приложениях такие данные, как правило, незначительны по объему, и могут быть сериализованы в JSON. Когда вы создаете компонент с состоянием, старайтесь поместить в него минимум данных. А уже внутри метода `render()` вычисляйте остальные данные, используя значения из состояния.
|
||||
**Состояние должно содержать данные, которые нужны для обновления интерфейса.** В реальных приложениях такие данные, как правило, незначительны по объему, и могут быть сериализованы в JSON. Когда вы создаете компонент с состоянием, старайтесь поместить в него минимум данных. А уже внутри метода `render()` вычисляйте остальные данные, используя значения из состояния.
|
||||
Со временем вы увидите, что такой подход позволяет создавать более стройные и устойчивые к изменениям приложения. Добавление в состояние лишних данных требует от вас дополнительных затрат на их синхронизацию. Но этого можно избежать, если позволить React делать все эти вычисления за вас.
|
||||
|
||||
## Какие данные *не надо* помещать в состояние?
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: interactivity-and-dynamic-uis-zh-CN
|
||||
title: 动态交互式用户界面
|
||||
permalink: interactivity-and-dynamic-uis-zh-CN.html
|
||||
permalink: docs/interactivity-and-dynamic-uis-zh-CN.html
|
||||
prev: jsx-gotchas-zh-CN.html
|
||||
next: multiple-components-zh-CN.html
|
||||
---
|
||||
@@ -19,7 +19,7 @@ var LikeButton = React.createClass({
|
||||
this.setState({liked: !this.state.liked});
|
||||
},
|
||||
render: function() {
|
||||
var text = this.state.liked ? 'like' : 'haven\'t liked';
|
||||
var text = this.state.liked ? 'liked' : 'haven\'t liked';
|
||||
return (
|
||||
<p onClick={this.handleClick}>
|
||||
You {text} this. Click to toggle.
|
||||
@@ -42,9 +42,9 @@ React 里只需把事件处理器(event handler)以骆峰命名(camelCased
|
||||
|
||||
在幕后,React 做了一些操作来让代码高效运行且易于理解。
|
||||
|
||||
**Autobinding:** 在 JavaScript 里创建回调的时候,为了保证 `this` 的正确性,一般都需要显式地绑定方法到它的实例上。在 React,所有方法被自动绑定到了它的组件实例上(除非使用ES6的class符号)。React 还缓存这些绑定方法,所以 CPU 和内存都是非常高效。而且还能减少打字!
|
||||
**自动绑定:** 在 JavaScript 里创建回调的时候,为了保证 `this` 的正确性,一般都需要显式地绑定方法到它的实例上。在 React 中,所有方法被自动绑定到了它的组件实例上([除非使用ES6的class符号](/react/docs/reusable-components.html#no-autobinding))。React 还缓存这些绑定方法,所以 CPU 和内存都是非常高效。而且还能减少打字!
|
||||
|
||||
**事件代理 :** React 实际并没有把事件处理器绑定到节点本身。当 React 启动的时候,它在最外层使用唯一一个事件监听器处理所有事件。当组件被加载和卸载时,只是在内部映射里添加或删除事件处理器。当事件触发,React 根据映射来决定如何分发。当映射里处理器时,会当作空操作处理。参考 [David Walsh 很棒的文章](http://davidwalsh.name/event-delegate) 了解这样做高效的原因。
|
||||
**事件代理:** React 实际并没有把事件处理器绑定到节点本身。当 React 启动的时候,它在最外层使用唯一一个事件监听器处理所有事件。当组件被加载和卸载时,只是在内部映射里添加或删除事件处理器。当事件触发,React 根据映射来决定如何分发。当映射里没有事件处理函数时,会当作空操作处理。参考 [David Walsh 很棒的文章](http://davidwalsh.name/event-delegate) 了解这样做高效的原因。
|
||||
|
||||
## 组件其实是状态机(State Machines)
|
||||
|
||||
@@ -54,7 +54,7 @@ React 里,只需更新组件的 state,然后根据新的 state 重新渲染
|
||||
|
||||
## State 工作原理
|
||||
|
||||
常用的通知 React 数据变化的方法是调用 `setState(data, callback)`。这个方法会合并(merge) `data` 到 `this.state`,并重新渲染组件。渲染完成后,调用可选的 `callback` 回调。大部分情况下不需要提供 `callback`,因为 React 会负责把界面更新到最新状态。
|
||||
常用的通知 React 数据变化的方法是调用 `setState(data, callback)`。这个方法会合并(merge) `data` 到 `this.state`,并重新渲染组件。重新渲染完成后,调用可选的 `callback` 回调。大部分情况下不需要提供 `callback`,因为 React 会负责把界面更新到最新状态。
|
||||
|
||||
## 哪些组件应该有 State?
|
||||
|
||||
@@ -66,12 +66,12 @@ React 里,只需更新组件的 state,然后根据新的 state 重新渲染
|
||||
|
||||
## 哪些 *应该* 作为 State?
|
||||
|
||||
**State 应该包括那些可能被组件的事件处理器改变并触发用户界面更新的数据。** 真实的应用中这种数据一般都很小且能被 JSON 序列化。当创建一个状态化的组件时,想象一下表示它的状态最少需要哪些数据,并只把这些数据存入 `this.state`。在 `render()` 里再根据 state 来计算你需要的其它数据。你会发现以这种方式思考和开发程序最终往往是正确的,因为如果在 state 里添加冗余数据或计算所得数据,需要你经常手动保持数据同步,不能让 React 来帮你处理。
|
||||
**State 应该包括那些可能被组件的事件处理器改变并触发用户界面更新的数据。** 真实的应用中这种数据一般都很小且能被 JSON 序列化。当创建一个状态化的组件时,思考一下表示它的状态最少需要哪些数据,并只把这些数据存入 `this.state`。在 `render()` 里再根据 state 来计算你需要的其它数据。你会发现以这种方式思考和开发程序最终往往是正确的,因为如果在 state 里添加冗余数据或计算所得数据,那么你就需要经常手动保持数据同步,而不能让 React 来帮你处理。
|
||||
|
||||
## 哪些 *不应该* 作为 State?
|
||||
|
||||
`this.state` 应该仅包括能表示用户界面状态所需的最少数据。因些,它不应该包括:
|
||||
`this.state` 应该仅包括能表示用户界面状态所需的最少数据。因此,它不应该包括:
|
||||
|
||||
* **计算所得数据:** 不要担心根据 state 来预先计算数据 —— 把所有的计算都放到 `render()` 里更容易保证用户界面和数据的一致性。例如,在 state 里有一个数组(listItems),我们要把数组长度渲染成字符串, 直接在 `render()` 里使用 `this.state.listItems.length + ' list items'` 比把它放到 state 里好的多。
|
||||
* **React 组件:** 在 `render()` 里使用当前 props 和 state 来创建它。
|
||||
* **基于 props 的重复数据:** 尽可能使用 props 来作为实际状态的源。把 props 保存到 state 的一个有效的场景是需要知道它以前值的时候,因为 props 可能因为父组件重绘的结果而变化。
|
||||
* **基于 props 的重复数据:** 尽可能使用 props 来作为实际状态的源。把 props 保存到 state 的一个有效的场景是需要知道它以前值的时候,因为 props 可能因为父组件的重绘而变化。
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: multiple-components-it-IT
|
||||
title: Componenti Multipli
|
||||
permalink: multiple-components-it-IT.html
|
||||
permalink: docs/multiple-components-it-IT.html
|
||||
prev: interactivity-and-dynamic-uis-it-IT.html
|
||||
next: reusable-components-it-IT.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: multiple-components
|
||||
title: 複数のコンポーネント
|
||||
permalink: multiple-components-ja-JP.html
|
||||
permalink: docs/multiple-components-ja-JP.html
|
||||
prev: interactivity-and-dynamic-uis-ja-JP.html
|
||||
next: reusable-components-ja-JP.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: multiple-components-ko-KR
|
||||
title: 복합 컴포넌트
|
||||
permalink: multiple-components-ko-KR.html
|
||||
permalink: docs/multiple-components-ko-KR.html
|
||||
prev: interactivity-and-dynamic-uis-ko-KR.html
|
||||
next: reusable-components-ko-KR.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: multiple-components
|
||||
title: Multiple Components
|
||||
permalink: multiple-components.html
|
||||
permalink: docs/multiple-components.html
|
||||
prev: interactivity-and-dynamic-uis.html
|
||||
next: reusable-components.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: multiple-components-zh-CN
|
||||
title: 复合组件
|
||||
permalink: multiple-components-zh-CN.html
|
||||
permalink: docs/multiple-components-zh-CN.html
|
||||
prev: interactivity-and-dynamic-uis-zh-CN.html
|
||||
next: reusable-components-zh-CN.html
|
||||
---
|
||||
@@ -54,9 +54,9 @@ ReactDOM.render(
|
||||
|
||||
## 从属关系
|
||||
|
||||
上面例子中,`Avatar` 拥有 `PagePic` 和 `PageLink` 的实例。`拥有者` 就是给其它组件设置 `props` 的那个组件。更正式地说,如果组件 `Y` 在 `render()` 方法是创建了组件 `X`,那么 `Y` 就拥有 `X`。上面讲过,组件不能修改自身的 `props` - 它们总是与它们拥有者设置的保持一致。这是保持用户界面一致性的基本不变量。
|
||||
上面例子中,`Avatar` 拥有 `PagePic` 和 `PageLink` 的实例。`拥有者` 就是给其它组件设置 `props` 的那个组件。更正式地说,如果组件 `Y` 在 `render()` 方法是创建了组件 `X`,那么 `Y` 就拥有 `X`。上面讲过,组件不能修改自身的 `props` - 它们总是与它们的拥有者所设置的值保持一致。这是保持用户界面一致性的基本不变量。
|
||||
|
||||
把从属关系与父子关系加以区别至关重要。从属关系是 React 特有的,而父子关系简单来讲就是DOM 里的标签的关系。在上一个例子中,`Avatar` 拥有 `div`、`PagePic` 和 `PageLink` 实例,`div` 是 `PagePic` 和 `PageLink` 实例的**父级**(但不是拥有者)。
|
||||
把从属关系与父子关系加以区别至关重要。从属关系是 React 特有的,而父子关系简单来讲就是 DOM 里的标签的关系。在上一个例子中,`Avatar` 拥有 `div`、`PagePic` 和 `PageLink` 实例,`div` 是 `PagePic` 和 `PageLink` 实例的**父级**(但不是拥有者)。
|
||||
|
||||
## 子级
|
||||
|
||||
@@ -66,7 +66,7 @@ ReactDOM.render(
|
||||
<Parent><Child /></Parent>
|
||||
```
|
||||
|
||||
`Parent` 能通过专门的 `this.props.children` props 读取子级。**`this.props.children` 是一个不透明的数据结构:** 通过 [React.Children 工具类](/react/docs/top-level-api.html#react.children) 来操作。
|
||||
`Parent` 能通过专门的 `this.props.children` prop 读取子级。**`this.props.children` 是一个不透明的数据结构:** 通过 [React.Children 工具类](/react/docs/top-level-api.html#react.children) 来操作。
|
||||
|
||||
### 子级校正(Reconciliation)
|
||||
|
||||
@@ -123,7 +123,8 @@ ReactDOM.render(
|
||||
```
|
||||
|
||||
当 React 校正带有 key 的子级时,它会确保它们被重新排序(而不是破坏)或者删除(而不是重用)。
|
||||
`务必` 把 `key` 添加到子级数组里组件本身上,而不是每个子级内部最外层 HTML 上:
|
||||
|
||||
务必把 `key` 添加到子级数组中的组件本身上,而不是数组中每个子级组件内部的最外层 HTML 上:
|
||||
|
||||
```javascript
|
||||
// 错误!
|
||||
@@ -164,11 +165,11 @@ var MyComponent = React.createClass({
|
||||
});
|
||||
```
|
||||
|
||||
也可以传递ReactFragment 对象 来做有 key 的子级。详见[Keyed Fragments](create-fragment.html)
|
||||
也可以传递 ReactFragment 对象来做有 key 的子级。详见[Keyed Fragments](create-fragment.html)
|
||||
|
||||
## 数据流
|
||||
|
||||
React 里,数据通过上面介绍过的 `props` 从拥有者流向归属者。这就是高效的单向数据绑定(one-way data binding):拥有者通过它的 `props` 或 `state` 计算出一些值,并把这些值绑定到它们拥有的组件的 props 上。因为这个过程会递归地调用,所以数据变化会自动在所有被使用的地方自动反映出来。
|
||||
React 里,数据通过上面介绍过的 `props` 从拥有者流向归属者。这就是高效的单向数据绑定(one-way data binding):拥有者们通过它们的 `props` 或 `state` 计算出一些值,并把这些值绑定到它们拥有的组件的 props 上。因为这个过程会递归地调用,所以数据变化会自动在所有它们被使用的地方反映出来。
|
||||
|
||||
|
||||
## 性能提醒
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: reusable-components-it-IT
|
||||
title: Componenti Riutilizzabili
|
||||
permalink: reusable-components-it-IT.html
|
||||
permalink: docs/reusable-components-it-IT.html
|
||||
prev: multiple-components-it-IT.html
|
||||
next: transferring-props-it-IT.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: reusable-components
|
||||
title: 再利用可能なコンポーネント
|
||||
permalink: reusable-components-ja-JP.html
|
||||
permalink: docs/reusable-components-ja-JP.html
|
||||
prev: multiple-components-ja-JP.html
|
||||
next: transferring-props-ja-JP.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: reusable-components-ko-KR
|
||||
title: 재사용가능한 컴포넌트
|
||||
permalink: reusable-components-ko-KR.html
|
||||
permalink: docs/reusable-components-ko-KR.html
|
||||
prev: multiple-components-ko-KR.html
|
||||
next: transferring-props-ko-KR.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: reusable-components
|
||||
title: Reusable Components
|
||||
permalink: reusable-components.html
|
||||
permalink: docs/reusable-components.html
|
||||
prev: multiple-components.html
|
||||
next: transferring-props.html
|
||||
---
|
||||
@@ -132,7 +132,7 @@ var ComponentWithDefaultProps = React.createClass({
|
||||
});
|
||||
```
|
||||
|
||||
The result of `getDefaultProps()` will be cached and used to ensure that `this.props.value` will have a value if it was not specified by the parent component. This allows you to safely just use your props without having to write repetitive and fragile code to handle that yourself.
|
||||
The result of `getDefaultProps()` will be cached and used to ensure that `this.props.value` will have a value if it was not specified by the owner component. This allows you to safely just use your props without having to write repetitive and fragile code to handle that yourself.
|
||||
|
||||
## Transferring Props: A Shortcut
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: reusable-components-zh-CN
|
||||
title: 可复用组件
|
||||
permalink: reusable-components-zh-CN.html
|
||||
permalink: docs/reusable-components-zh-CN.html
|
||||
prev: multiple-components-zh-CN.html
|
||||
next: transferring-props-zh-CN.html
|
||||
---
|
||||
@@ -119,7 +119,7 @@ var ComponentWithDefaultProps = React.createClass({
|
||||
|
||||
## 传递 Props:捷径
|
||||
|
||||
有一些常用的 React 组件只是对 HTML 做简单扩展。通常,你想 复制任何传进你的组件的HTML属性 到底层的HTML元素上。为了减少输入,你可以用 JSX _spread_ 语法来完成:
|
||||
有一些常用的 React 组件只是对 HTML 做简单扩展。通常,你想复制任何传进你的组件的HTML属性到底层的HTML元素上。为了减少输入,你可以用 JSX _spread_ 语法来完成:
|
||||
|
||||
```javascript
|
||||
var CheckLink = React.createClass({
|
||||
@@ -139,9 +139,9 @@ ReactDOM.render(
|
||||
|
||||
## Mixins
|
||||
|
||||
组件是 React 里复用代码最佳方式,但是有时一些复杂的组件间也需要共用一些功能。有时会被称为 [跨切面关注点](https://en.wikipedia.org/wiki/Cross-cutting_concern)。React 使用 `mixins` 来解决这类问题。
|
||||
组件是 React 里复用代码的最佳方式,但是有时一些不同的组件间也需要共用一些功能。有时会被称为 [跨切面关注点](https://en.wikipedia.org/wiki/Cross-cutting_concern)。React 使用 `mixins` 来解决这类问题。
|
||||
|
||||
一个通用的场景是:一个组件需要定期更新。用 `setInterval()` 做很容易,但当不需要它的时候取消定时器来节省内存是非常重要的。React 提供 [生命周期方法](/react/docs/working-with-the-browser.html#component-lifecycle) 来告知组件创建或销毁的时间。下面来做一个简单的 mixin,使用 `setInterval()` 并保证在组件销毁时清理定时器。
|
||||
一个通用的场景是:一个组件需要定期更新。用 `setInterval()` 做很容易,但当不需要它的时候取消定时器来节省内存是非常重要的。React 提供 [生命周期方法](/react/docs/working-with-the-browser.html#component-lifecycle) 来告知你组件创建或销毁的时间。下面来做一个简单的 mixin,使用 `setInterval()` 并保证在组件销毁时清理定时器。
|
||||
|
||||
```javascript
|
||||
var SetIntervalMixin = {
|
||||
@@ -186,7 +186,7 @@ ReactDOM.render(
|
||||
|
||||
## ES6 Classes
|
||||
|
||||
你也可以以一个简单的JavaScript 类来定义你的React classes。使用ES6 class的例子:
|
||||
你也可以以一个简单的 JavaScript 类来定义你的React classes。使用ES6 class的例子:
|
||||
|
||||
```javascript
|
||||
class HelloMessage extends React.Component {
|
||||
@@ -197,9 +197,9 @@ class HelloMessage extends React.Component {
|
||||
ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
|
||||
```
|
||||
|
||||
API近似于 `React.createClass` 除了 `getInitialState`。 你应该在构造函数里设置你的`state`,而不是提供一个单独的 `getInitialState` 方法。
|
||||
API近似于 `React.createClass` 除了 `getInitialState`。 你应该在构造函数里设置你的`state`,而不是提供一个单独的 `getInitialState` 方法。就像 `getInitialState` 的返回值,你赋给 `this.state` 的值会被作为组件的初始 state。
|
||||
|
||||
另一个不同是 `propTypes` 和 `defaultProps` 在构造函数而不是class body里被定义为属性。
|
||||
另一个不同是 `propTypes` 和 `defaultProps` 是在构造函数里被定义为属性,而不是在 class body 里。
|
||||
|
||||
```javascript
|
||||
export class Counter extends React.Component {
|
||||
@@ -224,11 +224,38 @@ Counter.defaultProps = { initialCount: 0 };
|
||||
|
||||
### 无自动绑定
|
||||
|
||||
方法遵循正式的ES6 class的语义,意味着它们不会自动绑定`this`到实例上。你必须显示的使用`.bind(this)` or [箭头函数](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions) `=>`.
|
||||
方法遵循正式的ES6 class的语义,意味着它们不会自动绑定`this`到实例上。你必须显示的使用`.bind(this)` or [箭头函数](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions) `=>`:
|
||||
|
||||
```javascript
|
||||
// 你可以使用 bind() 来绑定 `this`
|
||||
<div onClick={this.tick.bind(this)}>
|
||||
|
||||
// 或者你可以使用箭头函数
|
||||
<div onClick={() => this.tick()}>
|
||||
```
|
||||
|
||||
我们建议你在构造函数中绑定事件处理器,这样对于所有实例它们只需绑定一次:
|
||||
|
||||
```javascript
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {count: props.initialCount};
|
||||
this.tick = this.tick.bind(this);
|
||||
}
|
||||
```
|
||||
|
||||
现在你可以直接使用 `this.tick` 因为它已经在构造函数里绑定过一次了。
|
||||
|
||||
```javascript
|
||||
// 它已经在构造函数里绑定过了
|
||||
<div onClick={this.tick}>
|
||||
```
|
||||
|
||||
这对应用的性能有帮助,特别是当你用 [浅层比较](/react/docs/shallow-compare.html) 实现 [shouldComponentUpdate()](/react/docs/component-specs.html#updating-shouldcomponentupdate) 时。
|
||||
|
||||
### 没有 Mixins
|
||||
|
||||
不幸的是ES6的发布没有任何mixin的支持。因此,当你在ES6 classes下使用React时不支持mixins。作为替代,我们正在努力使它更容易支持这些用例不依靠mixins。
|
||||
不幸的是ES6的发布没有任何mixin的支持。因此,当你在ES6 classes下使用React时不支持mixins。作为替代,我们正在努力使它更容易不依靠mixins支持这些用例。
|
||||
|
||||
## 无状态函数
|
||||
|
||||
@@ -249,7 +276,7 @@ ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
|
||||
```
|
||||
|
||||
这个简化的组件API旨在用于那些纯函数态的组件 。这些组件必须没有保持任何内部状态,没有备份实例,也没有组件生命周期方法。他们纯粹的函数式的转化他们的输入,没有引用。
|
||||
然而,你仍然可以以设置为函数的properties的方式来指定 `.propTypes` 和 `.defaultProps`,就像你在ES6类里设置他们那样。
|
||||
然而,你仍然可以以设置函数 properties 的方式来指定 `.propTypes` 和 `.defaultProps`,就像你在ES6类里设置他们那样。
|
||||
|
||||
> 注意:
|
||||
>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: transferring-props-it-IT
|
||||
title: Trasferimento delle Proprietà
|
||||
permalink: transferring-props-it-IT.html
|
||||
permalink: docs/transferring-props-it-IT.html
|
||||
prev: reusable-components-it-IT.html
|
||||
next: forms-it-IT.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: transferring-props
|
||||
title: propsの移譲
|
||||
permalink: transferring-props-ja-JP.html
|
||||
permalink: docs/transferring-props-ja-JP.html
|
||||
prev: reusable-components-ja-JP.html
|
||||
next: forms-ja-JP.html
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: transferring-props-ko-KR
|
||||
title: Props 전달
|
||||
permalink: transferring-props-ko-KR.html
|
||||
permalink: docs/transferring-props-ko-KR.html
|
||||
prev: reusable-components-ko-KR.html
|
||||
next: forms-ko-KR.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: transferring-props
|
||||
title: Transferring Props
|
||||
permalink: transferring-props.html
|
||||
permalink: docs/transferring-props.html
|
||||
prev: reusable-components.html
|
||||
next: forms.html
|
||||
---
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
---
|
||||
id: transferring-props-zh-CN
|
||||
title: 传递 Props
|
||||
permalink: transferring-props-zh-CN.html
|
||||
permalink: docs/transferring-props-zh-CN.html
|
||||
prev: reusable-components-zh-CN.html
|
||||
next: forms-zh-CN.html
|
||||
---
|
||||
|
||||
React 里有一个非常常用的模式就是对组件做一层抽象。组件对外公开一个简单的属性(Props)来实现功能,但内部细节可能有非常复杂的实现。
|
||||
React 里有一个非常常用的模式就是对组件做一层抽象。组件对外公开一个简单的属性(Props)来实现功能,但内部的实现可能非常复杂。
|
||||
|
||||
可以使用 [JSX 展开属性](/react/docs/jsx-spread-zh-CN.html) 来合并现有的 props 和其它值:
|
||||
|
||||
@@ -53,7 +53,7 @@ ReactDOM.render(
|
||||
|
||||
有时把所有属性都传下去是不安全或啰嗦的。这时可以使用 [解构赋值](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) 中的剩余属性特性来把未知属性批量提取出来。
|
||||
|
||||
列出所有要当前使用的属性,后面跟着 `...other`。
|
||||
列出所有当前要使用的属性,后面跟着 `...other`。
|
||||
|
||||
```javascript
|
||||
var { checked, ...other } = props;
|
||||
@@ -118,11 +118,11 @@ function FancyCheckbox(props) {
|
||||
|
||||
> 注意:
|
||||
>
|
||||
> 顺序很重要,把 `{...other}` 放到 JSX props 前面会使它不被覆盖。上面例子中我们可以保证 input 的 type 是 `"checkbox"`。
|
||||
> 顺序很重要,把 `{...other}` 放到 JSX props 前面会使 props 不会被覆盖。上面例子中我们可以保证 input 的 type 是 `"checkbox"`。
|
||||
|
||||
## 剩余属性和展开属性 `...`
|
||||
|
||||
剩余属性可以把对象剩下的属性提取到一个新的对象。会把所有在解构赋值中列出的属性剔除。
|
||||
剩余属性可以把对象剩下的属性提取到一个新的对象。这会把所有在解构赋值中列出的属性剔除。
|
||||
|
||||
这是 [ECMAScript 草案](https://github.com/sebmarkbage/ecmascript-rest-spread) 中的试验特性。
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: forms-it-IT
|
||||
title: Moduli
|
||||
permalink: forms-it-IT.html
|
||||
permalink: docs/forms-it-IT.html
|
||||
prev: transferring-props-it-IT.html
|
||||
next: working-with-the-browser-it-IT.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: forms
|
||||
title: フォーム
|
||||
permalink: forms-ja-JP.html
|
||||
permalink: docs/forms-ja-JP.html
|
||||
prev: transferring-props-ja-JP.html
|
||||
next: working-with-the-browser-ja-JP.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: forms-ko-KR
|
||||
title: 폼
|
||||
permalink: forms-ko-KR.html
|
||||
permalink: docs/forms-ko-KR.html
|
||||
prev: transferring-props-ko-KR.html
|
||||
next: working-with-the-browser-ko-KR.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: forms
|
||||
title: Forms
|
||||
permalink: forms.html
|
||||
permalink: docs/forms.html
|
||||
prev: transferring-props.html
|
||||
next: working-with-the-browser.html
|
||||
---
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
---
|
||||
id: forms-zh-CN
|
||||
title: 表单组件
|
||||
permalink: forms-zh-CN.html
|
||||
permalink: docs/forms-zh-CN.html
|
||||
prev: transferring-props-zh-CN.html
|
||||
next: working-with-the-browser-zh-CN.html
|
||||
---
|
||||
|
||||
诸如 `<input>`、`<textarea>`、`<option>` 这样的表单组件不同于其他组件,因为他们可以通过用户交互发生变化。这些组件提供的界面使响应用户交互的表单数据处理更加容易。
|
||||
诸如 `<input>`、`<textarea>`、`<option>` 这样的表单组件不同于其他原生组件,因为他们可以通过用户交互发生变化。这些组件提供的界面使响应用户交互的表单数据处理更加容易。
|
||||
|
||||
关于 `<form>` 事件详情请查看 [表单事件](/react/docs/events-zh-CN.html#form-events)。
|
||||
|
||||
@@ -76,7 +76,7 @@ next: working-with-the-browser-zh-CN.html
|
||||
|
||||
### 复选框与单选按钮的潜在问题
|
||||
|
||||
当心,在力图标准化复选框与单选按钮的变换处理中,React使用`click` 事件代替 `change` 事件。在大多数情况下它们表现的如同预期,除了在`change` handler中调用`preventDefault` 。`preventDefault` 阻止了浏览器视觉上更新输入,即使`checked`被触发。变通的方式是要么移除`preventDefault`的调用,要么把`checked` 的触发放在一个`setTimeout`里。
|
||||
当心,在力图标准化复选框与单选按钮的变换处理中,React使用 `click` 事件代替 `change` 事件。在大多数情况下它们表现的如同预期,除了在`change` handler中调用`preventDefault` 。`preventDefault` 阻止了浏览器视觉上更新输入,即使`checked`被触发。变通的方式是要么移除`preventDefault`的调用,要么把`checked` 的触发放在一个`setTimeout`里。
|
||||
|
||||
## 不受控组件
|
||||
|
||||
@@ -102,7 +102,7 @@ next: working-with-the-browser-zh-CN.html
|
||||
}
|
||||
```
|
||||
|
||||
这个例子会像上面的 **不受控组件** 例子一样运行。
|
||||
这个例子会像上面的 **受控组件** 例子一样运行。
|
||||
|
||||
同样的, `<input type="checkbox">` 和 `<input type="radio">` 支持 `defaultChecked` 、 `<select>` 支持 `defaultValue`.
|
||||
|
||||
@@ -130,7 +130,7 @@ next: working-with-the-browser-zh-CN.html
|
||||
}
|
||||
```
|
||||
|
||||
既然这个方法描述了在任意时间点上的视图,那么文本输入框的值就应该*始终*为 `Untitled`。
|
||||
由于这个方法描述了在任意时间点上的视图,那么文本输入框的值就应该*始终*为 `Untitled`。
|
||||
|
||||
### 为什么 `<textarea>` 使用 `value` 属性?
|
||||
|
||||
@@ -141,7 +141,7 @@ next: working-with-the-browser-zh-CN.html
|
||||
<textarea name="description">This is the description.</textarea>
|
||||
```
|
||||
|
||||
对 HTML 而言,让开发者设置多行的值很容易。但是,React 是 JavaScript,没有字符串限制,可以使用 `\n` 实现换行。简言之,React 已经有 `value`、`defaultValue` 属性,`</textarea>` 组件的子节点扮演什么角色就有点模棱两可了。基于此, 设置 `<textarea>` 值时不应该使用子节点:
|
||||
对 HTML 而言,让开发者设置多行的值很容易。但是,由于 React 是 JavaScript,没有字符串限制,可以使用 `\n` 实现换行。简言之,React 已经有 `value`、`defaultValue` 属性,`<textarea>` 组件的子节点扮演什么角色就有点模棱两可了。基于此, 设置 `<textarea>` 值时不应该使用子节点:
|
||||
|
||||
```javascript
|
||||
<textarea name="description" value="This is a description." />
|
||||
@@ -151,7 +151,7 @@ next: working-with-the-browser-zh-CN.html
|
||||
|
||||
### 为什么 `<select>` 使用 `value` 属性
|
||||
|
||||
HTML 中 `<select>` 通常使用 `<option>` 的 `selected` 属性设置选中状态;React 为了更方面的控制组件,采用以下方式代替:
|
||||
HTML 中 `<select>` 通常使用 `<option>` 的 `selected` 属性设置选中状态;React 为了更方便地控制组件,采用以下方式代替:
|
||||
|
||||
```javascript
|
||||
<select value="B">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: working-with-the-browser-it-IT
|
||||
title: Lavorare con il Browser
|
||||
permalink: working-with-the-browser-it-IT.html
|
||||
permalink: docs/working-with-the-browser-it-IT.html
|
||||
prev: forms-it-IT.html
|
||||
next: more-about-refs-it-IT.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: working-with-the-browser
|
||||
title: ブラウザと動くこと
|
||||
permalink: working-with-the-browser-ja-JP.html
|
||||
permalink: docs/working-with-the-browser-ja-JP.html
|
||||
prev: forms-ja-JP.html
|
||||
next: more-about-refs-ja-JP.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: working-with-the-browser-ko-KR
|
||||
title: 브라우저에서의 동작
|
||||
permalink: working-with-the-browser-ko-KR.html
|
||||
permalink: docs/working-with-the-browser-ko-KR.html
|
||||
prev: forms-ko-KR.html
|
||||
next: more-about-refs-ko-KR.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: working-with-the-browser
|
||||
title: Working With the Browser
|
||||
permalink: working-with-the-browser.html
|
||||
permalink: docs/working-with-the-browser.html
|
||||
prev: forms.html
|
||||
next: more-about-refs.html
|
||||
---
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
---
|
||||
id: working-with-the-browser-zh-CN
|
||||
title: 与浏览器协作
|
||||
permalink: working-with-the-browser-zh-CN.html
|
||||
permalink: docs/working-with-the-browser-zh-CN.html
|
||||
prev: forms-zh-CN.html
|
||||
next: more-about-refs-zh-CN.html
|
||||
---
|
||||
|
||||
React提供了强大的抽象机制使你在大多数情况下免于直接接触DOM,但有时你仅仅只需要访问底层API,也许是为了与第三方库或者已有的代码协作。
|
||||
|
||||
## 虚拟DOM
|
||||
## 虚拟 DOM
|
||||
|
||||
React非常快速是因为它从不直接操作DOM。React维持了一个快速的内存中的DOM表示。`render()` 方法实际上返回一个对DOM的*描述*,然后React能根据内存中的“描述”来比较此“描述”以计算出最快速的方法更新浏览器。
|
||||
React非常快速是因为它从不直接操作DOM。React维持了一个快速的内存中的DOM表示。`render()` 方法实际上返回一个对DOM的*描述*,然后React能将其与内存中的“描述”进行比较,以计算出最快速的方式更新浏览器。
|
||||
|
||||
此外,React实现了一个完备的合成事件(synthetic event)系统,以使得所有的事件对象都被保证符合W3C细则,而不论各个浏览器的怪癖,并且所有事件跨浏览器地一致并高效的冒泡(bubbles),你甚至能在IE8里使用一些HTML5事件!
|
||||
此外,React实现了一个完备的合成事件(synthetic event)系统,以使得所有的事件对象都被保证符合W3C细则,而不论各个浏览器的怪癖,并且所有事件跨浏览器地一致并高效的冒泡(bubbles),你甚至能在IE8里使用一些HTML5事件!
|
||||
|
||||
大多数时间你应该和React的"伪造浏览器"呆在一起,因为它更高性能并且容易推理。然而,有时你只需要访问底层API,或许是为了与第三方库比如一个jQuery插件协作。React为你提供了安全仓口来直接使用底层API。
|
||||
大多数时间你应该和React的"伪造浏览器"呆在一起,因为它更高性能并且容易推理。然而,有时你只需要访问底层API,或许是为了与第三方库比如一个jQuery插件协作。React为你提供了安全舱口来直接使用底层API。
|
||||
|
||||
## Refs 和 findDOMNode()
|
||||
|
||||
为了与浏览器互动,你需要一个指向DOM node的引用。你可以连接一个 `ref` 到任何的元素,这允许你引用 组件的 **backing instance** 。它很有用,如果你需要在组件上调用命令式函数,或者想访问底层的DOM节点。要了解很多关于 refs,包括更有效使用他们的方法,请查看我们的 [关于Refs的更多内容](/react/docs/more-about-refs-zh-CN.html) 文档。
|
||||
为了与浏览器互动,你需要一个指向DOM node的引用。你可以连接一个 `ref` 到任何的元素,这允许你引用组件的 **backing instance** 。如果你需要在组件上调用命令式函数,或者想访问底层的DOM节点,它很有用。要了解更多关于 refs,包括更有效使用他们的方法,请查看我们的 [关于Refs的更多内容](/react/docs/more-about-refs-zh-CN.html) 文档。
|
||||
|
||||
## 组件的生命周期
|
||||
|
||||
@@ -32,7 +32,7 @@ React提供生命周期方法,以便你可以指定钩挂到这个过程上。
|
||||
|
||||
### 挂载
|
||||
|
||||
* `getInitialState(): object` 在组件挂载前被调用. 有状态组件(Stateful components) 应该实现此函数并返回初始state的数据。
|
||||
* `getInitialState(): object` 在组件挂载前被调用。有状态组件(Stateful components) 应该实现此函数并返回初始state的数据。
|
||||
* `componentWillMount()` 在挂载发生前被立即调用。
|
||||
* `componentDidMount()` 在挂载发生后被立即调用。 需要DOM node的初始化应该放在这里。
|
||||
|
||||
@@ -45,53 +45,16 @@ React提供生命周期方法,以便你可以指定钩挂到这个过程上。
|
||||
|
||||
### 卸载
|
||||
|
||||
* `componentWillUnmount()` 在组件被卸载和摧毁后被立即调用。清理应该放在这里。
|
||||
* `componentWillUnmount()` 在组件被卸载和摧毁前被立即调用。清理应该放在这里。
|
||||
|
||||
### 已挂载的方法
|
||||
|
||||
_Mounted_ 复合组件同样支持以下方法:
|
||||
|
||||
* `component.forceUpdate()` 可以在任何已挂载的组件上调用,在你知道 某些深处的组件状态被未使用 `this.setState()` 改变了时。
|
||||
* `component.forceUpdate()` 可以在任何已挂载的组件上调用,在你知道某些深处的组件状态在未使用 `this.setState()` 就被改变了时。
|
||||
|
||||
## 浏览器支持和填充物(polyfills)
|
||||
## 浏览器支持
|
||||
|
||||
在 Facebook,我们支持老浏览器,包括IE8。我们由来已久的有适当的填充物(polyfills)来让我们写前瞻性的js。这意味着我们在代码库中没有一堆散落在各处的技巧(hacks)并且我们依然能期望我们的代码"可行(just work)"。例如,我可以只写 `Date.now()`,而不是额外看到`+new Date()`。既然开源的React和我们内部使用的一样,我们也应用了这种使用前瞻性js的哲学。
|
||||
React 支持绝大多数流行的浏览器,包括 Internet Explorer 9 及以上。
|
||||
|
||||
除了这种哲学外,我们也采用了这样的立场,我们,作为一个JS库的作者,不应该把polyfills作为我们库的一部分。如果所有的库这样做,就有很大的机会发送同样的polyfill多次,这可能是一个相当大的无用代码。如果你的产品需要支援老的浏览器,你很有可能已经在使用某些东西比如[es5-shim](https://github.com/es-shims/es5-shim)。
|
||||
|
||||
### 需要用来支持旧浏览器的Polyfills
|
||||
|
||||
来自 [kriskowal's es5-shim](https://github.com/es-shims/es5-shim)的`es5-shim.js` 提供了如下React需要的东西:
|
||||
|
||||
* `Array.isArray`
|
||||
* `Array.prototype.every`
|
||||
* `Array.prototype.forEach`
|
||||
* `Array.prototype.indexOf`
|
||||
* `Array.prototype.map`
|
||||
* `Date.now`
|
||||
* `Function.prototype.bind`
|
||||
* `Object.keys`
|
||||
* `String.prototype.split`
|
||||
* `String.prototype.trim`
|
||||
|
||||
同样来自 [kriskowal's es5-shim](https://github.com/es-shims/es5-shim)的`es5-sham.js`, 提供了如下React需要的东西:
|
||||
|
||||
* `Object.create`
|
||||
* `Object.freeze`
|
||||
|
||||
非最小化的React build需要如下,来自[paulmillr's console-polyfill](https://github.com/paulmillr/console-polyfill).
|
||||
|
||||
* `console.*`
|
||||
|
||||
当在IE8里使用HTML5元素,包括`<section>`, `<article>`, `<nav>`, `<header>`, 和 `<footer>`, 同样必须包含[html5shiv](https://github.com/aFarkas/html5shiv) 或者类似的脚本。
|
||||
|
||||
### 跨浏览器问题
|
||||
|
||||
尽管React在抽象浏览器不同时做的相当好,但一些浏览器被限制或者表现出怪异的行为,我们没能找到变通的方案解决。
|
||||
|
||||
#### IE8的onScroll事件
|
||||
|
||||
在IE8`onScroll` 事件不冒泡,并且IE8没有定义事件捕获阶段handlers的API,意味React这没有办法去监听这些事件。
|
||||
目前这个事件的handler在IE8中是被忽略的。
|
||||
|
||||
参见 [onScroll doesn't work in IE8](https://github.com/facebook/react/issues/631) GitHub问题 来获得更多信息.
|
||||
(我们不支持那些不支持 ES5 methods 的更老的浏览器,但你可能发现如果你的页面包含了类似 [es5-shim and es5-sham](https://github.com/es-shims/es5-shim) 的填充物时是可以在更老的浏览器上运行的。是否做这一步取决于你自己。)
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: more-about-refs-it-IT
|
||||
title: Riferimenti ai Componenti
|
||||
permalink: more-about-refs-it-IT.html
|
||||
permalink: docs/more-about-refs-it-IT.html
|
||||
prev: working-with-the-browser-it-IT.html
|
||||
next: tooling-integration-it-IT.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: more-about-refs
|
||||
title: 参照についての詳細
|
||||
permalink: more-about-refs-ja-JP.html
|
||||
permalink: docs/more-about-refs-ja-JP.html
|
||||
prev: working-with-the-browser-ja-JP.html
|
||||
next: tooling-integration-ja-JP.html
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: more-about-refs-ko-KR
|
||||
title: refs에서 컴포넌트로
|
||||
permalink: more-about-refs-ko-KR.html
|
||||
permalink: docs/more-about-refs-ko-KR.html
|
||||
prev: working-with-the-browser-ko-KR.html
|
||||
next: tooling-integration-ko-KR.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: more-about-refs
|
||||
title: Refs to Components
|
||||
permalink: more-about-refs.html
|
||||
permalink: docs/more-about-refs.html
|
||||
prev: working-with-the-browser.html
|
||||
next: tooling-integration.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: more-about-refs-zh-CN
|
||||
title: 对组件的refs
|
||||
permalink: more-about-refs-zh-CN.html
|
||||
permalink: docs/more-about-refs-zh-CN.html
|
||||
prev: working-with-the-browser-zh-CN.html
|
||||
next: tooling-integration-zh-CN.html
|
||||
---
|
||||
@@ -11,8 +11,7 @@ next: tooling-integration-zh-CN.html
|
||||
|
||||
## 从 ReactDOM.render 返回的 ref
|
||||
|
||||
不要被 你在你的组件(它返回一个虚拟的DOM元素)里定义的 `render()` 迷惑了, [ReactDOM.render()](/react/docs/top-level-api.html#reactdom.render) 会返回一个对你的组件的 **backing instance** 的引用(或者 `null` for [stateless components](/react/docs/reusable-components.html#stateless-functions)).
|
||||
|
||||
不要被你在你的组件(它返回一个虚拟的DOM元素)里定义的 `render()` 迷惑了, [ReactDOM.render()](/react/docs/top-level-api.html#reactdom.render) 会返回一个对你的组件的 **backing instance** 的引用([无状态组件](/react/docs/reusable-components.html#stateless-functions) 返回 `null`).
|
||||
|
||||
```js
|
||||
var myComponent = ReactDOM.render(<MyComponent />, myContainer);
|
||||
@@ -64,7 +63,7 @@ React支持一种非常特殊的属性,你可以附加到任何的组件上。
|
||||
|
||||
当连接一个ref到一个DOM组件如 `<div />`,你取回DOM节点;当连接一个ref到一个复合组件如 `<TextInput />`,你会得到React类的实例。在后一种情况下,你可以调用任何那个组件的类暴露的方法。
|
||||
|
||||
注意当被引用的组件卸载和每当ref变动,旧的ref将会被以`null`做参数调用。这阻止了在实例被保存的情况下的内存泄露,如第一个例子。注意当像在这里的例子,使用内联函数表达式写refs,React在每次更新都看到不同的函数对象,ref将会被以`null` 立即调用在它被以组件实例调用前。
|
||||
注意当被引用的组件卸载和每当ref变动,旧的ref将会被以`null`做参数调用。这阻止了在实例被保存的情况下的内存泄露,如第二个例子。注意当像在这里的例子,使用内联函数表达式写refs,React在每次更新都看到不同的函数对象,ref将会被以`null` 立即调用在它被以组件实例调用前。
|
||||
|
||||
## ref String 属性
|
||||
|
||||
@@ -76,7 +75,7 @@ React同样支持使用一个字符串(代替回调函数)在任意组件上
|
||||
<input ref="myInput" />
|
||||
```
|
||||
|
||||
2. 在其他一些代码中(典型的事件处理代码),通过`this.refs`访问 **支持实例(backing instance)**,如:
|
||||
2. 在其他一些代码中(典型的如事件处理的代码),通过`this.refs`访问 **支持实例(backing instance)**,如:
|
||||
|
||||
```javascript
|
||||
var input = this.refs.myInput;
|
||||
@@ -85,6 +84,7 @@ React同样支持使用一个字符串(代替回调函数)在任意组件上
|
||||
```
|
||||
|
||||
## 完整的示例
|
||||
|
||||
为了获取一个React组件的引用,你既可以使用 `this` 来获取当前的React组件,也可以使用一个 ref 来获取一个你拥有的组件的引用。他们像这样工作:
|
||||
|
||||
```javascript
|
||||
@@ -121,7 +121,7 @@ ReactDOM.render(
|
||||
|
||||
## 总结
|
||||
|
||||
Refs是一种很好的发送消息给特定子实例(通过流式的Reactive `props` 和 `state`来做会不方便)的方式。它们应该,不论怎样,不是你数据流通你的应用的首选。默认情况下,使用响应式数据流,并为本身不是reactive的用例保存`ref`s。
|
||||
Refs是一种很好的发送消息给特定子实例(通过流式的Reactive `props` 和 `state`来做会不方便)的方式。它们应该,不论怎样,不是你的应用中数据流通的首选。默认情况下,使用响应式数据流,并为本身不是reactive的用例保存`ref`。
|
||||
|
||||
### 优点:
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: tooling-integration-it-IT
|
||||
title: Integrazione con Strumenti
|
||||
permalink: tooling-integration-it-IT.html
|
||||
permalink: docs/tooling-integration-it-IT.html
|
||||
prev: more-about-refs-it-IT.html
|
||||
next: addons-it-IT.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: tooling-integration
|
||||
title: インテグレーションツール
|
||||
permalink: tooling-integration-ja-JP.html
|
||||
permalink: docs/tooling-integration-ja-JP.html
|
||||
prev: more-about-refs-ja-JP.html
|
||||
next: addons-ja-JP.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: tooling-integration-ko-KR
|
||||
title: 툴 통합
|
||||
permalink: tooling-integration-ko-KR.html
|
||||
permalink: docs/tooling-integration-ko-KR.html
|
||||
prev: more-about-refs-ko-KR.html
|
||||
next: addons-ko-KR.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: tooling-integration
|
||||
title: Tooling Integration
|
||||
permalink: tooling-integration.html
|
||||
permalink: docs/tooling-integration.html
|
||||
prev: more-about-refs.html
|
||||
next: language-tooling.html
|
||||
---
|
||||
|
||||
@@ -1,80 +1,13 @@
|
||||
---
|
||||
id: tooling-integration-zh-CN
|
||||
title: 工具集成
|
||||
permalink: tooling-integration-zh-CN.html
|
||||
permalink: docs/tooling-integration-zh-CN.html
|
||||
prev: more-about-refs-zh-CN.html
|
||||
next: addons-zh-CN.html
|
||||
---
|
||||
|
||||
每个项目使用一个不同的系统来建立和部署JavaScript.我们努力使React尽可能环境无关。
|
||||
我们尽可能使 React 与环境无关。大家可以在各种语言(JavaScript, TypeScript, ClojureScript, etc)与各种环境(web, iOS, Android, NodeJS, Nashorn, etc)中使用 React。这里有很多工具来帮助你创建优秀的应用。在这一节中我们介绍一些在 React 中最流行的工具。
|
||||
|
||||
## React
|
||||
|
||||
### CDN-hosted React
|
||||
|
||||
我们提供了CDN-hosted版本的React[在我们的下载页面](/react/downloads.html).这些预构建的文件使用UMD模块格式。将他们放进一个简单的`<script>` 标签将会注入一个`React` 全局变量到你的环境里。这也同样在CommonJS 和 AMD 环境里开箱即用。
|
||||
|
||||
### 使用 master
|
||||
|
||||
我们[在我们的 GitHub repository](https://github.com/facebook/react)有从`master`构建的说明。我们在`build/modules` 下构建了一个CommonJS模块的树,你可以把它放到任何支持CommonJS的环境或者打包工具里。
|
||||
|
||||
## JSX
|
||||
|
||||
### 浏览器中的JSX转化
|
||||
|
||||
如果你喜欢使用JSX,Babel5 提供了被称为browser.js 用于开发的一个浏览器内的 ES6 和 JSX 转换器,它可以从 [CDNJS](http://cdnjs.com/libraries/babel-core/5.8.34) 引用。Include `<script type="text/babel">` 标记来使用 JSX 转换器.
|
||||
|
||||
> 注意:
|
||||
>
|
||||
> 浏览器中的JSX转换器相当大并且导致额外的本可避免的客户端计算。不要在生产环境中使用 - 见下一节。
|
||||
|
||||
### 投入生产: 预编译 JSX
|
||||
|
||||
如果你有[npm](https://www.npmjs.com/),你可以运行 `npm install -g babel-cli`. Babel 对React v0.12+ 有内建支持。 标签被自动转化为它们的等价物`React.createElement(...)`, `displayName` 被自动推断并添加到所有的React.createClass 调用。
|
||||
|
||||
这个工具会把使用JSX语法的文件转化为简单的可直接在浏览器运行的JavaScript文件。它同样将为你监视目录并自动转化文件当他们变动时;例如:`babel --watch src/ --out-dir lib/`.
|
||||
|
||||
从 Babel 6 开始,默认不再包含转换。这意味这必须在运行 `babel` 命令时指定选项,或者 `.babelrc` 必须指定选项。附加的捆绑了一大批转化的包(presets)也同样需要被安装.协同React工作最常用的是 `es2015` 和 `react` presets.更多关于 Babel 变化的信息可以在 [Babel 6 博客发布的信息](http://babeljs.io/blog/2015/10/29/6.0.0/)上找到.
|
||||
|
||||
这里是一个要使用ES2015 语法和 React 你该怎样做的例子:
|
||||
|
||||
```
|
||||
npm install babel-preset-es2015 babel-preset-react
|
||||
babel --presets es2015,react --watch src/ --out-dir lib/
|
||||
```
|
||||
|
||||
默认模式下带有`.js`后缀的JSX文件被转化。运行 `babel --help` 获取更多关于如何使用 Babel 的信息。
|
||||
|
||||
输出的例子:
|
||||
|
||||
```
|
||||
$ cat test.jsx
|
||||
var HelloMessage = React.createClass({
|
||||
render: function() {
|
||||
return <div>Hello {this.props.name}</div>;
|
||||
}
|
||||
});
|
||||
|
||||
ReactDOM.render(<HelloMessage name="John" />, mountNode);
|
||||
$ babel test.jsx
|
||||
"use strict";
|
||||
|
||||
var HelloMessage = React.createClass({
|
||||
displayName: "HelloMessage",
|
||||
|
||||
render: function render() {
|
||||
return React.createElement(
|
||||
"div",
|
||||
null,
|
||||
"Hello ",
|
||||
this.props.name
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
ReactDOM.render(React.createElement(HelloMessage, { name: "John" }), mountNode);
|
||||
```
|
||||
|
||||
### 有帮助的开源项目
|
||||
|
||||
开源社区已经创建了一些集成JSX到数个编辑器和构建系统的工具。全部列表请见[JSX integrations](https://github.com/facebook/react/wiki/Complementary-Tools#jsx-integrations) 。
|
||||
* [语言工具](/react/docs/language-tooling.html) 描述如何设置例如 Babel 的工具来编译 JSX。
|
||||
* [包管理](/react/docs/package-management.html) 讲述如何设置将 React 配置为项目中的依赖。
|
||||
* [服务端环境](/react/docs/environments.html) 讲述如何为 React 配置服务端渲染环境。
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: language-tooling
|
||||
title: Language Tooling
|
||||
permalink: language-tooling.html
|
||||
permalink: docs/language-tooling.html
|
||||
prev: tooling-integration.html
|
||||
next: package-management.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: package-management
|
||||
title: Package Management
|
||||
permalink: package-management.html
|
||||
permalink: docs/package-management.html
|
||||
prev: language-tooling.html
|
||||
next: environments.html
|
||||
---
|
||||
@@ -105,7 +105,7 @@ bower install --save react
|
||||
<title>Hello React!</title>
|
||||
<script src="bower_components/react/react.js"></script>
|
||||
<script src="bower_components/react/react-dom.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
|
||||
<script src="https://npmcdn.com/babel-core@5.8.38/browser.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="example"></div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: environments
|
||||
title: Server-side Environments
|
||||
permalink: environments.html
|
||||
permalink: docs/environments.html
|
||||
prev: package-management.html
|
||||
next: addons.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: addons-it-IT
|
||||
title: Add-ons
|
||||
permalink: addons-it-IT.html
|
||||
permalink: docs/addons-it-IT.html
|
||||
prev: tooling-integration-it-IT.html
|
||||
next: animation-it-IT.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: addons
|
||||
title: アドオン
|
||||
permalink: addons-ja-JP.html
|
||||
permalink: docs/addons-ja-JP.html
|
||||
prev: tooling-integration-ja-JP.html
|
||||
next: animation-ja-JP.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: addons-ko-KR
|
||||
title: 애드온
|
||||
permalink: addons-ko-KR.html
|
||||
permalink: docs/addons-ko-KR.html
|
||||
prev: tooling-integration-ko-KR.html
|
||||
next: animation-ko-KR.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: addons
|
||||
title: Add-ons
|
||||
permalink: addons.html
|
||||
permalink: docs/addons.html
|
||||
prev: environments.html
|
||||
next: animation.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: addons-zh-CN
|
||||
title: 插件
|
||||
permalink: addons-zh-CN.html
|
||||
permalink: docs/addons-zh-CN.html
|
||||
prev: tooling-integration-zh-CN.html
|
||||
next: animation-zh-CN.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: animation-it-IT
|
||||
title: Animazioni
|
||||
permalink: animation-it-IT.html
|
||||
permalink: docs/animation-it-IT.html
|
||||
prev: addons-it-IT.html
|
||||
next: two-way-binding-helpers-it-IT.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: animation
|
||||
title: アニメーション
|
||||
permalink: animation-ja-JP.html
|
||||
permalink: docs/animation-ja-JP.html
|
||||
prev: addons-ja-JP.html
|
||||
next: two-way-binding-helpers-ja-JP.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: animation-ko-KR
|
||||
title: 애니메이션
|
||||
permalink: animation-ko-KR.html
|
||||
permalink: docs/animation-ko-KR.html
|
||||
prev: addons-ko-KR.html
|
||||
next: two-way-binding-helpers-ko-KR.html
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: animation
|
||||
title: Animation
|
||||
permalink: animation.html
|
||||
permalink: docs/animation.html
|
||||
prev: addons.html
|
||||
next: two-way-binding-helpers.html
|
||||
---
|
||||
|
||||
Loaded 100 of 294 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user