diff --git a/.gitignore b/.gitignore index 319bab66cafa4..21728725b2f00 100644 --- a/.gitignore +++ b/.gitignore @@ -15,7 +15,7 @@ docs/code docs/_site docs/.sass-cache docs/js/* -docs/downloads +docs/downloads/*.zip docs/vendor/bundle examples/shared/*.js examples/**/bundle.js diff --git a/.travis.yml b/.travis.yml index e2271f6e5d68e..49223f8f34300 100644 --- a/.travis.yml +++ b/.travis.yml @@ -23,7 +23,11 @@ before_install: script: - | if [ "$TEST_TYPE" = build_website ]; then - if [ "$TRAVIS_BRANCH" = "$REACT_WEBSITE_BRANCH" ] && [ "$TRAVIS_PULL_REQUEST" = false ]; then + if [ "$TRAVIS_PULL_REQUEST" = false ]; then + if [ "$TRAVIS_BRANCH" != new-docs ]; then + echo "This code should only run on the new-docs branch. Please revert it." + exit 1 + fi set -e GH_PAGES_DIR="$TRAVIS_BUILD_DIR"/../react-gh-pages @@ -42,7 +46,7 @@ script: if ! git diff-index --quiet HEAD --; then git add -A . git commit -m "Rebuild website" - git push origin gh-pages + git push -f https://reactjs-bot@github.com/reactjs-bot/react.git gh-pages fi popd fi diff --git a/docs/README.md b/docs/README.md index 1b36319b33730..6517ab8bb47da 100644 --- a/docs/README.md +++ b/docs/README.md @@ -38,7 +38,7 @@ $ cd react/docs $ bundle exec rake $ bundle exec rake fetch_remotes $ bundle exec jekyll serve -w -$ open http://localhost:4000/react/ +$ open http://localhost:4000/react/index.html ``` We use [SASS](http://sass-lang.com/) (with [Bourbon](http://bourbon.io/)) for our CSS, and we use JSX to transform some of our JS. diff --git a/docs/_config.yml b/docs/_config.yml index 53fa1d01e8343..d84d29cbd994c 100644 --- a/docs/_config.yml +++ b/docs/_config.yml @@ -20,6 +20,12 @@ defaults: type: pages values: sectionid: blog +- scope: + path: tutorial + type: pages + values: + layout: tutorial + sectionid: tutorial - scope: path: docs type: pages @@ -27,15 +33,16 @@ defaults: layout: docs sectionid: docs - scope: - path: tips + path: contributing type: pages values: sectionid: docs - scope: - path: contributing + path: community type: pages values: - sectionid: docs + layout: community + sectionid: community exclude: - Gemfile - Gemfile.lock diff --git a/docs/_data/nav_community.yml b/docs/_data/nav_community.yml new file mode 100644 index 0000000000000..3740d3af7e89b --- /dev/null +++ b/docs/_data/nav_community.yml @@ -0,0 +1,14 @@ +- title: Community Resources + items: + - id: support + title: Where To Get Support + - id: conferences + title: Conferences + - id: videos + title: Videos + - id: complementary-tools + title: Complementary Tools + href: https://github.com/facebook/react/wiki/Complementary-Tools + - id: examples + title: Examples + href: https://github.com/facebook/react/wiki/Examples diff --git a/docs/_data/nav_docs.yml b/docs/_data/nav_docs.yml index e8f6b69132b35..1be1ce3c07db4 100644 --- a/docs/_data/nav_docs.yml +++ b/docs/_data/nav_docs.yml @@ -1,104 +1,83 @@ - title: Quick Start items: - - id: getting-started - title: Getting Started - - id: tutorial - title: Tutorial - - id: thinking-in-react - title: Thinking in React -- title: Community Resources + - id: installation + title: Installation + - id: hello-world + title: Hello World + - id: introducing-jsx + title: Introducing JSX + - id: rendering-elements + title: Rendering Elements + - id: components-and-props + title: Components and Props + - id: state-and-lifecycle + title: State and Lifecycle + - id: handling-events + title: Handling Events + - id: conditional-rendering + title: Conditional Rendering + - id: lists-and-keys + title: Lists and Keys + - id: forms + title: Forms + - id: lifting-state-up + title: Lifting State Up + - id: composition-vs-inheritance + title: Composition vs Inheritance + - id: thinking-in-react + title: Thinking In React +- title: Advanced Guides items: - - id: conferences - title: Conferences - - id: videos - title: Videos - - id: complementary-tools - title: Complementary Tools - href: https://github.com/facebook/react/wiki/Complementary-Tools - - id: examples - title: Examples - href: https://github.com/facebook/react/wiki/Examples -- title: Guides - items: - - id: why-react - title: Why React? - - id: displaying-data - title: Displaying Data - subitems: - id: jsx-in-depth - title: JSX in Depth - - id: jsx-spread - title: JSX Spread Attributes - - id: jsx-gotchas - title: JSX Gotchas - - id: interactivity-and-dynamic-uis - title: Interactivity and Dynamic UIs - - id: multiple-components - title: Multiple Components - - id: reusable-components - title: Reusable Components - - id: transferring-props - title: Transferring Props - - id: forms - title: Forms - - id: working-with-the-browser - title: Working With the Browser - subitems: - - id: more-about-refs - title: Refs to Components - - id: tooling-integration - title: Tooling Integration - subitems: - - id: language-tooling - title: Language Tooling - - id: package-management - title: Package Management - - id: environments - title: Server-side Environments - - id: addons - title: Add-Ons - subitems: - - id: animation - title: Animation - - id: two-way-binding-helpers - title: Two-Way Binding Helpers - - id: test-utils - title: Test Utilities - - id: clone-with-props - title: Cloning Elements - - id: create-fragment - title: Keyed Fragments - - id: update - title: Immutability Helpers - - id: pure-render-mixin - title: PureRenderMixin - - id: perf - title: Performance Tools - - id: shallow-compare - title: Shallow Compare - - id: advanced-performance - title: Advanced Performance - - id: context - title: Context + title: JSX In Depth + - id: typechecking-with-proptypes + title: Typechecking With PropTypes + - id: refs-and-the-dom + title: Refs and the DOM + - id: optimizing-performance + title: Optimizing Performance + - id: react-without-es6 + title: React Without ES6 + - id: react-without-jsx + title: React Without JSX + - id: reconciliation + title: Reconciliation + - id: context + title: Context + - id: web-components + title: Web Components - title: Reference items: - - id: top-level-api - title: Top-Level API - - id: component-api - title: Component API - - id: component-specs - title: Component Specs and Lifecycle - - id: tags-and-attributes - title: Supported Tags and Attributes - - id: events - title: Event System - - id: dom-differences - title: DOM Differences - - id: special-non-dom-attributes - title: Special Non-DOM Attributes - - id: reconciliation - title: Reconciliation - - id: webcomponents - title: Web Components - - id: glossary - title: React (Virtual) DOM Terminology + - id: react-api + title: React + subitems: + - id: react-component + title: React.Component + - id: react-dom + title: ReactDOM + - id: react-dom-server + title: ReactDOMServer + - id: dom-elements + title: DOM Elements + - id: events + title: SyntheticEvent + - id: addons + title: Add-Ons + subitems: + - id: perf + title: Performance Tools + - id: test-utils + title: Test Utilities + - id: animation + title: Animation + - id: create-fragment + title: Keyed Fragments + - id: update + title: Immutability Helpers + - id: pure-render-mixin + title: PureRenderMixin + - id: shallow-compare + title: Shallow Compare + - id: two-way-binding-helpers + title: Two-way Binding Helpers + diff --git a/docs/_data/nav_tips.yml b/docs/_data/nav_tips.yml deleted file mode 100644 index f568311444bdd..0000000000000 --- a/docs/_data/nav_tips.yml +++ /dev/null @@ -1,38 +0,0 @@ -- title: Tips - items: - - id: introduction - title: Introduction - - id: inline-styles - title: Inline Styles - - id: if-else-in-JSX - title: If-Else in JSX - - id: self-closing-tag - title: Self-Closing Tag - - id: maximum-number-of-jsx-root-nodes - title: Maximum Number of JSX Root Nodes - - id: style-props-value-px - title: Shorthand for Specifying Pixel Values in style props - - id: children-props-type - title: Type of the Children props - - id: controlled-input-null-value - title: Value of null for Controlled Input - - id: componentWillReceiveProps-not-triggered-after-mounting - title: componentWillReceiveProps Not Triggered After Mounting - - id: props-in-getInitialState-as-anti-pattern - title: Props in getInitialState Is an Anti-Pattern - - id: dom-event-listeners - title: DOM Event Listeners in a Component - - id: initial-ajax - title: Load Initial Data via AJAX - - id: false-in-jsx - title: False in JSX - - id: communicate-between-components - title: Communicate Between Components - - id: expose-component-functions - title: Expose Component Functions - - id: children-undefined - title: this.props.children undefined - - id: use-react-with-other-libraries - title: Use React with Other Libraries - - id: dangerously-set-inner-html - title: Dangerously Set innerHTML diff --git a/docs/_data/nav_tutorial.yml b/docs/_data/nav_tutorial.yml new file mode 100644 index 0000000000000..efa090f0cecb1 --- /dev/null +++ b/docs/_data/nav_tutorial.yml @@ -0,0 +1,71 @@ +- title: Tutorial + items: + - id: tutorial + title: Overview + subitems: + - id: what-were-building + title: What We're Building + href: /react/tutorial/tutorial.html#what-were-building + forceInternal: true + - id: what-is-react + title: What is React? + href: /react/tutorial/tutorial.html#what-is-react + forceInternal: true + - id: getting-started + title: Getting Started + href: /react/tutorial/tutorial.html#getting-started + forceInternal: true + - id: passing-data-through-props + title: Passing Data Through Props + href: /react/tutorial/tutorial.html#passing-data-through-props + forceInternal: true + - id: an-interactive-component + title: An Interactive Component + href: /react/tutorial/tutorial.html#an-interactive-component + forceInternal: true + - id: developer-tools + title: Developer Tools + href: /react/tutorial/tutorial.html#developer-tools + forceInternal: true + - id: lifting-state-up + title: Lifting State Up + href: /react/tutorial/tutorial.html#lifting-state-up + forceInternal: true + subitems: + - id: why-immutability-is-important + title: Why Immutability Is Important + href: /react/tutorial/tutorial.html#why-immutability-is-important + forceInternal: true + - id: functional-components + title: Functional Components + href: /react/tutorial/tutorial.html#functional-components + forceInternal: true + - id: taking-turns + title: Taking Turns + href: /react/tutorial/tutorial.html#taking-turns + forceInternal: true + - id: declaring-a-winner + title: Declaring a Winner + href: /react/tutorial/tutorial.html#declaring-a-winner + forceInternal: true + - id: storing-a-history + title: Storing A History + href: /react/tutorial/tutorial.html#storing-a-history + forceInternal: true + subitems: + - id: showing-the-moves + title: Showing the Moves + href: /react/tutorial/tutorial.html#showing-the-moves + forceInternal: true + - id: keys + title: Keys + href: /react/tutorial/tutorial.html#keys + forceInternal: true + - id: implementing-time-travel + title: Implementing Time Travel + href: /react/tutorial/tutorial.html#implementing-time-travel + forceInternal: true + - id: wrapping-up + title: Wrapping Up + href: /react/tutorial/tutorial.html#wrapping-up + forceInternal: true diff --git a/docs/_includes/footer.html b/docs/_includes/footer.html new file mode 100644 index 0000000000000..e2e6fdb65861c --- /dev/null +++ b/docs/_includes/footer.html @@ -0,0 +1,41 @@ + diff --git a/docs/_includes/hero.html b/docs/_includes/hero.html new file mode 100644 index 0000000000000..10530a7060dde --- /dev/null +++ b/docs/_includes/hero.html @@ -0,0 +1,13 @@ +
+
+
React
+
+ A JavaScript library for building user interfaces +
+ + +
+
diff --git a/docs/_includes/nav_community.html b/docs/_includes/nav_community.html new file mode 100644 index 0000000000000..7b26b8df93e78 --- /dev/null +++ b/docs/_includes/nav_community.html @@ -0,0 +1,24 @@ + diff --git a/docs/_includes/nav_docs.html b/docs/_includes/nav_docs.html index 560170606d8d6..be10a9c51319d 100644 --- a/docs/_includes/nav_docs.html +++ b/docs/_includes/nav_docs.html @@ -6,12 +6,12 @@

{{ section.title }}

{% endfor %} + diff --git a/docs/_includes/nav_tutorial.html b/docs/_includes/nav_tutorial.html new file mode 100644 index 0000000000000..2a720cbdd0bd7 --- /dev/null +++ b/docs/_includes/nav_tutorial.html @@ -0,0 +1,24 @@ + diff --git a/docs/_includes/navigation.html b/docs/_includes/navigation.html new file mode 100644 index 0000000000000..4632047aec8fe --- /dev/null +++ b/docs/_includes/navigation.html @@ -0,0 +1,23 @@ + diff --git a/docs/_layouts/community.html b/docs/_layouts/community.html new file mode 100644 index 0000000000000..9fda4ceb60c45 --- /dev/null +++ b/docs/_layouts/community.html @@ -0,0 +1,29 @@ +--- +layout: default +sectionid: community +--- + +
+
+ Edit on GitHub +

+ {{ page.title }} +

+
{{ page.description }}
+ + {{ content }} + +
+ {% if page.prev %} + ← Prev + {% endif %} + {% if page.next %} + Next → + {% endif %} +
+
+ + {% include nav_community.html %} +
diff --git a/docs/_layouts/contributing.html b/docs/_layouts/contributing.html index fc5bfbadae2ec..7d04c66a6a744 100644 --- a/docs/_layouts/contributing.html +++ b/docs/_layouts/contributing.html @@ -4,8 +4,6 @@ ---
- {% include nav_docs.html %} -

{{ page.title }}

{{ page.description }}
@@ -20,4 +18,6 @@

{{ page.title }}

{% endif %}
+ + {% include nav_docs.html %}
diff --git a/docs/_layouts/default.html b/docs/_layouts/default.html index a3a44a53aa663..2516518d61030 100644 --- a/docs/_layouts/default.html +++ b/docs/_layouts/default.html @@ -1,16 +1,26 @@ +{% if page.excerpt %} +{% assign type = 'article' %} +{% assign sectionTitle = 'React Blog' %} +{% assign description = page.excerpt | remove: '

' | remove: '

' %} +{% else %} +{% assign type = 'website' %} +{% assign sectionTitle = 'React' %} +{% assign description = 'A JavaScript library for building user interfaces' %} +{% endif %} +{% assign title = page.title | append: ' - ' | append: sectionTitle %} - {{ page.title }} | React - - - + {{ title }} + + + - + @@ -43,60 +53,14 @@
- - - {% if page.id == 'home' %} -
-
-
React
-
- A JavaScript library for building user interfaces -
- - -
-
- {% endif %} + {% include navigation.html %} {{ content }} - + {% include footer.html %}
-
+
- - - - -
- - - -``` - -Nel resto della documentazione, ci concentreremo soltanto sul codice JavaScript e assumeremo che sia inserito in un modello come quello qui sopra. Sostituisci il commento segnaposto qui sopra con il seguente codice JSX: - -```javascript -var HelloWorld = React.createClass({ - render: function() { - return ( -

- Ciao, ! - È il {this.props.date.toTimeString()} -

- ); - } -}); - -setInterval(function() { - ReactDOM.render( - , - document.getElementById('example') - ); -}, 500); -``` - - -## Aggiornamenti Reattivi - -Apri `hello-react.html` in un browser web e scrivi il tuo nome nel campo di testo. Osserva che React cambia soltanto la stringa di testo dell'ora nella UI — ogni input che inserisci nel campo di testo rimane, anche se non hai scritto alcun codice che gestisce questo comportamento. React lo capisce da solo al tuo posto e fa la cosa giusta. - -La maniera in cui siamo in grado di capirlo è che React non manipola il DOM a meno che non sia necessario. **Utilizza un DOM interno fittizio e veloce per effettuare confronti ed effettuare le mutazioni del DOM più efficienti al tuo posto.** - -Gli input di questo componente sono chiamati `props` — breve per "properties". Sono passati come attributi nella sintassi JSX. Puoi pensare ad essi come immutabili nel contesto del componente, ovvero, **non assegnare mai `this.props`**. - - -## I Componenti Sono Come Funzioni - -I componenti React sono molto semplici. Puoi immaginarli come semplici funzioni che ricevono in ingresso `props` e `state` (discusso in seguito) e rendono HTML. Fatta questa premessa, i componenti sono molto semplici da descrivere. - -> Nota: -> -> **Una limitazione**: i componenti React possono rendere soltanto un singolo nodo radice. Se desideri restituire nodi multipli, essi *devono* essere avvolti in un singolo nodo radice. - - -## Sintassi JSX - -Crediamo fermamente che i componenti sono la maniera corretta di separare i concetti anziché i "modelli" e la "logica di presentazione." Pensiamo che il markup e il codice che lo genera siano intimamente collegati. Inoltre, la logica di presentazione è solitamente molto complessa e usare un linguaggio di modello per esprimerla risulta dispendioso. - -Abbiamo scoperto che la migliore soluzione a questo problema è generare HTML e un albero di componenti direttamente dal codice JavaScript in maniera da poter utilizzare tutta la potenza espressiva di un vero linguaggio di programmazione per costruire UI. - -Per rendere il compito più facile, abbiamo aggiunto una semplice e **opzionale** sintassi simile all'HTML per creare questi nodi di albero React. - -**JSX ti permette di creare oggetti JavaScript usando una sintassi HTML.** Per generare un collegamento in React usando puro JavaScript puoi scrivere: - -`React.createElement('a', {href: 'https://facebook.github.io/react/'}, 'Ciao!')` - -Con JSX ciò diventa: - -`Ciao!` - -Abbiamo scoperto che questo ha reso la costruzione di applicazioni React più semplice e i designer tendono a preferire la sintassi, ma ciascuno ha un diverso flusso di lavoro, quindi **JSX non è richiesto per utilizzare React.** - -JSX è di dimensioni contenute. Per maggiori informazioni, consulta [JSX in profondità](/react/docs/jsx-in-depth-it-IT.html). Oppure osserva la trasformazione in tempo reale sulla [REPL di Babel](https://babeljs.io/repl/). - -JSX è simile all'HTML, ma non proprio identico. Consulta la guida [JSX gotchas](/react/docs/jsx-gotchas-it-IT.html) per alcune differenze fondamentali. - -[Babel offre una varietà di strumenti per cominciare a usare JSX](http://babeljs.io/docs/setup/), dagli strumenti a riga di comando alle integrazioni in Ruby on Rails. Scegli lo strumento che funziona meglio per te. - - -## React senza JSX - -JSX è completamente opzionale; non è necessario utilizzare JSX con React. Puoi creare elementi React in puro JavaScript usando `React.createElement`, che richiede un nome di tag o di componente, un oggetto di proprietà e un numero variabile di argomenti che rappresentano nodi figli opzionali. - -```javascript -var child1 = React.createElement('li', null, 'Primo Contenuto di Testo'); -var child2 = React.createElement('li', null, 'Secondo Contenuto di Testo'); -var root = React.createElement('ul', { className: 'my-list' }, child1, child2); -ReactDOM.render(root, document.getElementById('example')); -``` - -Per comodità, puoi creare funzioni factory scorciatoia per costruire elementi da componenti personalizzati. - -```javascript -var Factory = React.createFactory(ComponentClass); -... -var root = Factory({ custom: 'prop' }); -ReactDOM.render(root, document.getElementById('example')); -``` - -React possiede già delle factory predefinite per i tag HTML comuni: - -```javascript -var root = React.DOM.ul({ className: 'my-list' }, - React.DOM.li(null, 'Contenuto di Testo') - ); -``` diff --git a/docs/docs/02-displaying-data.ja-JP.md b/docs/docs/02-displaying-data.ja-JP.md deleted file mode 100644 index 174d3e0a1a249..0000000000000 --- a/docs/docs/02-displaying-data.ja-JP.md +++ /dev/null @@ -1,125 +0,0 @@ ---- -id: displaying-data-ja-JP -title: データを表示する -permalink: docs/displaying-data-ja-JP.html -prev: why-react-ja-JP.html -next: jsx-in-depth-ja-JP.html - ---- - -UIについて、最も基本的なことは、いくつかのデータを表示することです。Reactはデータを表示し、変更された時にはインターフェースを最新の状態に自動的に保つことが簡単にできるようになっています。 - -## はじめに - -本当に単純な例を見てみましょう。`hello-react.html` ファイルを以下のようなコードで作成してください。 - -```html - - - - - Hello React - - - - - -
- - - -``` - -このドキュメントの中では、JavaScriptのコードにのみフォーカスします。そして、それが上のようなテンプレートに挿入されていると考えます。 - -```javascript -var HelloWorld = React.createClass({ - render: function() { - return ( -

- Hello, ! - It is {this.props.date.toTimeString()} -

- ); - } -}); - -setInterval(function() { - ReactDOM.render( - , - document.getElementById('example') - ); -}, 500); -``` - - -## リアクティブなアップデート - -`hello-react.html` をウェブブラウザで開き、テキストフィールドにあなたの名前を入力してください。ReactはUIのうち、時間の文字列しか変更しないことに注意してください。あなたがテキストフィールドに入力したものは残っています。あなたはそういったコードを書いていないのにも関わらずです。Reactはあなたのことを理解しており、正しいことを行います。 - -このことについて私たちが理解できる方法は、Reactは必要になるまで、DOMの操作を行わないということです。 **Reactは、DOMの変化を表現し、あなたにもっとも効率的なDOMの変化を見積もるために早い、内部のモックのDOMを使っています。** - -このコンポーネントのインプットは `props` と呼ばれるものです。"properties" の省略形です。それらはJSXシンタックスの中でアトリビュートとして渡されます。それらはコンポーネントの中で不変と考えるべきで、 **`this.props` には書き込まないようにしてください** - -## コンポーネントは関数のようなものです。 - -Reactのコンポーネントはとても単純です。それらは `props` や `state` (後述します)を取り、HTMLをレンダリングする単純な関数だと考えることができます。この考えの元、コンポーネントは簡単に理解することができます。 - -> 注意: -> -> **1つの制限**: Reactのコンポーネントは単一の最上位のノードだけをレンダリングします。複数のノードをリターンしたい場合は、単一の最上位のもので *ラップする必要があります* 。 - -## JSXシンタックス - -私たちは関心を分離する正しい方法は「テンプレート」と「ディスプレイロジック」ではなくコンポーネントであると強く考えています。ビューを生成するマークアップとコードは密接につながっていると考えています。加えて、ディスプレイロジックはとても複雑になりえますし、ビューを表現するのにテンプレート言語を使うことはとてもややこしくなりえます。 - -私たちは、この問題の最適解は、UIを構築するのにリアルなプログラミング言語の表現力の全てを使うことができるように、JavaScriptのコードからHTMLやコンポーネントのツリーを直接生成することだと発見しました。 - -上記のことを簡単に行うために、私たちはReactのツリーノードを構築するためのとても単純で、 **オプショナルな** HTMLに似たシンタックスを加えました。 - -**JSXはHTMLのシンタックスを使ってJavaScriptのオブジェクトを構築するのを可能にします。** 純粋にJavaScriptを使ってReactでリンクを構築するには、以下のように書きます。 - -`React.createElement('a', {href: 'https://facebook.github.io/react/'}, 'Hello!')` - -JSXでは、以下のように変換されます。 - -`Hello!` - -以上のようなことで、Reactのアプリを作成するのは簡単になりましたし、デザイナーはこのシンタックスを好むようになると発見しました。しかし、人は自分自身のワークフローを持っているものです。 **JSXはReactを使う際に必ずしも必要ではありません。** - -JSXはとても小さいです。さらに学ぶためには、[JSXの深層](/react/docs/jsx-in-depth-ja-JP.html)を参照ください。または、[ライブJSXコンパイラー](/react/jsx-compiler.html)で変換の動作を確認してください。 - -JSXはHTMLに似ていますが、正確に同じではありません。いくつかのキーの違いについては[JSXの理解](/react/docs/jsx-gotchas.html) をご覧ください。 - -JSXを初めて使う際に最も簡単なのは、ブラウザで `JSXTransformer` を使う方法です。これはプロダクションでは使わないことを強くお勧めします。コードは、コマンドラインの[react-tools](https://www.npmjs.com/package/react-tools)パッケージを使うことでプリコンパイルできます。 - -## JSXを使わないReact - -JSXは完全にオプションです。Reactと一緒にJSXを使う必要はありません。`React.createElement` を使って、ただのJavaScriptでReactの要素を作ることもできます。それは、タグの名前やコンポーネント、プロパティのオブジェクト、いくつかのオプションの子要素をとります。 - -```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')); -``` -便利に書くために、カスタムコンポーネントで要素を作るために簡略した記法でファクトリー関数を作ることができます。 - -```javascript -var Factory = React.createFactory(ComponentClass); -... -var root = Factory({ custom: 'prop' }); -ReactDOM.render(root, document.getElementById('example')); -``` - -Reactはすでに、共通なHTMLのタグについてはビルトインの関数を持っています。 - -```javascript -var root = React.DOM.ul({ className: 'my-list' }, - React.DOM.li(null, 'Text Content') - ); -``` diff --git a/docs/docs/02-displaying-data.ko-KR.md b/docs/docs/02-displaying-data.ko-KR.md deleted file mode 100644 index 1a9f3738b804a..0000000000000 --- a/docs/docs/02-displaying-data.ko-KR.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -id: displaying-data-ko-KR -title: 데이터를 표시하기 -permalink: docs/displaying-data-ko-KR.html -prev: why-react-ko-KR.html -next: jsx-in-depth-ko-KR.html ---- - -UI를 가지고 할 수 있는 가장 기초적인 것은 데이터를 표시하는 것입니다. React는 데이터를 표시하고 데이터가 변할 때마다 인터페이스를 최신의 상태로 자동으로 유지하기 쉽게 해 줍니다. - -## 시작하기 - -정말 간단한 예제를 보도록 하죠. 다음과 같은 코드의 `hello-react.html` 파일을 만듭시다. - -```html - - - - - Hello React - - - - - -
- - - -``` - -문서의 나머지에서, 코드가 위와 같은 HTML 템플릿에 들어갔다고 가정하고 JavaScript 코드에만 집중할 것입니다. 위의 주석 부분을 다음과 같은 JSX 코드로 바꿔 보세요: - -```javascript -var HelloWorld = React.createClass({ - render: function() { - return ( -

- 안녕, ! - 지금 시간은 {this.props.date.toTimeString()} 입니다. -

- ); - } -}); - -setInterval(function() { - ReactDOM.render( - , - document.getElementById('example') - ); -}, 500); -``` - -## 반응 적(Reactive) 업데이트 - -`hello-react.html` 파일을 웹 브라우저에서 열어 당신의 이름을 텍스트 필드에 써 보세요. React는 단지 시간을 표시하는 부분만을 바꿉니다 — 텍스트 필드 안에 입력한 것은 그대로 남아 있구요, 당신이 이 동작을 관리하는 그 어떤 코드도 쓰지 않았음에도 불구하고 말이죠. React는 그걸 올바른 방법으로 알아서 해줍니다. - -우리가 이걸 할 수 있었던 건, React는 필요한 경우에만 DOM을 조작하기 때문입니다. **React는 빠른 React 내부의 DOM 모형을 이용하여 변경된 부분을 측정하고, 가장 효율적인 DOM 조작 방법을 계산해 줍니다.** - -이 컴포넌트에 대한 입력은 `props` 라고 불립니다 — "properties" 를 줄인 것이죠. 그들은 JSX 문법에서는 어트리뷰트로서 전달됩니다. 당신은 `props` 를 컴포넌트 안에서 불변의(immutable) 엘리먼트로서 생각해야 하고, `this.props` 를 덮어씌우려고 해서는 안됩니다. - -## 컴포넌트들은 함수와 같습니다 - -React 컴포넌트들은 매우 단순합니다. 당신은 그것들을 `props` 와 `state` (이것들은 나중에 언급할 것입니다) 를 받고 HTML을 렌더링하는 단순한 함수들로 생각해도 됩니다. 이걸 염두하면, 컴포넌트의 작동을 이해하는 것도 쉽습니다. - -> 주의: -> -> **한가지 제약이 있습니다**: React 컴포넌트들은 단 하나의 루트 노드(root node)만을 렌더할 수 있습니다. 만약 여러개의 노드들을 리턴하고 싶다면, 그것들은 단 하나의 루트 노드로 싸여져 있어야만 합니다. - -## JSX 문법 - -우리는 컴포넌트를 사용하는 것이 "템플릿"과 "디스플레이 로직(display logic)"을 이용하는 것보다 관심을 분리(separate concerns)하는 데에 올바른 방법이라고 강하게 믿고 있습니다. 우리는 마크업과 그것을 만들어내는 코드는 친밀하게 함께 결합되어있다고 생각합니다. 또한, 디스플레이 로직은 종종 매우 복잡하고, 그것을 템플릿 언어를 이용해 표현하는 것은 점점 사용하기 어렵게 됩니다. - -우리는 이 문제를 해결하는 최고의 해결책은, UI를 만드는 진짜 프로그래밍 언어의 표현력을 모두 사용할 수 있는 JavaScript 코드로부터 HTML과 컴포넌트 트리들을 생성하는 것임을 발견했습니다. - -이것을 더 쉽게 하기 위해서, 우리는 매우 간단하고, **선택적인** HTML과 비슷한 문법을 추가하여 이 React 트리 노드들을 만들 수 있게 했습니다. - -**JSX는 당신으로 하여금 HTML 문법을 이용해 JavaScript 객체를 만들게 해줍니다.** React를 이용해 순수한 JavaScript 문법으로 링크를 만드려고 한다면, 코드는 다음과 같습니다: - -`React.createElement('a', {href: 'https://facebook.github.io/react/'}, '안녕하세요!')` - -JSX를 이용하면: - -`안녕하세요!` - -우리는 이것이 React 앱들을 만들기 쉽게 하고, 디자이너들이 이 문법을 더 선호하는 것을 발견했습니다, 하지만 모든 사람은 그들만의 선호하는 워크플로우가 있기 마련이므로, **JSX는 React를 사용하기 위해 필수적이지는 않습니다.** - -JSX는 매우 작은 언어입니다. 그것을 배우고 싶다면, [JSX 깊게 살펴보기](/react/docs/jsx-in-depth-ko-KR.html)를 살펴 보시기 바랍니다. 또는, [바벨 REPL](https://babeljs.io/repl/)를 통해 문법이 변환되는 것을 살펴 보시기 바랍니다. - -JSX는 HTML과 비슷하지만, 완전히 똑같지는 않습니다. [JSX의 실수하기 쉬운 부분들](/react/docs/jsx-gotchas-ko-KR.html)에 중요한 차이점들에 대해 설명되어 있습니다. - -[바벨에서 JSX를 시작하는 여러 방법을 제공합니다](http://babeljs.io/docs/setup/). 여기에는 커맨드 라인 툴부터 루비 온 레일스 연동까지 다양한 방법이 있습니다. 가장 편한 툴을 사용하세요. - -## JSX 없이 React 사용하기 - -JSX는 완전히 선택적입니다. 당신은 React와 JSX를 함께 사용하지 않아도 상관없습니다. 그냥 JavaScript에서 React 엘리먼트를 `React.createElement`로 만들 수 있습니다. 여기에 태그 이름이나 컴포넌트, 속성 객체, 자식 엘리먼트들을 전달하면 됩니다. - -```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')); -``` - -편의를 위하여, 당신은 팩토리 함수 헬퍼들을 이용해 커스텀 컴포넌트로부터 엘리먼트들을 만들 수 있습니다. - -```javascript -var Factory = React.createFactory(ComponentClass); -... -var root = Factory({ custom: 'prop' }); -ReactDOM.render(root, document.getElementById('example')); -``` - -React는 이미 일반적인 HTML 태그에 대한 빌트인 팩토리를 가지고 있습니다. - -```javascript -var root = React.DOM.ul({ className: 'my-list' }, - React.DOM.li(null, '텍스트') - ); -``` diff --git a/docs/docs/02-displaying-data.md b/docs/docs/02-displaying-data.md deleted file mode 100644 index 70ad425adda9e..0000000000000 --- a/docs/docs/02-displaying-data.md +++ /dev/null @@ -1,126 +0,0 @@ ---- -id: displaying-data -title: Displaying Data -permalink: docs/displaying-data.html -prev: why-react.html -next: jsx-in-depth.html ---- - -The most basic thing you can do with a UI is display some data. React makes it easy to display data and automatically keeps the interface up-to-date when the data changes. - -## Getting Started - -Let's look at a really simple example. Create a `hello-react.html` file with the following code: - -```html - - - - - Hello React - - - - - -
- - - -``` - -For the rest of the documentation, we'll just focus on the JavaScript code and assume it's inserted into a template like the one above. Replace the placeholder comment above with the following JSX: - -```javascript -class HelloWorld extends React.Component { - render() { - return ( -

- Hello, ! - It is {this.props.date.toTimeString()} -

- ); - } -} - -function tick() { - ReactDOM.render( - , - document.getElementById('example') - ); -} - -setInterval(tick, 500); -``` - -## Reactive Updates - -Open `hello-react.html` in a web browser and type your name into the text field. Notice that React is only changing the time string in the UI — any input you put in the text field remains, even though you haven't written any code to manage this behavior. React figures it out for you and does the right thing. - -The way we are able to figure this out is that React does not manipulate the DOM unless it needs to. **It uses a fast, internal mock DOM to perform diffs and computes the most efficient DOM mutation for you.** - -The inputs to this component are called `props` — short for "properties". They're passed as attributes in JSX syntax. You should think of these as immutable within the component, that is, **never write to `this.props`**. - -## Components are Just Like Functions - -React components are very simple. You can think of them as simple functions that take in `props` and `state` (discussed later) and render HTML. With this in mind, components are easy to reason about. - -> Note: -> -> **One limitation**: React components can only render a single root node. If you want to return multiple nodes they *must* be wrapped in a single root. - -## JSX Syntax - -We strongly believe that components are the right way to separate concerns rather than "templates" and "display logic." We think that markup and the code that generates it are intimately tied together. Additionally, display logic is often very complex and using template languages to express it becomes cumbersome. - -We've found that the best solution for this problem is to generate HTML and component trees directly from the JavaScript code such that you can use all of the expressive power of a real programming language to build UIs. - -In order to make this easier, we've added a very simple, **optional** HTML-like syntax to create these React tree nodes. - -**JSX lets you create JavaScript objects using HTML syntax.** To generate a link in React using pure JavaScript you'd write: - -`React.createElement('a', {href: 'https://facebook.github.io/react/'}, 'Hello!')` - -With JSX this becomes: - -`Hello!` - -We've found this has made building React apps easier and designers tend to prefer the syntax, but everyone has their own workflow, so **JSX is not required to use React.** - -JSX is very small. To learn more about it, see [JSX in depth](/react/docs/jsx-in-depth.html). Or see the transform in action in [the Babel REPL](https://babeljs.io/repl/). - -JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences. - -[Babel exposes a number of ways to get started using JSX](http://babeljs.io/docs/setup/), ranging from command line tools to Ruby on Rails integrations. Choose the tool that works best for you. - -## React without JSX - -JSX is completely optional; you don't have to use JSX with React. You can create React elements in plain JavaScript using `React.createElement`, which takes a tag name or component, a properties object, and variable number of optional child arguments. - -```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')); -``` - -For convenience, you can create short-hand factory functions to create elements from custom components. - -```javascript -var Factory = React.createFactory(ComponentClass); -... -var root = Factory({ custom: 'prop' }); -ReactDOM.render(root, document.getElementById('example')); -``` - -React already has built-in factories for common HTML tags: - -```javascript -var root = React.DOM.ul({ className: 'my-list' }, - React.DOM.li(null, 'Text Content') - ); -``` diff --git a/docs/docs/02-displaying-data.ru-RU.md b/docs/docs/02-displaying-data.ru-RU.md deleted file mode 100644 index 38e707766a4ee..0000000000000 --- a/docs/docs/02-displaying-data.ru-RU.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -id: displaying-data-ru-RU -title: Отображение данных -permalink: docs/displaying-data-ru-RU.html -prev: why-react-ru-RU.html -next: jsx-in-depth.html ---- - -Главная задача интерфейса — это отображать данные. React делает это легко и обновляет интерфейс сразу, как только изменятся данные. - -## Начало - -Давайте рассмотрим простой пример. Создайте файл `hello-react.html` со следующим текстом: - -```html - - - - - Hello React - - - - - -
- - - -``` - -Добавим в этот шаблон немного JavaScript. Замените комментарий на следующий JSX-код: - -```javascript -var HelloWorld = React.createClass({ - render: function() { - return ( -

- Hello, ! - It is {this.props.date.toTimeString()} -

- ); - } -}); - -setInterval(function() { - ReactDOM.render( - , - document.getElementById('example') - ); -}, 500); -``` - -## Реактивные обновления - -Откройте `hello-react.html` в браузере и введите в текстовое поле свое имя. Что происходит со страницей? Каждые полсекунды обновляется время, остальные же части страницы остаются без изменений. Обратите внимание, что мы не написали ни строчки кода, чтобы управлять этим поведением. React сам отлично понимает что надо делать и обновляет элементы на странице по мере необходимости. - -Суть в том, что React не меняет DOM-дерево до тех пор, пока это не потребуется. **Чтобы отразить изменения, React использует быстрое внутреннее представление DOM-дерева и просчитывает как его изменить наиболее эффективно**. - -Передаваемые в компонент данные называются `props` — сокращенно от "properties". В JSX коде они передаются как атрибуты компонента. Считайте, что компонент получает `props` только для чтения. **Никогда не перезаписывайте значения `this.props` внутри компонента.** - -## Компоненты как функции - -Компоненты React — довольно простые сущности. Можно считать их обыкновенными функциями, которые принимают на входе `props` и `state` (см. далее) и возвращают HTML. Если помнить об этом, то компоненты становятся простыми для понимания. - -> Замечание: -> -> **Есть одно ограничение**: Компоненты React умеют возвращать только один узел. Если вам надо вернуть сразу несколько, они *должны* быть обернуты в один корневой узел. - -## Синтаксис JSX - -Мы убеждены, что компоненты — самый подходящий способ разделения ответственностей, гораздо более удобный чем "шаблоны" и "вынесение логики на страницу". Мы считаем, что разметка и код, который её генерирует, неотделимы друг от друга. Плюс, логика на странице часто бывает запутанной, и использование шаблонизаторов, чтобы описать её, только затрудняет работу. - -Мы решили, что лучшим вариантом будет генерировать HTML и деревья компонентов прямо из JS кода. Так вы сможете зайдействовать всю выразительную мощь современного языка программирования для создания интерфейсов. - -А чтобы упростить создание узлов дерева, мы ввели **опциональный** HTML-подобный синтаксис. - -**JSX позволяет вам создавать JavaScript объекты используя синтаксис HTML**. Для генерации ссылки в React вы напишете на чистом JavaScript: - -`React.createElement('a', {href: 'https://facebook.github.io/react/'}, 'Hello!')` - -С JSX это станет: - -`Hello!` - -Мы установили, что с JSX создавать React приложения проще, и дизайнеров как правило устраивает его синтаксис. Но у разных людей разные предпочтения, поэтому стоит сказать, что **JSX необязателен при работе с React.** - -JSX сам по себе очень прост. Чтобы узнать о нем больше, почитайте [подробно про JSX](/react/docs/jsx-in-depth.html). Или можете попробовать его в [Babel REPL](https://babeljs.io/repl/). - -JSX похож на HTML, но но имеет существенные отличия. Почитайте про [подводные камни JSX](/react/docs/jsx-gotchas.html), чтобы понять их ключевые различия. - -[Babel предлагает несколько способов начать работу с JSX](http://babeljs.io/docs/setup/), от консольных утилит до интеграций с Ruby on Rails. Выберите тот инструмент, который лучше всего вам подходит. - -## React без использования JSX - -JSX полностью опционален; вам совсем необязательно использовать его вместе с React. Вы можете создавать React-элементы на чистом JavaScript используя функцию `React.createElement`, которая принимает имя тега или компонента, объект со свойствами, и набор необязательных дочерних элементов. - -```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')); -``` - -Для удобства, вы можете создать сокращенные фабричные функции, чтобы создавать React-элементы из ваших собственных компонентов. - -```javascript -var Factory = React.createFactory(ComponentClass); -... -var root = Factory({ custom: 'prop' }); -ReactDOM.render(root, document.getElementById('example')); -``` - -А для базовых HTML тегов в React уже есть встроенные фабрики: - -```javascript -var root = React.DOM.ul({ className: 'my-list' }, - React.DOM.li(null, 'Text Content') - ); -``` diff --git a/docs/docs/02-displaying-data.zh-CN.md b/docs/docs/02-displaying-data.zh-CN.md deleted file mode 100644 index d099c1440e207..0000000000000 --- a/docs/docs/02-displaying-data.zh-CN.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -id: displaying-data-zh-CN -title: 显示数据 -permalink: docs/displaying-data-zh-CN.html -prev: why-react-zh-CN.html -next: jsx-in-depth-zh-CN.html ---- - -用户界面能做的最基础的事就是显示一些数据。React 让显示数据变得简单,当数据变化的时候,用户界面会自动同步更新。 - -## 开始 - -让我们看一个非常简单的例子。新建一个名为 `hello-react.html` 的文件,代码内容如下: - -```html - - - - - Hello React - - - - - -
- - - -``` - -在接下去的文档中,我们只关注 JavaScript 代码,假设我们把代码插入到上面那个模板中。用下面的代码替换掉上面用来占位的注释。 - -```javascript -var HelloWorld = React.createClass({ - render: function() { - return ( -

- Hello, ! - It is {this.props.date.toTimeString()} -

- ); - } -}); - -setInterval(function() { - ReactDOM.render( - , - document.getElementById('example') - ); -}, 500); -``` - -## 被动更新 (Reactive Updates) - -在浏览器中打开 `hello-react.html` ,在输入框输入你的名字。你会发现 React 在用户界面中只改变了时间, 任何你在输入框输入的内容一直保留着,即使你没有写任何代码来完成这个功能。React 为你解决了这个问题,做了正确的事。 - -我们想到的方法是除非不得不操作 DOM ,React 是不会去操作 DOM 的。**它用一种更快的内置仿造的 DOM 来操作差异,为你计算出出效率最高的 DOM 改变**。 - -对这个组件的输入称为 `props` - "properties"的缩写。得益于 JSX 语法,它们通过参数传递。你必须知道在组件里,这些属性是不可改变的,也就是说 **`this.props` 是只读的**。 - -## 组件就像是函数 - -React 组件非常简单。你可以认为它们就是简单的函数,接受 `props` 和 `state` (后面会讨论) 作为参数,然后渲染出 HTML。正是应为它们是这么的简单,这使得它们非常容易理解。 - -> 注意: -> -> **只有一个限制**: React 组件只能渲染单个根节点。如果你想要返回多个节点,它们*必须*被包含在同一个节点里。 - -## JSX 语法 - -我们坚信组件是正确方法去做关注分离,而不是通过“模板”和“展示逻辑”。我们认为标签和生成它的代码是紧密相连的。此外,展示逻辑通常是很复杂的,通过模板语言实现这些逻辑会产生大量代码。 - -我们得出解决这个问题最好的方案是通过 JavaScript 直接生成模板,这样你就可以用一个真正语言的所有表达能力去构建用户界面。 - -为了使这变得更简单,我们做了一个非常简单、**可选**类似 HTML 语法 ,通过函数调用即可生成模板的编译器,称为 JSX。 - -**JSX 让你可以用 HTML 语法去写 JavaScript 函数调用** 为了在 React 生成一个链接,通过纯 JavaScript 你可以这么写: - -`React.createElement('a', {href: 'https://facebook.github.io/react/'}, 'Hello React!')`。 - -通过 JSX 这就变成了 - -`Hello React!`。 - -我们发现这会使搭建 React 应用更加简单,设计师也偏向用这用语法,但是每个人可以有它们自己的工作流,所以**JSX 不是必须用的。** - -JSX 非常小;上面“hello, world”的例子使用了 JSX 所有的特性。想要了解更多,请看 [深入理解 JSX](/react/docs/jsx-in-depth-zh-CN.html)。或者直接使用[在线 JSX 编译器](/react/jsx-compiler.html)观察变化过程。 - -JSX 类似于 HTML,但不是完全一样。参考 [JSX 陷阱](/react/docs/jsx-gotchas-zh-CN.html) 学习关键区别。 - -[Babel 公开了一些使用 JSX 的方式],从命令行工具到 Ruby on Rails 集成。选择一个对你来说最合适的工具。 - -## 没有 JSX 的 React - -JSX完全是可选的;你无需在 React 中必须使用 JSX。你可以通过 `React.createElement` 来创建一个树。第一个参数是标签,第二个参数是一个属性对象,第三个是子节点。 - -```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')); -``` - -方便起见,你可以创建基于自定义组件的速记工厂方法。 - -```javascript -var Factory = React.createFactory(ComponentClass); -... -var root = Factory({ custom: 'prop' }); -ReactDOM.render(root, document.getElementById('example')); -``` - -React 已经为 HTML 标签提供内置工厂方法。 - -```javascript -var root = React.DOM.ul({ className: 'my-list' }, - React.DOM.li(null, 'Text Content') - ); -``` diff --git a/docs/docs/02-displaying-data.zh-TW.md b/docs/docs/02-displaying-data.zh-TW.md deleted file mode 100644 index 2cc2d4bc47f09..0000000000000 --- a/docs/docs/02-displaying-data.zh-TW.md +++ /dev/null @@ -1,125 +0,0 @@ ---- -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 - - - - - Hello React - - - - - -
- - - -``` - -這份文件其他部份,我們將只會專注在JavaScript程式碼解說上,並且假設程式碼會被放置在如上述模板的註解區塊內. 用下列的JSX程式碼取代上述註解區塊: - -```javascript -var HelloWorld = React.createClass({ - render: function() { - return ( -

- Hello, ! - It is {this.props.date.toTimeString()} -

- ); - } -}); - -setInterval(function() { - ReactDOM.render( - , - 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語法則變成: - -`Hello!` - -我們發現這麼做能讓建立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') - ); -``` diff --git a/docs/docs/02.1-jsx-in-depth.it-IT.md b/docs/docs/02.1-jsx-in-depth.it-IT.md deleted file mode 100644 index 67eac164440a0..0000000000000 --- a/docs/docs/02.1-jsx-in-depth.it-IT.md +++ /dev/null @@ -1,228 +0,0 @@ ---- -id: jsx-in-depth-it-IT -title: JSX in Profondità -permalink: docs/jsx-in-depth-it-IT.html -prev: displaying-data-it-IT.html -next: jsx-spread-it-IT.html ---- - -[JSX](https://facebook.github.io/jsx/) è un'estensione della sintassi JavaScript che somiglia all'XML. Puoi usare una semplice trasformazione sintattica di JSX con React. - -## Perché JSX? - -Non devi per forza utilizzare JSX con React. Puoi anche usare semplice JS. Tuttavia, raccomandiamo di utilizzare JSX perché usa una sintassi concisa e familiare per definire strutture ad albero dotate di attributi. - -È più familiare a sviluppatori occasionali come i designer. - -L'XML ha i benefici di tag di apertura e chiusura bilanciati. Ciò rende la lettura di grandi strutture ad albero più semplice di chiamate a funzione o oggetti letterali. - -Non altera la semantica di JavaScript. - -## Tag HTML o Componenti React - -React può sia rendere tag HTML (stringhe) che componenti React (classi). - -Per rendere untag HTML, usa nomi di tag minuscoli in JSX: - -```javascript -var myDivElement =
; -ReactDOM.render(myDivElement, document.getElementById('example')); -``` - -Per rendere un componente React, definisci una variabile locale che comincia con una lettera maiuscola: - -```javascript -var MyComponent = React.createClass({/*...*/}); -var myElement = ; -ReactDOM.render(myElement, document.getElementById('example')); -``` - -Il JSX di React utilizza la convenzione maiuscolo o minuscolo per distinguere tra classi di componenti locali e tag HTML. - -> Nota: -> -> Poiché JSX è JavaScript, gli identificatori come `class` e `for` sono sconsigliati -> come nomi di attributi XML. Invece, i componenti DOM React si aspettano nomi di proprietà -> come `className` e `htmlFor` rispettivamente. - -## La Trasformazione - -Il JSX di React viene trasformato da una sintassi XML a JavaScript nativo. Gli elementi XML, gli attributi e i figli sono trasformati in argomenti passati a `React.createElement`. - -```javascript -var Nav; -// Input (JSX): -var app =