committed by
Dan Abramov
354 changed files with 7519 additions and 27324 deletions
@ -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 |
@ -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 |
|||
|
|||
|
@ -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 |
@ -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 |
@ -0,0 +1,41 @@ |
|||
<footer class="nav-footer"> |
|||
<section class="sitemap"> |
|||
<a href="/react/" class="nav-home"> |
|||
</a> |
|||
<div> |
|||
<h5><a href="/react/docs/">Docs</a></h5> |
|||
<a href="/react/docs/hello-world.html">Quick Start</a> |
|||
<a href="/react/docs/thinking-in-react.html">Thinking in React</a> |
|||
<a href="/react/tutorial/tutorial.html">Tutorial</a> |
|||
<a href="/react/docs/jsx-in-depth.html">Advanced Guides</a> |
|||
</div> |
|||
<div> |
|||
<h5><a href="/react/community/support.html">Community</a></h5> |
|||
<a href="http://stackoverflow.com/questions/tagged/reactjs" target="_blank">Stack Overflow</a> |
|||
<a href="https://discuss.reactjs.org/" target="_blank">Discussion Forum</a> |
|||
<a href="https://discord.gg/0ZcbPKXt5bZjGY5n" target="_blank">Reactiflux Chat</a> |
|||
<a href="https://www.facebook.com/react" target="_blank">Facebook</a> |
|||
<a href="https://twitter.com/reactjs" target="_blank">Twitter</a> |
|||
</div> |
|||
<div> |
|||
<h5><a href="/react/community/support.html">Resources</a></h5> |
|||
<a href="/react/community/conferences.html">Conferences</a> |
|||
<a href="/react/community/videos.html">Videos</a> |
|||
<a href="https://github.com/facebook/react/wiki/Examples" target="_blank">Examples</a> |
|||
<a href="https://github.com/facebook/react/wiki/Complementary-Tools" target="_blank">Complementary Tools</a> |
|||
</div> |
|||
<div> |
|||
<h5>More</h5> |
|||
<a href="/react/blog/">Blog</a> |
|||
<a href="https://github.com/facebook/react" target="_blank">GitHub</a> |
|||
<a href="http://facebook.github.io/react-native/" target="_blank">React Native</a> |
|||
<a href="/react/acknowledgements.html">Acknowledgements</a> |
|||
</div> |
|||
</section> |
|||
<a href="https://code.facebook.com/projects/" target="_blank" class="fbOpenSource"> |
|||
<img src="/react/img/oss_logo.png" alt="Facebook Open Source" width="170" height="45"/> |
|||
</a> |
|||
<section class="copyright"> |
|||
Copyright © {{ site.time | date: '%Y' }} Facebook Inc. |
|||
</section> |
|||
</footer> |
@ -0,0 +1,13 @@ |
|||
<div class="hero"> |
|||
<div class="wrap"> |
|||
<div class="text"><strong>React</strong></div> |
|||
<div class="minitext"> |
|||
A JavaScript library for building user interfaces |
|||
</div> |
|||
|
|||
<div class="buttons-unit"> |
|||
<a href="/react/docs/hello-world.html" class="button">Get Started</a> |
|||
<a href="/react/tutorial/tutorial.html" class="button">Take the Tutorial</a> |
|||
</div> |
|||
</div> |
|||
</div> |
@ -0,0 +1,24 @@ |
|||
<div class="nav-docs"> |
|||
<!-- Community Nav --> |
|||
{% for section in site.data.nav_community %} |
|||
<div class="nav-docs-section"> |
|||
<h3>{{ section.title }}</h3> |
|||
<ul> |
|||
{% for item in section.items %} |
|||
<li> |
|||
{{ item | community_sidebar_link }} |
|||
{% if item.subitems %} |
|||
<ul> |
|||
{% for subitem in item.subitems %} |
|||
<li> |
|||
{{ subitem | community_sidebar_link }} |
|||
</li> |
|||
{% endfor %} |
|||
</ul> |
|||
{% endif %} |
|||
</li> |
|||
{% endfor %} |
|||
</ul> |
|||
</div> |
|||
{% endfor %} |
|||
</div> |
@ -0,0 +1,24 @@ |
|||
<div class="nav-docs"> |
|||
<!-- Tutorial Nav --> |
|||
{% for section in site.data.nav_tutorial %} |
|||
<div class="nav-docs-section"> |
|||
<h3>{{ section.title }}</h3> |
|||
<ul> |
|||
{% for item in section.items %} |
|||
<li> |
|||
{{ item | tutorial_sidebar_link }} |
|||
{% if item.subitems %} |
|||
<ul> |
|||
{% for subitem in item.subitems %} |
|||
<li> |
|||
{{ subitem | tutorial_sidebar_link }} |
|||
</li> |
|||
{% endfor %} |
|||
</ul> |
|||
{% endif %} |
|||
</li> |
|||
{% endfor %} |
|||
</ul> |
|||
</div> |
|||
{% endfor %} |
|||
</div> |
@ -0,0 +1,23 @@ |
|||
<div class="nav-main"> |
|||
<div class="wrap"> |
|||
<a class="nav-home" href="/react/index.html"> |
|||
<img class="nav-logo" src="/react/img/logo.svg" width="36" height="36"> |
|||
React |
|||
</a> |
|||
<div class="nav-lists"> |
|||
<ul class="nav-site nav-site-internal"> |
|||
<li><a href="/react/docs/hello-world.html"{% if page.sectionid == 'docs' or page.sectionid == 'tips' or page.sectionid == 'contributing' %} class="active"{% endif %}>Docs</a></li> |
|||
<li><a href="/react/tutorial/tutorial.html"{% if page.sectionid == 'tutorial' %} class="active"{% endif %}>Tutorial</a></li> |
|||
<li><a href="/react/community/support.html"{% if page.sectionid == 'community' %} class="active"{% endif %}>Community</a></li> |
|||
<li><a href="/react/blog/"{% if page.sectionid == 'blog' %} class="active"{% endif %}>Blog</a></li> |
|||
<li class="nav-site-search"> |
|||
<input id="algolia-doc-search" type="text" placeholder="Search docs..." /> |
|||
</li> |
|||
</ul> |
|||
<ul class="nav-site nav-site-external"> |
|||
<li><a href="https://github.com/facebook/react">GitHub</a></li> |
|||
<li><a href="https://facebook.github.io/react-native/">React Native</a></li> |
|||
</ul> |
|||
</div> |
|||
</div> |
|||
</div> |
@ -0,0 +1,29 @@ |
|||
--- |
|||
layout: default |
|||
sectionid: community |
|||
--- |
|||
|
|||
<section class="content wrap communityContent"> |
|||
<div class="inner-content"> |
|||
<a class="edit-page-link" |
|||
href="https://github.com/facebook/react/tree/master/docs/{{ page.path }}" |
|||
target="_blank">Edit on GitHub</a> |
|||
<h1> |
|||
{{ page.title }} |
|||
</h1> |
|||
<div class="subHeader">{{ page.description }}</div> |
|||
|
|||
{{ content }} |
|||
|
|||
<div class="docs-prevnext"> |
|||
{% if page.prev %} |
|||
<a class="docs-prev" href="/react/community/{{ page.prev }}">← Prev</a> |
|||
{% endif %} |
|||
{% if page.next %} |
|||
<a class="docs-next" href="/react/community/{{ page.next }}">Next →</a> |
|||
{% endif %} |
|||
</div> |
|||
</div> |
|||
|
|||
{% include nav_community.html %} |
|||
</section> |
@ -0,0 +1,11 @@ |
|||
--- |
|||
layout: default |
|||
--- |
|||
|
|||
{% if page.id == 'home' %} |
|||
{% include hero.html %} |
|||
{% endif %} |
|||
|
|||
<section class="content wrap"> |
|||
{{ content }} |
|||
</section> |
@ -1,23 +0,0 @@ |
|||
--- |
|||
layout: default |
|||
sectionid: tips |
|||
--- |
|||
|
|||
<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/tips/{{ page.prev }}">← Prev</a> |
|||
{% endif %} |
|||
{% if page.next %} |
|||
<a class="docs-next" href="/react/tips/{{ page.next }}">Next →</a> |
|||
{% endif %} |
|||
</div> |
|||
</div> |
|||
</section> |
@ -0,0 +1,29 @@ |
|||
--- |
|||
layout: default |
|||
sectionid: tutorial |
|||
--- |
|||
|
|||
<section class="content wrap documentationContent"> |
|||
{% include nav_tutorial.html %} |
|||
|
|||
<div class="inner-content"> |
|||
<a class="edit-page-link" |
|||
href="https://github.com/facebook/react/tree/master/docs/{{ page.path }}" |
|||
target="_blank">Edit on GitHub</a> |
|||
<h1> |
|||
{{ page.title }} |
|||
</h1> |
|||
<div class="subHeader">{{ page.description }}</div> |
|||
|
|||
{{ content }} |
|||
|
|||
<div class="docs-prevnext"> |
|||
{% if page.prev %} |
|||
<a class="docs-prev" href="/react/tutorial/{{ page.prev }}">← Prev</a> |
|||
{% endif %} |
|||
{% if page.next %} |
|||
<a class="docs-next" href="/react/tutorial/{{ page.next }}">Next →</a> |
|||
{% endif %} |
|||
</div> |
|||
</div> |
|||
</section> |
@ -0,0 +1,180 @@ |
|||
--- |
|||
id: videos |
|||
title: Videos |
|||
layout: community |
|||
sectionid: community |
|||
permalink: community/videos.html |
|||
redirect_from: "docs/videos.html" |
|||
--- |
|||
|
|||
### Introduction to React |
|||
|
|||
[Tom Occhino](http://tomocchino.com/) and [Jordan Walke](https://github.com/jordwalke) introduce React at Facebook Seattle. |
|||
|
|||
<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/XxVg_s8xAms" frameborder="0" allowfullscreen></iframe> |
|||
|
|||
### Introducing React Native |
|||
|
|||
[Tom Occhino](https://twitter.com/tomocchino) reviews the past and present of React in 2015, and teases where it's going next. |
|||
|
|||
<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe> |
|||
|
|||
### Rethinking Web App Development at Facebook |
|||
|
|||
Delivering reliable, high-performance web experiences at Facebook's scale has required us to challenge some long-held assumptions about software development. Watch this Facebook F8 2014 talk to learn how we abandoned the traditional MVC paradigm in favor of a more functional application architecture. |
|||
|
|||
<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/nYkdrAPrdcw" frameborder="0" allowfullscreen></iframe> |
|||
|
|||
### Secrets of the Virtual DOM |
|||
|
|||
[Pete Hunt](http://www.petehunt.net/) at Mountain West JavaScript 2014 discusses why a virtual DOM was built for React, how it compares to other systems, and its relevance to the future of browser technologies. |
|||
|
|||
<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/h3KksH8gfcQ" frameborder="0" allowfullscreen></iframe> |
|||
|
|||
### Rethinking Best Practices |
|||
|
|||
[Pete Hunt](http://www.petehunt.net/)'s talk at JSConf EU 2013 covers three topics: throwing out the notion of templates and building views with JavaScript, “re-rendering” your entire application when your data changes, and a lightweight implementation of the DOM and events. |
|||
|
|||
<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe> |
|||
|
|||
|
|||
### High performance functional DOM programming |
|||
|
|||
Tech Talk by [Pete Hunt](http://www.petehunt.net/) at Meteor DevShop 11. |
|||
|
|||
<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/qqVbr_LaCIo" frameborder="0" allowfullscreen></iframe> |
|||
|
|||
|
|||
### Developing User Interfaces With React |
|||
|
|||
[Steven Luscher](https://github.com/steveluscher) at Super VanJS 2013. |
|||
|
|||
<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/1OeXsL5mr4g" frameborder="0" allowfullscreen></iframe> |
|||
|
|||
|
|||
### Introduction to React |
|||
|
|||
[Stoyan Stefanov](http://www.phpied.com/) at LAWebSpeed meetup. |
|||
|
|||
<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/SMMRJif5QW0" frameborder="0" allowfullscreen></iframe> |
|||
|
|||
### Going big with React |
|||
|
|||
Areeb Malik investigates how React performs in a high stress situation, and how it helped his team build safe code on a massive scale. |
|||
|
|||
[](https://skillsmatter.com/skillscasts/5429-going-big-with-react#video) |
|||
|
|||
### Backbone + React + Middleman Screencast |
|||
|
|||
This screencast shows how to integrate Backbone with React using [Backbone-React-Component](https://github.com/magalhas/backbone-react-component). |
|||
|
|||
<iframe width="100%" height="488" src="https://www.youtube-nocookie.com/embed/iul1fWHVU6A" frameborder="0" allowfullscreen></iframe> |
|||
|
|||
### React, or how to make life simpler |
|||
|
|||
Tech talk by [Alexander Solovyov](http://solovyov.net/) at FrontEnd Dev Conf '14 (Russian). |
|||
|
|||
<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/YJNUK0EA_Jo" frameborder="0" allowfullscreen></iframe> |
|||
|
|||
|
|||
### React and Flux: Building Applications with a Unidirectional Data Flow |
|||
|
|||
Facebook engineers [Bill Fisher](https://twitter.com/fisherwebdev) and [Jing Chen](https://twitter.com/jingc) talk about Flux and React at Forward JS 2014, and how using an application architecture with a unidirectional data flow cleans up a lot of their code. |
|||
|
|||
<iframe width="100%" height="366" src="https://www.youtube-nocookie.com/embed/i__969noyAM" frameborder="0" allowfullscreen></iframe> |
|||
|
|||
### Server-Side Rendering of Isomorphic Apps at SoundCloud |
|||
|
|||
Walk-through by [Andres Suarez](https://github.com/zertosh) on how [SoundCloud](https://developers.soundcloud.com/blog/) is using React and Flux for server-side rendering. |
|||
|
|||
<iframe src="https://player.vimeo.com/video/108488724" width="100%" height="365" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> |
|||
|
|||
> [Slides and sample code](https://github.com/zertosh/ssr-demo-kit) |
|||
|
|||
### CodeWinds Podcast |
|||
|
|||
[Pete Hunt](http://www.petehunt.net/) talked with [Jeff Barczewski](http://jeff.barczewski.com/) about React in [CodeWinds Episode 4](http://codewinds.com/podcast/004.html). |
|||
<figure>[](http://codewinds.com/4)</figure> |
|||
|
|||
<table width="100%"> |
|||
<tr> |
|||
<th>02:08</th><td>What is React and why use it?</td> |
|||
<th>27:17</th><td>Rendering HTML on the server with Node.js. Rendering backends</td> |
|||
</tr> |
|||
<tr> |
|||
<th>03:08</th><td>The symbiotic relationship of ClojureScript and React</td> |
|||
<th>29:20</th><td>React evolved through survival of the fittest at Facebook</td> |
|||
</tr> |
|||
<tr> |
|||
<th>04:54</th><td>The history of React and why it was created</td> |
|||
<th>30:15</th><td>Ideas for having state on server and client, using web sockets.</td> |
|||
</tr> |
|||
<tr> |
|||
<th>09:43</th><td>Updating web page with React without using data binding</td> |
|||
<th>32:05</th><td>React-multiuser - distributed shared mutable state using Firebase</td> |
|||
</tr> |
|||
<tr> |
|||
<th>13:11</th><td>Using the virtual DOM to change the browser DOM</td> |
|||
<th>33:03</th><td>Better debugging with React using the state transitions, replaying events</td> |
|||
</tr> |
|||
<tr> |
|||
<th>13:57</th><td>Programming with React, render targets HTML, canvas, other</td> |
|||
<th>34:08</th><td>Differences from Web Components</td> |
|||
</tr> |
|||
<tr> |
|||
<th>16:45</th><td>Working with designers. Contrasted with Ember and AngularJS</td> |
|||
<th>34:25</th><td>Notable companies using React</td> |
|||
</tr> |
|||
<tr> |
|||
<th>21:45</th><td>JSX Compiler bridging HTML and React javascript</td> |
|||
<th>35:16</th><td>Could a React backend plugin be created to target PDF?</td> |
|||
</tr> |
|||
<tr> |
|||
<th>23:50</th><td>Autobuilding JSX and in browser tools for React</td> |
|||
<th>36:30</th><td>Future of React, what's next?</td> |
|||
</tr> |
|||
<tr> |
|||
<th>24:50</th><td>Tips and tricks to working with React, getting started</td> |
|||
<th>39:38</th><td>Contributing and getting help</td> |
|||
</tr> |
|||
</table> |
|||
|
|||
### JavaScript Jabber Podcast |
|||
|
|||
[Pete Hunt](http://www.petehunt.net/) and [Jordan Walke](https://github.com/jordwalke) talked about React in [JavaScript Jabber 73](https://devchat.tv/js-jabber/073-jsj-react-with-pete-hunt-and-jordan-walke). |
|||
<figure>[](http://javascriptjabber.com/073-jsj-react-with-pete-hunt-and-jordan-walke/#content)</figure> |
|||
|
|||
<table width="100%"> |
|||
<tr> |
|||
<th>01:34</th><td>Pete Hunt Introduction</td> |
|||
<th>23:06</th><td>Supporting Node.js</td> |
|||
</tr> |
|||
<tr> |
|||
<th>02:45</th><td>Jordan Walke Introduction</td> |
|||
<th>24:03</th><td>rendr</td> |
|||
</tr> |
|||
<tr> |
|||
<th>04:15</th><td>React</td> |
|||
<th>26:02</th><td>JSX</td> |
|||
</tr> |
|||
<tr> |
|||
<th>06:38</th><td>60 Frames Per Second</td> |
|||
<th>30:31</th><td>requestAnimationFrame</td> |
|||
</tr> |
|||
<tr> |
|||
<th>09:34</th><td>Data Binding</td> |
|||
<th>34:15</th><td>React and Applications</td> |
|||
</tr> |
|||
<tr> |
|||
<th>12:31</th><td>Performance</td> |
|||
<th>38:12</th><td>React Users Khan Academy</td> |
|||
</tr> |
|||
<tr> |
|||
<th>17:39</th><td>Diffing Algorithm</td> |
|||
<th>39:53</th><td>Making it work</td> |
|||
</tr> |
|||
<tr> |
|||
<th>19:36</th><td>DOM Manipulation</td> |
|||
<th></th><td></td> |
|||
</tr> |
|||
</table> |
@ -1,28 +0,0 @@ |
|||
--- |
|||
id: why-react-de-DE |
|||
title: Warum React? |
|||
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. |
|||
|
|||
Wir haben React für folgende Aufgabe entwickelt: **umfangreiche Anwendungen zu bauen, deren Daten sich zeitlich ändern**. |
|||
|
|||
## Einfach |
|||
|
|||
Beschreibe, wie sich Deine App zu jedem gewünschten Zeitpunkt präsentieren soll und React kümmert sich um alle Benutzeroberflächen-Änderungen sobald sich die zugrundeliegenden Daten ändern. |
|||
|
|||
## Deklarativ |
|||
|
|||
Bei Datenveränderungen drückt React bildlich die "Aktualisieren"-Taste und versteht sich darauf, nur die veränderten Elemente zu erneuern. |
|||
|
|||
## Baue zusammensetzbare Komponenten |
|||
|
|||
React unterstützt die Entwicklung wiederverwendbarer Komponenten. Tatsächlich machst Du in React nichts anderes, als Komponenten zu bauen. Dank ihrer Kapselung erleichtern Komponenten die Wiederverwendung und das Testen von Code sowie die Trennung der Belange. |
|||
|
|||
## Gib' ihnen fünf Minuten |
|||
|
|||
React hinterfragt eine ganze Reihe konventioneller Standpunkte. Auf den ersten Blick mögen einige Ideen verrückt klingen. [Gib' ihnen fünf Minuten](https://signalvnoise.com/posts/3124-give-it-five-minutes) während Du diese Anleitung liest; diese verrückten Ideen halfen dabei, tausende von Komponenten innerhalb und außerhalb von Facebook und Instagram zu entwickeln. |
|||
|
|||
## Erfahre mehr |
|||
|
|||
Erfahre mehr über unsere Motivation zur Entwicklung von React in [diesem Blogeintrag](/react/blog/2013/06/05/why-react.html). |
@ -1,29 +0,0 @@ |
|||
--- |
|||
id: why-react-it-IT |
|||
title: Perché React? |
|||
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)**. |
|||
|
|||
Abbiamo costruito React per risolvere un problema: **costruire applicazioni di grandi dimensioni con dati che cambiano nel tempo**. |
|||
|
|||
## Semplice |
|||
|
|||
Dichiara semplicemente come la tua app debba apparire in ogni istante, e React gestirà automaticamente tutti gli aggiornamenti della UI quando i dati sottostanti cambiano. |
|||
|
|||
## Dichiarativo |
|||
|
|||
Quando i dati cambiano, React preme idealmente il bottone "aggiorna", e sa come aggiornare soltanto le parti che sono cambiate. |
|||
|
|||
## Costruisci Componenti Componibili |
|||
|
|||
React è basato interamente sulla costruzione di componenti riutilizzabili. Infatti, con React l'*unica* cosa che fai è costruire componenti. Dal momento che sono così incapsulati, i componenti facilitano il riutilizzo del codice, la verifica e la separazione dei concetti. |
|||
|
|||
## Dagli Cinque Minuti |
|||
|
|||
React sfida molte convenzioni, e a prima vista alcune delle idee potrebbero sembrare folli. [Dagli cinque minuti](https://signalvnoise.com/posts/3124-give-it-five-minutes) mentre leggi questa guida; quelle idee folli hanno funzionato per costruire migliaia di componenti sia dentro che fuori da Facebook e Instagram. |
|||
|
|||
## Per Approfondire |
|||
|
|||
Puoi approfondire le nostre motivazioni per la costruzione di React leggendo [questo articolo del blog](/react/blog/2013/06/05/why-react.html). |
@ -1,29 +0,0 @@ |
|||
--- |
|||
id: why-react-ja-JP |
|||
title: なぜReactを使うのでしょうか? |
|||
permalink: docs/why-react-ja-JP.html |
|||
next: displaying-data-ja-JP.html |
|||
|
|||
--- |
|||
ReactはFacebookとInstagramによって作られたユーザーインターフェイスを構築するためのJavaScriptのライブラリです。 |
|||
多くの人がReactを **[MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)** の **V** だと考えています。 |
|||
私たちはReactをある1つの問題を解決するために使います。それは、 **絶えず変化していくデータとともに大きなアプリケーションを構築する** ことです。それを行うために、Reactは2つの主要な考えを持っています。 |
|||
|
|||
## 単純さ |
|||
|
|||
どのタイミングにおいても、アプリケーションがどのように見えるべきかを単純に表現し、Reactは根底にあるデータの変更があった場合に自動的に全てのUIを管理します。 |
|||
|
|||
## 叙述的 |
|||
|
|||
データが変わった時、Reactは概念的に「リフレッシュ」ボタンを押し、変わった箇所のみを検知します。 |
|||
|
|||
## コンポーザブルなコンポーネントの構築 |
|||
Reactは再利用可能なコンポーネントを構築するものです。実際、Reactを用いてあなたがする *ただ1つの* ことは、コンポーネントを構築することです。Reactは無駄な部分を省いてあるので、コンポーネントはコードの再利用、テスト、関心の分離を可能にします。 |
|||
|
|||
## 5分ください |
|||
|
|||
Reactは型にはまった知識にも挑戦し、ちらっと見ただけではおかしく見えるアイディアもあるでしょう。このガイドを読むのに[5分ください](https://signalvnoise.com/posts/3124-give-it-five-minutes) 。それらのおかしく見えるアイディアはFacebookやInstagramの中と外の両方で何千ものコンポーネントを構築するために動いています。 |
|||
|
|||
## 更なる学習 |
|||
|
|||
[このブログの投稿](/react/blog/2013/06/05/why-react.html)で、私たちがReactを構築するモチベーションについて更に学習することができます。 |
@ -1,30 +0,0 @@ |
|||
--- |
|||
id: why-react-ko-KR |
|||
title: 왜 React인가? |
|||
permalink: docs/why-react-ko-KR.html |
|||
next: displaying-data-ko-KR.html |
|||
--- |
|||
|
|||
React는 페이스북과 인스타그램에서 사용자 인터페이스를 구성하기 위해 만들어진 라이브러리입니다. 많은 사람들은 React를 **[MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)** 에서의 **V** 로 생각하는 경향이 있습니다. |
|||
|
|||
우리는 단 하나의 문제를 해결하기 위해 React를 만들었습니다: **지속해서 데이터가 변화하는 대규모 애플리케이션을 구축하기.** 이 문제를 해결하기 위해, React는 두가지 컨셉을 도입했습니다. |
|||
|
|||
## 단순함 |
|||
|
|||
당신의 애플리케이션이 특정 시점에 어떻게 보여야 할지를 단순히 표현하는 것만으로, 데이터가 변할 때 React는 자동으로 모든 UI 업데이트를 관리해줍니다. |
|||
|
|||
## 선언적 문법 |
|||
|
|||
데이터가 변할 때 React는 "새로 고침" 버튼을 누르듯이 작동하며, 데이터의 바뀐 부분만을 업데이트할 수 있습니다. |
|||
|
|||
## 구성적인 컴포넌트를 만드세요 |
|||
|
|||
React는 재사용 가능한 컴포넌트들을 만드는 데에 도움이 됩니다. 사실, React를 사용하면 *단지* 컴포넌트를 만드는 일만 하게 됩니다. 컴포넌트들은 잘 캡슐화되어 되어 있기 때문에, 컴포넌트들은 코드의 재사용성을 높이고, 테스트를 쉽게 해 주며, 관심 분리의 원칙(separation of concerns)을 지키게 해 줍니다. |
|||
|
|||
## 5분만 투자하세요 |
|||
|
|||
React는 많은 관습적인 사고에 도전하며, 첫눈에 볼 때는 이상한 아이디어들의 모음이라고 생각할 수도 있습니다. 이 가이드를 읽기 위해 [5분만 투자하세요](https://signalvnoise.com/posts/3124-give-it-five-minutes); 그 이상한 아이디어들은 페이스북과 인스타그램 안팎의 수천 개의 컴포넌트들을 만드는 데에 사용되었기 때문입니다. |
|||
|
|||
## 더 알아보기 |
|||
|
|||
[이 블로그 포스트](/react/blog/2013/06/05/why-react.html)에서 React를 만든 우리의 동기에 대해 알아볼 수 있습니다. |
@ -1,29 +0,0 @@ |
|||
--- |
|||
id: why-react |
|||
title: Why React? |
|||
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)**. |
|||
|
|||
We built React to solve one problem: **building large applications with data that changes over time**. |
|||
|
|||
## Simple |
|||
|
|||
Simply express how your app should look at any given point in time, and React will automatically manage all UI updates when your underlying data changes. |
|||
|
|||
## Declarative |
|||
|
|||
When the data changes, React conceptually hits the "refresh" button, and knows to only update the changed parts. |
|||
|
|||
## Build Composable Components |
|||
|
|||
React is all about building reusable components. In fact, with React the *only* thing you do is build components. Since they're so encapsulated, components make code reuse, testing, and separation of concerns easy. |
|||
|
|||
## Give It Five Minutes |
|||
|
|||
React challenges a lot of conventional wisdom, and at first glance some of the ideas may seem crazy. [Give it five minutes](https://signalvnoise.com/posts/3124-give-it-five-minutes) while reading this guide; those crazy ideas have worked for building thousands of components both inside and outside of Facebook and Instagram. |
|||
|
|||
## Learn More |
|||
|
|||
You can learn more about our motivations behind building React in [this blog post](/react/blog/2013/06/05/why-react.html). |
@ -1,29 +0,0 @@ |
|||
--- |
|||
id: why-react-ru-RU |
|||
title: Почему именно React? |
|||
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)**. |
|||
|
|||
Мы делали React, чтобы решить одну важную задачу: **создавать действительно большие приложения с постоянно меняющимися данными**. |
|||
|
|||
## Простота |
|||
|
|||
С React вы всегда точно знаете как будет выглядеть ваше приложение, ведь как только изменятся данные, он мгновенно отобразит эти изменения в интерфейсе. |
|||
|
|||
## Декларативность |
|||
|
|||
Как только состояние приложения изменится, React будто нажимает кнопку "обновить" и точно знает, какие части интерфейса надо поменять, а какие нет. Никаких дополнительных инструкций и команд, React сам отслеживает изменения данных и реагирует на них. |
|||
|
|||
## Создание компонентов, как строительных блоков приложения |
|||
|
|||
По сути, разработка на React целиком состоит в создании таких компонентов. С React вы *только* тем и занимаетесь, что пишете новые компоненты, те самые строительные блоки, из которых будет строиться приложение. А поскольку они хорошо инскапсулированы, их удобно использовать повторно даже в других проектах, плюс такой код проще тестировать. |
|||
|
|||
## Уделите этому 5 минут |
|||
|
|||
React бросает вызов многим устоявшимся идеям и правилам, и на первый взгляд, некоторые из его идей выглядят по меньшей мере странными. [Уделите этому 5 минут](https://signalvnoise.com/posts/3124-give-it-five-minutes) пока читаете эту статью; эти безумные идеи нашли свое применение при создании тысяч компонентов не только для Facebook и Instagram, но и в других крупных проектах. |
|||
|
|||
## Узнай больше |
|||
|
|||
Вы можете больше узнать о причинах создания React [отсюда](/react/blog/2013/06/05/why-react.html). |
@ -1,29 +0,0 @@ |
|||
--- |
|||
id: why-react-zh-CN |
|||
title: 为什么使用 React? |
|||
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**(视图)。 |
|||
|
|||
我们创造 React 是为了解决一个问题:**构建随着时间数据不断变化的大规模应用程序**。 |
|||
|
|||
### 简单 |
|||
|
|||
仅仅只要表达出你的应用程序在任一个时间点应该呈现的样子,然后当底层的数据变了,React 会自动处理所有用户界面的更新。 |
|||
|
|||
### 声明式 (Declarative) |
|||
|
|||
数据变化后,React 概念上与点击“刷新”按钮类似,但仅会更新变化的部分。 |
|||
|
|||
## 构建可组合的组件 |
|||
|
|||
React 都是关于构建可复用的组件。事实上,通过 React 你*唯一*要做的事情就是构建组件。得益于其良好的封装性,组件使代码复用、测试和关注分离(separation of concerns)更加简单。 |
|||
|
|||
## 给它5分钟的时间 |
|||
|
|||
React挑战了很多传统的知识,第一眼看上去可能很多想法有点疯狂。当你阅读这篇指南,请[给它5分钟的时间](https://signalvnoise.com/posts/3124-give-it-five-minutes);那些疯狂的想法已经帮助 Facebook 和 Instagram 从里到外创建了上千的组件了。 |
|||
|
|||
## 了解更多 |
|||
|
|||
你可以从这篇[博客](/react/blog/2013/06/05/why-react.html)了解更多我们创造 React 的动机。 |
@ -1,29 +0,0 @@ |
|||
--- |
|||
id: why-react-zh-TW |
|||
title: Why React? |
|||
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** 的部份. |
|||
|
|||
我們建造React用來解決一個問題: **開發資料能隨時間頻繁更新的大型應用程式**. |
|||
|
|||
## 簡單(Simple) |
|||
|
|||
簡單意味著你所開發的應用程式外觀任何一部分都要能即時呈現, 並且當資料有所變動時React能自動管理所有UI的更新. |
|||
|
|||
## 陳述(Declarative) |
|||
|
|||
當資料改變時, React概念上就像是點擊了 "刷新" 的按鈕, 並且知道只需更新有改變的部份. |
|||
|
|||
## 建立可組合的元件(Composable Components) |
|||
|
|||
React就是在建造可重用的元件(Components). 事實上, 當你使用React時 *唯一* 在做的事就是建立元件(Components). 由於它們封裝性高,元件使得程式碼能夠易於重複使用, 測試, 並且容易做到讓關注點分離(separation of concerns easy). |
|||
|
|||
## 指引(Give It Five Minutes) |
|||
|
|||
React挑戰了許多傳統的觀念, 第一次乍看之下這些構想可能看起來有點瘋狂. [Give it five minutes](https://signalvnoise.com/posts/3124-give-it-five-minutes) 而當閱讀完這篇指引; 這些瘋狂的構想在Facebook和Instagram裡裡外外建立了數以千計的元件(components)之後被證明是可實行的. |
|||
|
|||
## 更多學習資源 |
|||
|
|||
從這裡你能學習到更多建造React背後的動機 [this blog post](/react/blog/2013/06/05/why-react.html). |
@ -1,129 +0,0 @@ |
|||
--- |
|||
id: displaying-data-it-IT |
|||
title: Visualizzare Dati |
|||
permalink: docs/displaying-data-it-IT.html |
|||
prev: why-react-it-IT.html |
|||
next: jsx-in-depth-it-IT.html |
|||
--- |
|||
|
|||
L'attività più basilare che puoi effettuare con una UI è mostrare dei dati. React rende visualizzare dati semplice e mantiene automaticamente l'interfaccia aggiornata quando i dati cambiano. |
|||
|
|||
|
|||
## Per Cominciare |
|||
|
|||
Diamo un'occhiata ad un esempio davvero semplice. Creiamo un file dal nome `hello-react.html` con il codice seguente: |
|||
|
|||
```html |
|||
<!DOCTYPE html> |
|||
<html> |
|||
<head> |
|||
<meta charset="UTF-8" /> |
|||
<title>Hello React</title> |
|||
<script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script> |
|||
<script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script> |
|||
<script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script> |
|||
</head> |
|||
<body> |
|||
<div id="example"></div> |
|||
<script type="text/babel"> |
|||
|
|||
// ** Il tuo codice va qui! ** |
|||
|
|||
</script> |
|||
</body> |
|||
</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 ( |
|||
<p> |
|||
Ciao, <input type="text" placeholder="Scrivi il tuo nome" />! |
|||
È il {this.props.date.toTimeString()} |
|||
</p> |
|||
); |
|||
} |
|||
}); |
|||
|
|||
setInterval(function() { |
|||
ReactDOM.render( |
|||
<HelloWorld date={new Date()} />, |
|||
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: |
|||
|
|||
`<a href="https://facebook.github.io/react/">Ciao!</a>` |
|||
|
|||
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') |
|||
); |
|||
``` |
@ -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 |
|||
<!DOCTYPE html> |
|||
<html> |
|||
<head> |
|||
<meta charset="UTF-8" /> |
|||
<title>Hello React</title> |
|||
<script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script> |
|||
<script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script> |
|||
<script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script> |
|||
</head> |
|||
<body> |
|||
<div id="example"></div> |
|||
<script type="text/babel"> |
|||
|
|||
// ** コードをここに書きます! ** |
|||
|
|||
</script> |
|||
</body> |
|||
</html> |
|||
``` |
|||
|
|||
このドキュメントの中では、JavaScriptのコードにのみフォーカスします。そして、それが上のようなテンプレートに挿入されていると考えます。 |
|||
|
|||
```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); |
|||
``` |
|||
|
|||
|
|||
## リアクティブなアップデート |
|||
|
|||
`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では、以下のように変換されます。 |
|||
|
|||
`<a href="https://facebook.github.io/react/">Hello!</a>` |
|||
|
|||
以上のようなことで、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') |
|||
); |
|||
``` |
@ -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 |
|||
<!DOCTYPE html> |
|||
<html> |
|||
<head> |
|||
<meta charset="UTF-8" /> |
|||
<title>Hello React</title> |
|||
<script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script> |
|||
<script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script> |
|||
<script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script> |
|||
</head> |
|||
<body> |
|||
<div id="example"></div> |
|||
<script type="text/babel"> |
|||
|
|||
// ** 코드는 여기에 작성하면 됩니다! ** |
|||
|
|||
</script> |
|||
</body> |
|||
</html> |
|||
``` |
|||
|
|||
문서의 나머지에서, 코드가 위와 같은 HTML 템플릿에 들어갔다고 가정하고 JavaScript 코드에만 집중할 것입니다. 위의 주석 부분을 다음과 같은 JSX 코드로 바꿔 보세요: |
|||
|
|||
```javascript |
|||
var HelloWorld = React.createClass({ |
|||
render: function() { |
|||
return ( |
|||
<p> |
|||
안녕, <input type="text" placeholder="이름을 여기에 작성하세요" />! |
|||
지금 시간은 {this.props.date.toTimeString()} 입니다. |
|||
</p> |
|||
); |
|||
} |
|||
}); |
|||
|
|||
setInterval(function() { |
|||
ReactDOM.render( |
|||
<HelloWorld date={new Date()} />, |
|||
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를 이용하면: |
|||
|
|||
`<a href="https://facebook.github.io/react/">안녕하세요!</a>` |
|||
|
|||
우리는 이것이 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, '텍스트') |
|||
); |
|||
``` |
@ -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 |
|||
<!DOCTYPE html> |
|||
<html> |
|||
<head> |
|||
<meta charset="UTF-8" /> |
|||
<title>Hello React</title> |
|||
<script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script> |
|||
<script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script> |
|||
<script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script> |
|||
</head> |
|||
<body> |
|||
<div id="example"></div> |
|||
<script type="text/babel"> |
|||
|
|||
// ** Your code goes here! ** |
|||
|
|||
</script> |
|||
</body> |
|||
</html> |
|||
``` |
|||
|
|||
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 ( |
|||
<p> |
|||
Hello, <input type="text" placeholder="Your name here" />! |
|||
It is {this.props.date.toTimeString()} |
|||
</p> |
|||
); |
|||
} |
|||
} |
|||
|
|||
function tick() { |
|||
ReactDOM.render( |
|||
<HelloWorld date={new Date()} />, |
|||
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: |
|||
|
|||
`<a href="https://facebook.github.io/react/">Hello!</a>` |
|||
|
|||
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') |
|||
); |
|||
``` |
@ -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 |
|||
<!DOCTYPE html> |
|||
<html> |
|||
<head> |
|||
<meta charset="UTF-8" /> |
|||
<title>Hello React</title> |
|||
<script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script> |
|||
<script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script> |
|||
<script src="https://unpkg.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); |
|||
``` |
|||
|
|||
## Реактивные обновления |
|||
|
|||
Откройте `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 это станет: |
|||
|
|||
`<a href="https://facebook.github.io/react/">Hello!</a>` |
|||
|
|||
Мы установили, что с 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') |
|||
); |
|||
``` |
@ -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 |
|||
<!DOCTYPE html> |
|||
<html> |
|||
<head> |
|||
<meta charset="UTF-8" /> |
|||
<title>Hello React</title> |
|||
<script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script> |
|||
<script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script> |
|||
<script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script> |
|||
</head> |
|||
<body> |
|||
<div id="example"></div> |
|||
<script type="text/babel"> |
|||
|
|||
// ** 在这里替换成你的代码 ** |
|||
|
|||
</script> |
|||
</body> |
|||
</html> |
|||
``` |
|||
|
|||
在接下去的文档中,我们只关注 JavaScript 代码,假设我们把代码插入到上面那个模板中。用下面的代码替换掉上面用来占位的注释。 |
|||
|
|||
```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 在用户界面中只改变了时间, 任何你在输入框输入的内容一直保留着,即使你没有写任何代码来完成这个功能。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 这就变成了 |
|||
|
|||
`<a href="https://facebook.github.io/react/">Hello React!</a>`。 |
|||
|
|||
我们发现这会使搭建 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') |
|||
); |
|||
``` |
@ -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 |
|||
<!DOCTYPE html> |
|||
<html> |
|||
<head> |
|||
<meta charset="UTF-8" /> |
|||
<title>Hello React</title> |
|||
<script src="https://unpkg.com/react@{{site.react_version}}/dist/react.js"></script> |
|||
<script src="https://unpkg.com/react-dom@{{site.react_version}}/dist/react-dom.js"></script> |
|||
<script src="https://unpkg.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,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 = <div className="foo" />; |
|||
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 = <MyComponent someProperty={true} />; |
|||
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 = <Nav color="blue" />; |
|||
// Output (JS): |
|||
var app = React.createElement(Nav, {color:"blue"}); |
|||
``` |
|||
|
|||
Osserva che per utilizzare `<Nav />`, la variabile `Nav` deve essere visibile. |
|||
|
|||
JSX permette anche di specificare i figli usando una sintassi XML: |
|||
|
|||
```javascript |
|||
var Nav, Profile; |
|||
// Input (JSX): |
|||
var app = <Nav color="blue"><Profile>click</Profile></Nav>; |
|||
// Output (JS): |
|||
var app = React.createElement( |
|||
Nav, |
|||
{color:"blue"}, |
|||
React.createElement(Profile, null, "click") |
|||
); |
|||
``` |
|||
|
|||
JSX inferirà il [displayName](/react/docs/component-specs-it-IT.html#displayname) della classe dall'assegnazione delle variabile, quando il valore di displayName è indefinito: |
|||
|
|||
```javascript |
|||
// Input (JSX): |
|||
var Nav = React.createClass({ }); |
|||
// Output (JS): |
|||
var Nav = React.createClass({displayName: "Nav", }); |
|||
``` |
|||
|
|||
Usa la [REPL di Babel](https://babeljs.io/repl/) per provare il JSX e vedere come viene trasformato |
|||
in JavaScript nativo, e il |
|||
[convertitore da HTML a JSX](http://magic.reactjs.net/htmltojsx.htm) per convertire il tuo HTML esistente a |
|||
JSX. |
|||
|
|||
Se desideri utilizzare JSX, la guida [Primi Passi](/react/docs/getting-started-it-IT.html) ti mostra come impostare la compilazione. |
|||
|
|||
> Nota: |
|||
> |
|||
> L'espressione JSX viene sempre valutata come un ReactElement. Le implementazioni |
|||
> attuali potrebbero differire. Un modo ottimizzato potrebbe porre il |
|||
> ReactElement in linea come un oggetto letterale per evitare il codice di validazione in |
|||
> `React.createElement`. |
|||
|
|||
## Namespace dei Componenti |
|||
|
|||
Se stai costruendo un componente che ha parecchi figli, come ad esempio un modulo, potresti facilmente trovarti con una quantità di dichiarazioni di variabili: |
|||
|
|||
```javascript |
|||
// Imbarazzante blocco di dichiarazioni di variabili |
|||
var Form = MyFormComponent; |
|||
var FormRow = Form.Row; |
|||
var FormLabel = Form.Label; |
|||
var FormInput = Form.Input; |
|||
|
|||
var App = ( |
|||
<Form> |
|||
<FormRow> |
|||
<FormLabel /> |
|||
<FormInput /> |
|||
</FormRow> |
|||
</Form> |
|||
); |
|||
``` |
|||
|
|||
Per rendere tutto ciò più semplice e leggibile, *i componenti con un namespace* ti permettono di usare un componente che dispone di altri componenti come proprietà: |
|||
|
|||
```javascript |
|||
var Form = MyFormComponent; |
|||
|
|||
var App = ( |
|||
<Form> |
|||
<Form.Row> |
|||
<Form.Label /> |
|||
<Form.Input /> |
|||
</Form.Row> |
|||
</Form> |
|||
); |
|||
``` |
|||
|
|||
Per fare ciò, devi semplicemente creare i tuoi *"sub-componenti"* come proprietà del componente principale: |
|||
|
|||
```javascript |
|||
var MyFormComponent = React.createClass({ ... }); |
|||
|
|||
MyFormComponent.Row = React.createClass({ ... }); |
|||
MyFormComponent.Label = React.createClass({ ... }); |
|||
MyFormComponent.Input = React.createClass({ ... }); |
|||
``` |
|||
|
|||
JSX gestirà il tutto correttamente al momento di compilare il tuo codice. |
|||
|
|||
```javascript |
|||
var App = ( |
|||
React.createElement(Form, null, |
|||
React.createElement(Form.Row, null, |
|||
React.createElement(Form.Label, null), |
|||
React.createElement(Form.Input, null) |
|||
) |
|||
) |
|||
); |
|||
``` |
|||
|
|||
> Nota: |
|||
> |
|||
> Questa funzionalità è disponibile nella [v0.11](/react/blog/2014/07/17/react-v0.11.html#jsx) e successive. |
|||
|
|||
## Espressioni JavaScript |
|||
|
|||
### Expressioni come Attributi |
|||
|
|||
Per usare un'espressione JavaScript come valore di un attributo, racchiudi l'espressione in un paio |
|||
di parentesi graffe (`{}`) anziché doppi apici (`""`). |
|||
|
|||
```javascript |
|||
// Input (JSX): |
|||
var person = <Person name={window.isLoggedIn ? window.name : ''} />; |
|||
// Output (JS): |
|||
var person = React.createElement( |
|||
Person, |
|||
{name: window.isLoggedIn ? window.name : ''} |
|||
); |
|||
``` |
|||
|
|||
### Attributi Booleani |
|||
|
|||
Omettere il valore di un attributo fa in modo che JSX lo tratti come `true`. Per passare `false` occorre utilizzare un'espressione come attributo. Ciò capita spesso quando si usano elementi di moduli HTML, con attributi come `disabled`, `required`, `checked` e `readOnly`. |
|||
|
|||
```javascript |
|||
// Queste due forme sono equivalenti in JSX per disabilitare un bottone |
|||
<input type="button" disabled />; |
|||
<input type="button" disabled={true} />; |
|||
|
|||
// E queste due forme sono equivalenti in JSX per non disabilitare un bottone |
|||
<input type="button" />; |
|||
<input type="button" disabled={false} />; |
|||
``` |
|||
|
|||
### Expressioni per Figli |
|||
|
|||
Similmente, espressioni JavaScript possono essere utilizzate per rappresentare figli: |
|||
|
|||
```javascript |
|||
// Input (JSX): |
|||
var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>; |
|||
// Output (JS): |
|||
var content = React.createElement( |
|||
Container, |
|||
null, |
|||
window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login) |
|||
); |
|||
``` |
|||
|
|||
### Commenti |
|||
|
|||
È facile aggiungere commenti al tuo codice JSX; sono semplici espressioni JS. Devi soltanto prestare attenzione a porre `{}` attorno ai commenti quando ti trovi dentro la sezione figli di un tag. |
|||
|
|||
```javascript |
|||
var content = ( |
|||
<Nav> |
|||
{/* commento figlio, racchiuso in {} */} |
|||
<Person |
|||
/* commento |
|||
su più |
|||
righe */ |
|||
name={window.isLoggedIn ? window.name : ''} // fine del commento su una riga |
|||
/> |
|||
</Nav> |
|||
); |
|||
``` |
|||
|
|||
> NOTA: |
|||
> |
|||
> JSX è simile all'HTML, ma non esattamente identico. Consulta la guida [JSX gotchas](/react/docs/jsx-gotchas-it-IT.html) per le differenze fondamentali. |
@ -1,219 +0,0 @@ |
|||
--- |
|||
id: jsx-in-depth |
|||
title: JSXの深層 |
|||
permalink: docs/jsx-in-depth-ja-JP.html |
|||
prev: displaying-data-ja-JP.html |
|||
next: jsx-spread-ja_JP.html |
|||
--- |
|||
|
|||
[JSX](https://facebook.github.io/jsx/)はXMLに似たJavaScriptのシンタックスの拡張です。Reactでは、単純なJSXのシンタックスの変換を使うことができます。 |
|||
|
|||
## なぜJSXを使うのでしょうか? |
|||
|
|||
ReactでJSXの使用を強制されるわけではありません。生のJSを使うこともできます。しかし、JSXは簡潔で、木構造とReactの特性を定義しやすいシンタックスであるため、JSXを使うことをお勧めします。 |
|||
|
|||
デザイナーのようなカジュアルな開発者にとってはさらに馴染みやすいでしょう。 |
|||
|
|||
XMLにはバランスの取れた開始タグと終了タグという利益があります。このことで、関数がオブジェクトリテラルを呼んでいるのを読むよりも簡単に大きな木構造を作ることができます。 |
|||
|
|||
これはJavaScriptのセマンティックスを代替するものではありません。 |
|||
|
|||
## HTMLタグ対Reactコンポーネント |
|||
|
|||
ReactはHTMLタグ(文字列)とReactコンポーネント(クラス)の両方をレンダリングすることができます。 |
|||
|
|||
以下のようにJSXで小文字のタグ名を使用するだけで、HTMLタグをレンダリングできます。 |
|||
|
|||
```javascript |
|||
var myDivElement = <div className="foo" />; |
|||
ReactDOM.render(myDivElement, document.getElementById('example')); |
|||
``` |
|||
|
|||
以下のように大文字から始まるローカル変数を作成するだけで、Reactのコンポーネントをレンダリングできます。 |
|||
|
|||
```javascript |
|||
var MyComponent = React.createClass({/*...*/}); |
|||
var myElement = <MyComponent someProperty={true} />; |
|||
ReactDOM.render(myElement, document.getElementById('example')); |
|||
``` |
|||
|
|||
ReactのJSXは大文字と小文字を使うことで、ローカルのコンポーネントクラスとHTMLタグを識別する習慣があります。 |
|||
|
|||
> 注意: |
|||
> |
|||
> JSXはJavaScriptなので、 `class` や `for` といった識別子はXMLの属性名としては使用しません。代わりに、 ReactのDOMコンポーネントはDOMのプロパティ名がそれぞれ `className` や `htmlFor` といったものであることを期待します。 |
|||
|
|||
## The Transform |
|||
|
|||
ReactのJSXはXMLに似たシンタックスをネイティブなJavaScriptに変換します。XML要素や属性や子要素は `React.createElement` で渡される引数に変換されます。 |
|||
|
|||
```javascript |
|||
var Nav; |
|||
// 入力 (JSX): |
|||
var app = <Nav color="blue" />; |
|||
// 出力 (JS): |
|||
var app = React.createElement(Nav, {color:"blue"}); |
|||
``` |
|||
|
|||
`<Nav />` を使うためには、 `Nav` 変数がスコープの中にないといけないことに注意してください。 |
|||
|
|||
以下のように、JSXはXMLシンタックスを使うことで、細かな子要素の使用も許可します。 |
|||
|
|||
```javascript |
|||
var Nav, Profile; |
|||
// 入力 (JSX): |
|||
var app = <Nav color="blue"><Profile>click</Profile></Nav>; |
|||
// 出力 (JS): |
|||
var app = React.createElement( |
|||
Nav, |
|||
{color:"blue"}, |
|||
React.createElement(Profile, null, "click") |
|||
); |
|||
``` |
|||
|
|||
以下のように、displayNameがundefinedの時には、JSXはクラスの[displayName](/react/docs/component-specs.html#displayname)を変数の割り当てから予測します。 |
|||
|
|||
```javascript |
|||
// 入力 (JSX): |
|||
var Nav = React.createClass({ }); |
|||
// 出力 (JS): |
|||
var Nav = React.createClass({displayName: "Nav", }); |
|||
``` |
|||
|
|||
JSXを試し、どのようにネイティブなJavaScriptに変換されるか見るには、[JSX Compiler](/react/jsx-compiler.html)を、すでに存在するHTMLをJSXに変換するには[HTMLからJSXへのコンバーター](http://magic.reactjs.net/htmltojsx.htm)を使ってください。 |
|||
|
|||
JSXを使いたい場合は、[始めてみましょう](/react/docs/getting-started-ja-JP.html)というガイドがどのようにコンパイルを設定するか示してくれます。 |
|||
|
|||
> 注意: |
|||
> |
|||
> JSXという表現は常にReactElementを評価します。実際に実行する際の詳細はおそらく異なっているでしょう。最適化されたモードでは `React.createElement` のコードのバリデーションを避けるためにReactElementをオブジェクトリテラルとして配置するでしょう。 |
|||
|
|||
|
|||
## ネームスペース化されたコンポーネント |
|||
|
|||
formのように、たくさんの子要素を持つコンポーネントを構築する際には、以下のように多くの変数を宣言しなければいけないでしょう。 |
|||
|
|||
```javascript |
|||
// 変数宣言のあまりよくない部分 |
|||
var Form = MyFormComponent; |
|||
var FormRow = Form.Row; |
|||
var FormLabel = Form.Label; |
|||
var FormInput = Form.Input; |
|||
|
|||
var App = ( |
|||
<Form> |
|||
<FormRow> |
|||
<FormLabel /> |
|||
<FormInput /> |
|||
</FormRow> |
|||
</Form> |
|||
); |
|||
``` |
|||
|
|||
これを単純で簡単にするために、 *ネームスペース化されたコンポーネント* では、以下のように他のコンポーネントを付属物として持つ1つのコンポーネントを使うことができます。 |
|||
|
|||
```javascript |
|||
var Form = MyFormComponent; |
|||
|
|||
var App = ( |
|||
<Form> |
|||
<Form.Row> |
|||
<Form.Label /> |
|||
<Form.Input /> |
|||
</Form.Row> |
|||
</Form> |
|||
); |
|||
``` |
|||
|
|||
これを行うためには、以下のようにメインコンポーネントの付属物として、「サブコンポーネント」を作るだけで大丈夫です。 |
|||
|
|||
```javascript |
|||
var MyFormComponent = React.createClass({ ... }); |
|||
|
|||
MyFormComponent.Row = React.createClass({ ... }); |
|||
MyFormComponent.Label = React.createClass({ ... }); |
|||
MyFormComponent.Input = React.createClass({ ... }); |
|||
``` |
|||
|
|||
JSXはコードをコンパイルする際にこのプロパティをハンドルします。 |
|||
|
|||
```javascript |
|||
var App = ( |
|||
React.createElement(Form, null, |
|||
React.createElement(Form.Row, null, |
|||
React.createElement(Form.Label, null), |
|||
React.createElement(Form.Input, null) |
|||
) |
|||
) |
|||
); |
|||
``` |
|||
|
|||
> 注意: |
|||
> この特徴は [v0.11](/react/blog/2014/07/17/react-v0.11.html#jsx) 以上で使用できます。 |
|||
|
|||
## JavaScriptの表現 |
|||
|
|||
### アトリビュートの表現 |
|||
|
|||
JavaScriptで書いたものをアトリビュートの値として使うためには、その表現を引用(`""`)ではなく波括弧(`{}`)で囲ってください。 |
|||
|
|||
```javascript |
|||
// 入力 (JSX): |
|||
var person = <Person name={window.isLoggedIn ? window.name : ''} />; |
|||
// 出力 (JS): |
|||
var person = React.createElement( |
|||
Person, |
|||
{name: window.isLoggedIn ? window.name : ''} |
|||
); |
|||
``` |
|||
|
|||
### Booleanのアトリビュート |
|||
|
|||
アトリビュートの値を記述しないと、JSXはそれを `true` として扱ってしまいます。`false` を渡すためには、アトリビュートが使われる必要があります。これらはHTMLのform要素の `disabled` 、 `required` 、 `checked` 、 `readOnly` といったアトリビュートを使う際によく見かけられます。 |
|||
|
|||
|
|||
```javascript |
|||
// 以下の2つはボタンを使用不能にするという意味でJSXでは同義です。 |
|||
<input type="button" disabled />; |
|||
<input type="button" disabled={true} />; |
|||
|
|||
// 以下の2つはボタンを使用不能にしないという意味でJSXでは同義です。 |
|||
<input type="button" />; |
|||
<input type="button" disabled={false} />; |
|||
``` |
|||
|
|||
### 子要素の表現 |
|||
|
|||
同様に、JavaScriptは子要素を表現するのに使われることもあります。 |
|||
|
|||
```javascript |
|||
// 入力 (JSX): |
|||
var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>; |
|||
// 出力 (JS): |
|||
var content = React.createElement( |
|||
Container, |
|||
null, |
|||
window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login) |
|||
); |
|||
``` |
|||
|
|||
### コメント |
|||
|
|||
JSXにコメントを加えるのは簡単です。ただのJSの書き方です。タグの内側にコメントを書く時には、 `{}` で囲うことに注意してください。 |
|||
|
|||
```javascript |
|||
var content = ( |
|||
<Nav> |
|||
{/* 子要素にコメントを書く時には、 {} で囲う */} |
|||
<Person |
|||
/* 複数 |
|||
行 |
|||
コメント */ |
|||
name={window.isLoggedIn ? window.name : ''} // 行末コメント |
|||
/> |
|||
</Nav> |
|||
); |
|||
``` |
|||
|
|||
> 注意: |
|||
> JSXはHTMLに似ていますが、全く同じではありません。いくつかのキーの違いについては[JSXの理解](/react/docs/jsx-gotchas.html) をご覧ください。 |
@ -1,223 +0,0 @@ |
|||
--- |
|||
id: jsx-in-depth-ko-KR |
|||
title: JSX 깊이보기 |
|||
permalink: docs/jsx-in-depth-ko-KR.html |
|||
prev: displaying-data-ko-KR.html |
|||
next: jsx-spread-ko-KR.html |
|||
--- |
|||
|
|||
[JSX](https://facebook.github.io/jsx/)는 XML과 비슷한 JavaScript문법 확장입니다. React에서 변환되는 간단한 JSX 구문을 사용하실 수 있습니다. |
|||
|
|||
## 왜 JSX인가? |
|||
|
|||
React를 위해 꼭 JSX를 사용할 필요는 없고, 그냥 일반 JS를 사용할 수도 있습니만 JSX를 사용하기를 추천합니다. 왜냐하면, 어트리뷰트를 가진 트리 구조로 정의할 수 있는 간결하고 익숙한 문법이기 때문입니다. |
|||
|
|||
이것은 디자이너 같은 케쥬얼 개발자에게 더 익숙합니다. |
|||
|
|||
XML에는 여닫는 태그의 장점이 있습니다. 태그는 큰 트리일 때 함수 호출이나 객체 리터럴보다 읽기 쉬워 집니다. |
|||
|
|||
JSX는 JavaScript의 시맨틱을 변경하지 않습니다. |
|||
|
|||
## HTML 태그 vs. React 컴포넌트 |
|||
|
|||
React는 렌더 HTML 태그(문자열)이나 React 컴포넌트(클래스)일 수 있습니다. |
|||
|
|||
HTML 태그를 렌더하려면, 그냥 JSX에 소문자 태그를 사용하세요. |
|||
|
|||
```javascript |
|||
var myDivElement = <div className="foo" />; |
|||
ReactDOM.render(myDivElement, document.getElementById('example')); |
|||
``` |
|||
|
|||
React 컴포넌트를 렌더하려면, 대문자로 시작하는 로컬 변수를 만드세요. |
|||
|
|||
```javascript |
|||
var MyComponent = React.createClass({/*...*/}); |
|||
var myElement = <MyComponent someProperty={true} />; |
|||
ReactDOM.render(myElement, document.getElementById('example')); |
|||
``` |
|||
|
|||
React JSX는 대소문자를 로컬 컴포넌트 클래스와 HTML 태그를 구별하는 컨벤션으로 사용합니다. |
|||
|
|||
> 주의: |
|||
> |
|||
> JSX가 JavaScript기 때문에, `class`, `for`같은 식별자는 XML 어트리뷰트 이름으로 |
|||
> 권장하지 않습니다. 대신, React DOM 컴포넌트는 각각 `className`, `htmlFor`같은 |
|||
> DOM 프로퍼티 이름을 기대합니다. |
|||
|
|||
## 변환 |
|||
|
|||
React JSX는 XML같은 문법에서 네이티브 JavaScript로 변환됩니다. XML 엘리먼트, 어트리뷰트, 자식은 `React.createElement`에 넘겨지는 인자로 변환됩니다. |
|||
|
|||
```javascript |
|||
var Nav; |
|||
// 입력 (JSX): |
|||
var app = <Nav color="blue" />; |
|||
// 출력 (JS): |
|||
var app = React.createElement(Nav, {color:"blue"}); |
|||
``` |
|||
|
|||
`<Nav />`를 사용하려면, `Nav`변수는 스코프에 있어야 합니다. |
|||
|
|||
JSX에서는 XML 구문으로 자식을 지정할 수도 있습니다. |
|||
|
|||
```javascript |
|||
var Nav, Profile; |
|||
// 입력 (JSX): |
|||
var app = <Nav color="blue"><Profile>click</Profile></Nav>; |
|||
// 출력 (JS): |
|||
var app = React.createElement( |
|||
Nav, |
|||
{color:"blue"}, |
|||
React.createElement(Profile, null, "click") |
|||
); |
|||
``` |
|||
|
|||
클래스에 [displayName](/react/docs/component-specs-ko-KR.html#displayname)이 정의되어 있지 않으면 JSX는 변수명을 displayName으로 간주할 것입니다: |
|||
|
|||
```javascript |
|||
// 입력 (JSX): |
|||
var Nav = React.createClass({ }); |
|||
// 출력 (JS): |
|||
var Nav = React.createClass({displayName: "Nav", }); |
|||
``` |
|||
|
|||
[바벨 REPL](https://babeljs.io/repl/)를 보면 JSX에서 어떻게 네이티브 JavaScript로 변환(desugars)하는지 볼 수 있고, [HTML-JSX 변환기](http://magic.reactjs.net/htmltojsx.htm)는 이미 있는 HTML을 JSX로 변환해 줍니다. |
|||
|
|||
JSX를 사용 하시려면, [시작하기](/react/docs/getting-started-ko-KR.html) 가이드에서 어떻게 컴파일을 하기 위해 설정하는지 보실 수 있습니다. |
|||
|
|||
> 주의: |
|||
> |
|||
> JSX 표현식은 언제나 ReactElement로 변환됩니다. 실제 구현의 세부사항은 많이 |
|||
> 다를 수 있습니다. 최적화 모드는 ReactElement를 `React.createElement`에서 검증 |
|||
> 코드를 우회하는 객체 리터럴로 ReactElement를 인라인으로 만들 수 있습니다. |
|||
|
|||
## 네임스페이스를 사용한 컴포넌트 |
|||
|
|||
폼같은 자식을 많이 가지는 컴포넌트를 만든다면, 많은 변수 선언을 하게 될 것입니다. |
|||
|
|||
```javascript |
|||
// 변수 선언의 어색한 블록 |
|||
var Form = MyFormComponent; |
|||
var FormRow = Form.Row; |
|||
var FormLabel = Form.Label; |
|||
var FormInput = Form.Input; |
|||
|
|||
var App = ( |
|||
<Form> |
|||
<FormRow> |
|||
<FormLabel /> |
|||
<FormInput /> |
|||
</FormRow> |
|||
</Form> |
|||
); |
|||
``` |
|||
|
|||
더 간단하고 쉽게 *네임스페이스를 사용한 컴포넌트*를 사용해서, 다른 컴포넌트를 어트리뷰트로 가지는 하나의 컴포넌트만 쓸 수 있습니다. |
|||
|
|||
```javascript |
|||
var Form = MyFormComponent; |
|||
|
|||
var App = ( |
|||
<Form> |
|||
<Form.Row> |
|||
<Form.Label /> |
|||
<Form.Input /> |
|||
</Form.Row> |
|||
</Form> |
|||
); |
|||
``` |
|||
|
|||
이렇게 하려면, *"sub-components"*를 메인 컴포넌트의 어트리뷰트로 만들 필요가 있습니다. |
|||
|
|||
```javascript |
|||
var MyFormComponent = React.createClass({ ... }); |
|||
|
|||
MyFormComponent.Row = React.createClass({ ... }); |
|||
MyFormComponent.Label = React.createClass({ ... }); |
|||
MyFormComponent.Input = React.createClass({ ... }); |
|||
``` |
|||
|
|||
코드를 컴파일할 때 JSX는 이것을 제대로 처리해 줍니다. |
|||
|
|||
```javascript |
|||
var App = ( |
|||
React.createElement(Form, null, |
|||
React.createElement(Form.Row, null, |
|||
React.createElement(Form.Label, null), |
|||
React.createElement(Form.Input, null) |
|||
) |
|||
) |
|||
); |
|||
``` |
|||
|
|||
> 주의: |
|||
> |
|||
> 이 기능은 [v0.11](/react/blog/2014/07/17/react-v0.11.html#jsx) 이상에만 있습니다. |
|||
|
|||
## JavaScript 표현식 |
|||
|
|||
### 어트리뷰트 표현식 |
|||
|
|||
JavaScript 표현식을 어트리뷰트 값으로 사용하려면, 표현식을 쌍따옴표(`""`)대신 중괄호(`{}`)로 감싸야 합니다. |
|||
|
|||
```javascript |
|||
// 입력 (JSX): |
|||
var person = <Person name={window.isLoggedIn ? window.name : ''} />; |
|||
// 출력 (JS): |
|||
var person = React.createElement( |
|||
Person, |
|||
{name: window.isLoggedIn ? window.name : ''} |
|||
); |
|||
``` |
|||
|
|||
### 불린 어트리뷰트 |
|||
|
|||
어트리뷰트의 값을 생략하면 JSX는 값을 `true`로 취급합니다. 어트리뷰트 표현식에 `false`를 넘기려면 사용해야만 합니다. HTML 폼 엘리먼트에 `disabled`, `required`, `checked`, `readOnly`같은 어트리뷰트를 사용할 일이 자주 있습니다. |
|||
|
|||
```javascript |
|||
// JSX에서 이 두 줄은 똑같이 버튼을 비활성화합니다. |
|||
<input type="button" disabled />; |
|||
<input type="button" disabled={true} />; |
|||
|
|||
// 그리고 JSX에서 이 두 줄은 똑같이 버튼을 비활성화하지 않습니다. |
|||
<input type="button" />; |
|||
<input type="button" disabled={false} />; |
|||
``` |
|||
|
|||
### 자식 표현식 |
|||
|
|||
비슷하게, JavaScript 표현식을 자식을 표현하는 데 사용할 수 있습니다. |
|||
|
|||
```javascript |
|||
// 입력 (JSX): |
|||
var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>; |
|||
// 출력 (JS): |
|||
var content = React.createElement( |
|||
Container, |
|||
null, |
|||
window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login) |
|||
); |
|||
``` |
|||
|
|||
### 주석 |
|||
|
|||
JSX에 주석을 넣기는 쉽습니다. 그냥 JS 표현식과 같습니다. 그냥 태그의 자식 섹션에서만 조심하시면 됩니다. 이럴 땐 주석 주변에 `{}`를 감싸야 합니다. |
|||
|
|||
```javascript |
|||
var content = ( |
|||
<Nav> |
|||
{/* 자식 주석, {}로 감싼다 */} |
|||
<Person |
|||
/* 여러 |
|||
줄 |
|||
주석 */ |
|||
name={window.isLoggedIn ? window.name : ''} // 줄 끝부분 주석 |
|||
/> |
|||
</Nav> |
|||
); |
|||
``` |
|||
|
|||
> 주의: |
|||
> |
|||
> JSX 는 HTML과 비슷하지만 완전히 같지는 않습니다. 중요한 차이점을 보시려면 [JSX gotchas](/react/docs/jsx-gotchas-ko-KR.html)를 보세요. |
@ -1,224 +0,0 @@ |
|||
--- |
|||
id: jsx-in-depth |
|||
title: JSX in Depth |
|||
permalink: docs/jsx-in-depth.html |
|||
prev: displaying-data.html |
|||
next: jsx-spread.html |
|||
--- |
|||
|
|||
[JSX](https://facebook.github.io/jsx/) is a JavaScript syntax extension that looks similar to XML. You can use a simple JSX syntactic transform with React. |
|||
|
|||
## Why JSX? |
|||
|
|||
You don't have to use JSX with React. You can just use plain JS. However, we recommend using JSX because it is a concise and familiar syntax for defining tree structures with attributes. |
|||
|
|||
It's more familiar for casual developers such as designers. |
|||
|
|||
XML has the benefit of balanced opening and closing tags. This helps make large trees easier to read than function calls or object literals. |
|||
|
|||
It doesn't alter the semantics of JavaScript. |
|||
|
|||
## HTML Tags vs. React Components |
|||
|
|||
React can either render HTML tags (strings) or React components (classes). |
|||
|
|||
To render an HTML tag, just use lower-case tag names in JSX: |
|||
|
|||
```javascript |
|||
var myDivElement = <div className="foo" />; |
|||
ReactDOM.render(myDivElement, document.getElementById('example')); |
|||
``` |
|||
|
|||
To render a React Component, just create a local variable that starts with an upper-case letter: |
|||
|
|||
```javascript |
|||
var MyComponent = React.createClass({/*...*/}); |
|||
var myElement = <MyComponent someProperty={true} />; |
|||
ReactDOM.render(myElement, document.getElementById('example')); |
|||
``` |
|||
|
|||
React's JSX uses the upper vs. lower case convention to distinguish between local component classes and HTML tags. |
|||
|
|||
> Note: |
|||
> |
|||
> Since JSX is JavaScript, identifiers such as `class` and `for` are discouraged |
|||
> as XML attribute names. Instead, React DOM components expect DOM property |
|||
> names like `className` and `htmlFor`, respectively. |
|||
|
|||
## The Transform |
|||
|
|||
React JSX transforms from an XML-like syntax into native JavaScript. XML elements, attributes and children are transformed into arguments that are passed to `React.createElement`. |
|||
|
|||
```javascript |
|||
var Nav; |
|||
// Input (JSX): |
|||
var app = <Nav color="blue" />; |
|||
// Output (JS): |
|||
var app = React.createElement(Nav, {color:"blue"}); |
|||
``` |
|||
|
|||
Notice that in order to use `<Nav />`, the `Nav` variable must be in scope. |
|||
|
|||
JSX also allows specifying children using XML syntax: |
|||
|
|||
```javascript |
|||
var Nav, Profile; |
|||
// Input (JSX): |
|||
var app = <Nav color="blue"><Profile>click</Profile></Nav>; |
|||
// Output (JS): |
|||
var app = React.createElement( |
|||
Nav, |
|||
{color:"blue"}, |
|||
React.createElement(Profile, null, "click") |
|||
); |
|||
``` |
|||
|
|||
JSX will infer the class's [displayName](/react/docs/component-specs.html#displayname) from the variable assignment when the displayName is undefined: |
|||
|
|||
```javascript |
|||
// Input (JSX): |
|||
var Nav = React.createClass({ }); |
|||
// Output (JS): |
|||
var Nav = React.createClass({displayName: "Nav", }); |
|||
``` |
|||
|
|||
Use the [Babel REPL](https://babeljs.io/repl/) to try out JSX and see how it desugars into native JavaScript, and the [HTML to JSX converter](http://magic.reactjs.net/htmltojsx.htm) to convert your existing HTML to JSX. |
|||
|
|||
If you want to use JSX, the [Getting Started](/react/docs/getting-started.html) guide shows how to set up compilation. |
|||
|
|||
> Note: |
|||
> |
|||
> The JSX expression always evaluates to a ReactElement. The actual |
|||
> implementation details may vary. An optimized mode could inline the |
|||
> ReactElement as an object literal to bypass the validation code in |
|||
> `React.createElement`. |
|||
|
|||
## Namespaced Components |
|||
|
|||
If you are building a component that has many children, like a form, you might end up with something with a lot of variable declarations: |
|||
|
|||
```javascript |
|||
// Awkward block of variable declarations |
|||
var Form = MyFormComponent; |
|||
var FormRow = Form.Row; |
|||
var FormLabel = Form.Label; |
|||
var FormInput = Form.Input; |
|||
|
|||
var App = ( |
|||
<Form> |
|||
<FormRow> |
|||
<FormLabel /> |
|||
<FormInput /> |
|||
</FormRow> |
|||
</Form> |
|||
); |
|||
``` |
|||
|
|||
To make it simpler and easier, *namespaced components* let you use one component that has other components as attributes: |
|||
|
|||
```javascript |
|||
var Form = MyFormComponent; |
|||
|
|||
var App = ( |
|||
<Form> |
|||
<Form.Row> |
|||
<Form.Label /> |
|||
<Form.Input /> |
|||
</Form.Row> |
|||
</Form> |
|||
); |
|||
``` |
|||
|
|||
To do this, you just need to create your *"sub-components"* as attributes of the main component: |
|||
|
|||
```javascript |
|||
var MyFormComponent = React.createClass({ ... }); |
|||
|
|||
MyFormComponent.Row = React.createClass({ ... }); |
|||
MyFormComponent.Label = React.createClass({ ... }); |
|||
MyFormComponent.Input = React.createClass({ ... }); |
|||
``` |
|||
|
|||
JSX will handle this properly when compiling your code. |
|||
|
|||
```javascript |
|||
var App = ( |
|||
React.createElement(Form, null, |
|||
React.createElement(Form.Row, null, |
|||
React.createElement(Form.Label, null), |
|||
React.createElement(Form.Input, null) |
|||
) |
|||
) |
|||
); |
|||
``` |
|||
|
|||
> Note: |
|||
> |
|||
> This feature is available in [v0.11](/react/blog/2014/07/17/react-v0.11.html#jsx) and above. |
|||
|
|||
## JavaScript Expressions |
|||
|
|||
### Attribute Expressions |
|||
|
|||
To use a JavaScript expression as an attribute value, wrap the expression in a pair of curly braces (`{}`) instead of quotes (`""`). |
|||
|
|||
```javascript |
|||
// Input (JSX): |
|||
var person = <Person name={window.isLoggedIn ? window.name : ''} />; |
|||
// Output (JS): |
|||
var person = React.createElement( |
|||
Person, |
|||
{name: window.isLoggedIn ? window.name : ''} |
|||
); |
|||
``` |
|||
|
|||
### Boolean Attributes |
|||
|
|||
Omitting the value of an attribute causes JSX to treat it as `true`. To pass `false` an attribute expression must be used. This often comes up when using HTML form elements, with attributes like `disabled`, `required`, `checked` and `readOnly`. |
|||
|
|||
```javascript |
|||
// These two are equivalent in JSX for disabling a button |
|||
<input type="button" disabled />; |
|||
<input type="button" disabled={true} />; |
|||
|
|||
// And these two are equivalent in JSX for not disabling a button |
|||
<input type="button" />; |
|||
<input type="button" disabled={false} />; |
|||
``` |
|||
|
|||
### Child Expressions |
|||
|
|||
Likewise, JavaScript expressions may be used to express children: |
|||
|
|||
```javascript |
|||
// Input (JSX): |
|||
var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>; |
|||
// Output (JS): |
|||
var content = React.createElement( |
|||
Container, |
|||
null, |
|||
window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login) |
|||
); |
|||
``` |
|||
|
|||
### Comments |
|||
|
|||
It's easy to add comments within your JSX; they're just JS expressions. You just need to be careful to put `{}` around the comments when you are within the children section of a tag. |
|||
|
|||
```javascript |
|||
var content = ( |
|||
<Nav> |
|||
{/* child comment, put {} around */} |
|||
<Person |
|||
/* multi |
|||
line |
|||
comment */ |
|||
name={window.isLoggedIn ? window.name : ''} // end of line comment |
|||
/> |
|||
</Nav> |
|||
); |
|||
``` |
|||
|
|||
> NOTE: |
|||
> |
|||
> JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences. |
@ -1,224 +0,0 @@ |
|||
--- |
|||
id: jsx-in-depth-zh-CN |
|||
title: 深入 JSX |
|||
permalink: docs/jsx-in-depth-zh-CN.html |
|||
prev: displaying-data-zh-CN.html |
|||
next: jsx-spread-zh-CN.html |
|||
--- |
|||
|
|||
[JSX](https://facebook.github.io/jsx/) 是一个看起来很像 XML 的 JavaScript 语法扩展。React 可以用来做简单的 JSX 句法转换。 |
|||
|
|||
## 为什么要用 JSX? |
|||
|
|||
你不需要为了 React 使用 JSX,可以直接使用原生 JS。但是,我们建议使用 JSX 是因为它能精确,也是常用的定义包含属性的树状结构的语法。 |
|||
|
|||
它对于非专职开发者比如设计师也比较熟悉。 |
|||
|
|||
XML 有固定的标签开启和闭合的优点。这能让复杂的树更易于阅读,优于方法调用和对象字面量的形式。 |
|||
|
|||
它没有修改 JavaScript 语义。 |
|||
|
|||
|
|||
## HTML 标签对比 React 组件 |
|||
|
|||
React 可以渲染 HTML 标签 (strings) 或 React 组件 (classes)。 |
|||
|
|||
要渲染 HTML 标签,只需在 JSX 里使用小写字母的标签名。 |
|||
|
|||
```javascript |
|||
var myDivElement = <div className="foo" />; |
|||
ReactDOM.render(myDivElement, document.getElementById('example')); |
|||
``` |
|||
|
|||
要渲染 React 组件,只需创建一个大写字母开头的本地变量。 |
|||
|
|||
```javascript |
|||
var MyComponent = React.createClass({/*...*/}); |
|||
var myElement = <MyComponent someProperty={true} />; |
|||
ReactDOM.render(myElement, document.getElementById('example')); |
|||
``` |
|||
|
|||
React 的 JSX 使用大、小写的约定来区分本地组件的类和 HTML 标签。 |
|||
|
|||
> 注意: |
|||
> |
|||
> 由于 JSX 就是 JavaScript,一些标识符像 `class` 和 `for` 不建议作为 XML |
|||
> 属性名。作为替代,React DOM 使用 `className` 和 `htmlFor` 来做对应的属性。 |
|||
|
|||
## 转换(Transform) |
|||
|
|||
JSX 把类 XML 的语法转成原生 JavaScript,XML 元素、属性和子节点被转换成 `React.createElement` 的参数。 |
|||
|
|||
```javascript |
|||
var Nav; |
|||
// 输入 (JSX): |
|||
var app = <Nav color="blue" />; |
|||
// 输出 (JS): |
|||
var app = React.createElement(Nav, {color:"blue"}); |
|||
``` |
|||
|
|||
注意,要想使用 `<Nav />`,`Nav` 变量一定要在作用区间内。 |
|||
|
|||
JSX 也支持使用 XML 语法定义子结点: |
|||
|
|||
```javascript |
|||
var Nav, Profile; |
|||
// 输入 (JSX): |
|||
var app = <Nav color="blue"><Profile>click</Profile></Nav>; |
|||
// 输出 (JS): |
|||
var app = React.createElement( |
|||
Nav, |
|||
{color:"blue"}, |
|||
React.createElement(Profile, null, "click") |
|||
); |
|||
``` |
|||
|
|||
当显示名称没有定义时,JSX 会根据变量赋值来推断类的 [显示名称](/react/docs/component-specs.html#displayname) : |
|||
|
|||
```javascript |
|||
// 输入 (JSX): |
|||
var Nav = React.createClass({ }); |
|||
// 输出 (JS): |
|||
var Nav = React.createClass({displayName: "Nav", }); |
|||
``` |
|||
|
|||
使用 [JSX 编译器](/react/jsx-compiler.html) 来试用 JSX 并理解它是如何转换到原生 JavaScript,还有 [HTML 到 JSX 转换器](http://magic.reactjs.net/htmltojsx.htm) 来把现有 HTML 转成 JSX。 |
|||
|
|||
如果你要使用 JSX,这篇 [新手入门](/react/docs/getting-started.html) 教程来教你如何搭建环境。 |
|||
|
|||
> 注意: |
|||
> |
|||
> |
|||
> JSX 表达式总是会当作 ReactElement 执行。具体的实际细节可能不同。一种优化 |
|||
> 的模式是把 ReactElement 当作一个行内的对象字面量形式来绕过 |
|||
> `React.createElement` 里的校验代码。 |
|||
|
|||
## 命名组件(Namespaced Components) |
|||
|
|||
如果你正在构建一个有很多子组件的组件,比如表单,你也许会最终得到许多的变量声明。 |
|||
|
|||
```javascript |
|||
// 尴尬的变量声明块 |
|||
var Form = MyFormComponent; |
|||
var FormRow = Form.Row; |
|||
var FormLabel = Form.Label; |
|||
var FormInput = Form.Input; |
|||
|
|||
var App = ( |
|||
<Form> |
|||
<FormRow> |
|||
<FormLabel /> |
|||
<FormInput /> |
|||
</FormRow> |
|||
</Form> |
|||
); |
|||
``` |
|||
|
|||
为了使其更简单和容易,*命名组件*令你使用包含其他组件作为属性的单一的组件。 |
|||
|
|||
```javascript |
|||
var Form = MyFormComponent; |
|||
|
|||
var App = ( |
|||
<Form> |
|||
<Form.Row> |
|||
<Form.Label /> |
|||
<Form.Input /> |
|||
</Form.Row> |
|||
</Form> |
|||
); |
|||
``` |
|||
|
|||
要做到这一点,你只需要把你的*"子组件"*创建为主组件的属性。 |
|||
|
|||
```javascript |
|||
var MyFormComponent = React.createClass({ ... }); |
|||
|
|||
MyFormComponent.Row = React.createClass({ ... }); |
|||
MyFormComponent.Label = React.createClass({ ... }); |
|||
MyFormComponent.Input = React.createClass({ ... }); |
|||
``` |
|||
|
|||
当编译你的代码时,JSX会恰当的进行处理。 |
|||
|
|||
```javascript |
|||
var App = ( |
|||
React.createElement(Form, null, |
|||
React.createElement(Form.Row, null, |
|||
React.createElement(Form.Label, null), |
|||
React.createElement(Form.Input, null) |
|||
) |
|||
) |
|||
); |
|||
``` |
|||
|
|||
> 注意: |
|||
> |
|||
> 此特性在 [v0.11](/react/blog/2014/07/17/react-v0.11.html#jsx) 及以上可用. |
|||
|
|||
## JavaScript 表达式 |
|||
|
|||
### 属性表达式 |
|||
|
|||
要使用 JavaScript 表达式作为属性值,只需把这个表达式用一对大括号 (`{}`) 包起来,不要用引号 (`""`)。 |
|||
|
|||
```javascript |
|||
// 输入 (JSX): |
|||
var person = <Person name={window.isLoggedIn ? window.name : ''} />; |
|||
// 输出 (JS): |
|||
var person = React.createElement( |
|||
Person, |
|||
{name: window.isLoggedIn ? window.name : ''} |
|||
); |
|||
``` |
|||
|
|||
### Boolean 属性 |
|||
|
|||
省略一个属性的值会导致JSX把它当做 `true`。要传值 `false`必须使用属性表达式。这常出现于使用HTML表单元素,含有属性如`disabled`, `required`, `checked` 和 `readOnly`。 |
|||
|
|||
```javascript |
|||
// 在JSX中,对于禁用按钮这二者是相同的。 |
|||
<input type="button" disabled />; |
|||
<input type="button" disabled={true} />; |
|||
|
|||
// 在JSX中,对于不禁用按钮这二者是相同的。 |
|||
<input type="button" />; |
|||
<input type="button" disabled={false} />; |
|||
``` |
|||
|
|||
### 子节点表达式 |
|||
|
|||
同样地,JavaScript 表达式可用于描述子结点: |
|||
|
|||
```javascript |
|||
// 输入 (JSX): |
|||
var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>; |
|||
// 输出 (JS): |
|||
var content = React.createElement( |
|||
Container, |
|||
null, |
|||
window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login) |
|||
); |
|||
``` |
|||
|
|||
### 注释 |
|||
|
|||
JSX 里添加注释很容易;它们只是 JS 表达式而已。你仅仅需要小心的是当你在一个标签的子节点块时,要用 `{}` 包围要注释的部分。 |
|||
|
|||
```javascript |
|||
var content = ( |
|||
<Nav> |
|||
{/* child comment, 用 {} 包围 */} |
|||
<Person |
|||
/* 多 |
|||
行 |
|||
注释 */ |
|||
name={window.isLoggedIn ? window.name : ''} // 行尾注释 |
|||
/> |
|||
</Nav> |
|||
); |
|||
``` |
|||
|
|||
> 注意: |
|||
> |
|||
> JSX 类似于 HTML,但不完全一样。参考 [JSX 陷阱](/react/docs/jsx-gotchas-zh-CN.html) 了解主要不同。 |
@ -1,52 +0,0 @@ |
|||
--- |
|||
id: jsx-spread-it-IT |
|||
title: Attributi Spread JSX |
|||
permalink: docs/jsx-spread-it-IT.html |
|||
prev: jsx-in-depth-it-IT.html |
|||
next: jsx-gotchas-it-IT.html |
|||
--- |
|||
|
|||
Se sai in anticipo che tutte le proprietà che desideri assegnare ad un componente, usare JSX è facile: |
|||
|
|||
```javascript |
|||
var component = <Component foo={x} bar={y} />; |
|||
``` |
|||
|
|||
## Le Props Mutevoli sono il Male |
|||
|
|||
Se non sai quali proprietà desideri impostare, potresti essere tentato di aggiungerle all'oggetto in seguito: |
|||
|
|||
```javascript |
|||
var component = <Component />; |
|||
component.props.foo = x; // male |
|||
component.props.bar = y; // altrettanto male |
|||
``` |
|||
|
|||
Questo è un anti-pattern perché significa che non possiamo aiutarti a verificare i propTypes per tempo. Ciò significa che i tuoi errori di propTypes finiscono per avere uno stack trace indecifrabile. |
|||
|
|||
Le props dovrebbero essere considerate immutabili. Mutare l'oggetto props altrove potrebbe causare conseguenze inattese, quindi a questo punto dovrebbe essere idealmente considerato un oggetto congelato. |
|||
|
|||
## Attributi Spread |
|||
|
|||
Adesso puoi utilizzare una nuova caratteristica di JSX chiamata attributi spread: |
|||
|
|||
```javascript |
|||
var props = {}; |
|||
props.foo = x; |
|||
props.bar = y; |
|||
var component = <Component {...props} />; |
|||
``` |
|||
|
|||
Le proprietà dell'oggetto che passi al componente sono copiate nelle sue props. |
|||
|
|||
Puoi usarlo più volte o combinarlo con altri attributi. L'ordine in cui sono specificati è rilevante. Attributi successivi ridefiniscono quelli precedentemente impostati. |
|||
|
|||
```javascript |
|||
var props = { foo: 'default' }; |
|||
var component = <Component {...props} foo={'override'} />; |
|||
console.log(component.props.foo); // 'override' |
|||
``` |
|||
|
|||
## Cos'è la strana notazione `...`? |
|||
|
|||
L'operatore `...` (o operatore spread) è già supportato per gli [array in ES6](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). Esiste anche una proposta per ES7 per le proprietà [Spread e Rest di Object](https://github.com/sebmarkbage/ecmascript-rest-spread). Stiamo prendendo spunto da questi standard supportati o in corso di sviluppo per fornire una sintassi più pulita a JSX. |
@ -1,52 +0,0 @@ |
|||
--- |
|||
id: jsx-spread |
|||
title: JSXの拡張属性 |
|||
permalink: docs/jsx-spread-ja-JP.html |
|||
prev: jsx-in-depth-ja-JP.html |
|||
next: jsx-gotchas-ja-JP.html |
|||
--- |
|||
|
|||
以下のように、コンポーネントにどのようなプロパティを配置したいか前もって全て分かっている場合は、JSXを使うことは簡単です。 |
|||
|
|||
```javascript |
|||
var component = <Component foo={x} bar={y} />; |
|||
``` |
|||
|
|||
## Propsを変更してはいけない |
|||
|
|||
セットしたいプロパティが分からない場合は、以下のように後からオブジェクトに追加したいと思うでしょう。 |
|||
|
|||
```javascript |
|||
var component = <Component />; |
|||
component.props.foo = x; // だめ |
|||
component.props.bar = y; // 同様にだめ |
|||
``` |
|||
|
|||
これはアンチパターンです。なぜなら、後々まで正しいpropTypesであるかどうかチェックすることを助けることができないことを意味するからです。これは、propTypesのエラーが隠されたスタックトレースに出力されて終わってしまうことを意味します。 |
|||
|
|||
propsは変更不可と考えられるべきです。propsのオブジェクトをどこかで変更することは予期せぬ結果を発生させる可能性があるので、理想的には、この時点ではpropsは固定のオブジェクトであるべきです。 |
|||
|
|||
## 拡張属性 |
|||
|
|||
以下のように、拡張属性というJSXの新しい特徴を使うことができます。 |
|||
|
|||
```javascript |
|||
var props = {}; |
|||
props.foo = x; |
|||
props.bar = y; |
|||
var component = <Component {...props} />; |
|||
``` |
|||
|
|||
あなたが渡したオブジェクトのプロパティはコンポーネントのpropsにコピーされます。 |
|||
|
|||
これを複数回使用したり、他の属性と組み合わせたりすることもできます。仕様書では、順序が重要となっています。後の属性は前の属性をオーバーライドします。 |
|||
|
|||
```javascript |
|||
var props = { foo: 'default' }; |
|||
var component = <Component {...props} foo={'override'} />; |
|||
console.log(component.props.foo); // 'override' |
|||
``` |
|||
|
|||
## 奇妙な `...` という表現は何でしょうか? |
|||
|
|||
`...` 操作(拡張操作)は既に[ES6のarrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)でサポートされています。[Object Rest と Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread)のES7のプロポーザルもあります。JSXのきれいなシンタックスを供給するために、それらのサポートや開発中の標準使用を利用しています。 |
@ -1,52 +0,0 @@ |
|||
--- |
|||
id: jsx-spread-ko-KR |
|||
title: JSX 스프레드 어트리뷰트 |
|||
permalink: docs/jsx-spread-ko-KR.html |
|||
prev: jsx-in-depth-ko-KR.html |
|||
next: jsx-gotchas-ko-KR.html |
|||
--- |
|||
|
|||
미리 컴포넌트에 넣을 모든 프로퍼티를 알게 된다면, JSX를 사용하기 쉬워집니다. |
|||
|
|||
```javascript |
|||
var component = <Component foo={x} bar={y} />; |
|||
``` |
|||
|
|||
## Props의 변경은 나빠요 |
|||
|
|||
하지만 어떤 프로퍼티를 설정하고 싶은지 모른다면, 객체 레이어에 넣고 싶어질 수도 있습니다. |
|||
|
|||
```javascript |
|||
var component = <Component />; |
|||
component.props.foo = x; // 나쁨 |
|||
component.props.bar = y; // 역시 나쁨 |
|||
``` |
|||
|
|||
이것은 안티 패턴입니다. 왜냐하면 한참 뒤까지 정확한 propTypes을 체크할 수 없다는 뜻이기 때문입니다. 이것은 propTypes 에러는 알기 힘든 스택 트레이스로 끝난다는 의미입니다. |
|||
|
|||
props는 변하지 않는 것으로 간주해야 합니다. props 객체를 변경하는 것은 다른 곳에서 예기치 못한 결과가 생길 수 있기 때문에 이상적으로는 이 시점에서 frozen 객체가 되어야 합니다. |
|||
|
|||
## 스프레드 어트리뷰트 |
|||
|
|||
이제 JSX의 새로운 기능인 스프레드 어트리뷰트를 사용하실 수 있습니다. |
|||
|
|||
```javascript |
|||
var props = {}; |
|||
props.foo = x; |
|||
props.bar = y; |
|||
var component = <Component {...props} />; |
|||
``` |
|||
|
|||
전달한 객체의 프로퍼티가 컴포넌트의 props에 복사됩니다. |
|||
|
|||
이렇게 여러 번 사용하거나 다른 어트리뷰트와 조합해서 사용할 수 있습니다. 명세의 순서는 중요합니다. 나중의 어트리뷰트가 이전 것보다 우선되기 때문입니다. |
|||
|
|||
```javascript |
|||
var props = { foo: 'default' }; |
|||
var component = <Component {...props} foo={'override'} />; |
|||
console.log(component.props.foo); // 'override' |
|||
``` |
|||
|
|||
## 이상한 `...` 표기법은 무엇인가요? |
|||
|
|||
`...` 연산자(스프레드 연산자)는 이미 [ES6의 배열](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)에서 지원합니다. [객체 rest와 스프레드 프로퍼티](https://github.com/sebmarkbage/ecmascript-rest-spread)에 대한 ES7의 제안도 있습니다. JSX의 구문을 더 깔끔하게 하기 위해 지원되고 개발중인 표준을 활용하고 있습니다. |
@ -1,52 +0,0 @@ |
|||
--- |
|||
id: jsx-spread |
|||
title: JSX Spread Attributes |
|||
permalink: docs/jsx-spread.html |
|||
prev: jsx-in-depth.html |
|||
next: jsx-gotchas.html |
|||
--- |
|||
|
|||
If you know all the properties that you want to place on a component ahead of time, it is easy to use JSX: |
|||
|
|||
```javascript |
|||
var component = <Component foo={x} bar={y} />; |
|||
``` |
|||
|
|||
## Mutating Props is Bad |
|||
|
|||
If you don't know which properties you want to set, you might be tempted to add them onto the object later: |
|||
|
|||
```javascript |
|||
var component = <Component />; |
|||
component.props.foo = x; // bad |
|||
component.props.bar = y; // also bad |
|||
``` |
|||
|
|||
This is an anti-pattern because it means that we can't help you check the right propTypes until way later. This means that your propTypes errors end up with a cryptic stack trace. |
|||
|
|||
The props should be considered immutable. Mutating the props object somewhere else could cause unexpected consequences so ideally it would be a frozen object at this point. |
|||
|
|||
## Spread Attributes |
|||
|
|||
Now you can use a new feature of JSX called spread attributes: |
|||
|
|||
```javascript |
|||
var props = {}; |
|||
props.foo = x; |
|||
props.bar = y; |
|||
var component = <Component {...props} />; |
|||
``` |
|||
|
|||
The properties of the object that you pass in are copied onto the component's props. |
|||
|
|||
You can use this multiple times or combine it with other attributes. The specification order is important. Later attributes override previous ones. |
|||
|
|||
```javascript |
|||
var props = { foo: 'default' }; |
|||
var component = <Component {...props} foo={'override'} />; |
|||
console.log(component.props.foo); // 'override' |
|||
``` |
|||
|
|||
## What's with the weird `...` notation? |
|||
|
|||
The `...` operator (or spread operator) is already supported for [arrays in ES6](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). There is also an ECMAScript proposal for [Object Rest and Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread). We're taking advantage of these supported and developing standards in order to provide a cleaner syntax in JSX. |
@ -1,52 +0,0 @@ |
|||
--- |
|||
id: jsx-spread-zh-CN |
|||
title: JSX 展开属性 |
|||
permalink: docs/jsx-spread-zh-CN.html |
|||
prev: jsx-in-depth-zh-CN.html |
|||
next: jsx-gotchas-zh-CN.html |
|||
--- |
|||
|
|||
如果你事先知道组件需要的全部 Props(属性),JSX 很容易地这样写: |
|||
|
|||
```javascript |
|||
var component = <Component foo={x} bar={y} />; |
|||
``` |
|||
|
|||
## 修改 Props 是不好的,明白吗 |
|||
|
|||
如果你不知道要设置哪些 Props,那么现在最好不要设置它: |
|||
|
|||
```javascript |
|||
var component = <Component />; |
|||
component.props.foo = x; // 不好 |
|||
component.props.bar = y; // 同样不好 |
|||
``` |
|||
|
|||
这样是反模式,因为 React 不能帮你检查属性类型(propTypes)。这样即使你的 属性类型有错误也不能得到清晰的错误提示。 |
|||
|
|||
Props 应该被认为是不可变的。在别处修改 props 对象可能会导致预料之外的结果,所以原则上这将是一个冻结的对象。 |
|||
|
|||
## 展开属性(Spread Attributes) |
|||
|
|||
现在你可以使用 JSX 的新特性 - 展开属性: |
|||
|
|||
```javascript |
|||
var props = {}; |
|||
props.foo = x; |
|||
props.bar = y; |
|||
var component = <Component {...props} />; |
|||
``` |
|||
|
|||
传入对象的属性会被复制到组件内。 |
|||
|
|||
它能被多次使用,也可以和其它属性一起用。注意顺序很重要,后面的会覆盖掉前面的。 |
|||
|
|||
```javascript |
|||
var props = { foo: 'default' }; |
|||
var component = <Component {...props} foo={'override'} />; |
|||
console.log(component.props.foo); // 'override' |
|||
``` |
|||
|
|||
## 这个奇怪的 `...` 标记是什么? |
|||
|
|||
这个 `...` 操作符(增强的操作符)已经被 [ES6 数组](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator) 支持。相关的还有 ECMAScript 规范草案中的 [Object 剩余和展开属性(Rest and Spread Properties)](https://github.com/sebmarkbage/ecmascript-rest-spread)。我们利用了这些还在制定中标准中已经被支持的特性来使 JSX 拥有更优雅的语法。 |
@ -1,68 +0,0 @@ |
|||
--- |
|||
id: jsx-gotchas-it-IT |
|||
title: JSX Gotchas |
|||
permalink: docs/jsx-gotchas-it-IT.html |
|||
prev: jsx-spread-it-IT.html |
|||
next: interactivity-and-dynamic-uis-it-IT.html |
|||
--- |
|||
|
|||
JSX somiglia all'HTML ma ci sono delle differenze importanti da tenere in considerazione. |
|||
|
|||
> Nota: |
|||
> |
|||
> Per le differenze del DOM, come l'attributo `style` in linea, consulta [here](/react/docs/dom-differences-it-IT.html). |
|||
|
|||
## Entità HTML |
|||
|
|||
Puoi inserire entità HTML nel testo letterale in JSX: |
|||
|
|||
```javascript |
|||
<div>Primo · Secondo</div> |
|||
``` |
|||
|
|||
Se desideri visualizzare un'entità HTML all'interno di un contenuto dinamico, avrai problemi con il doppio escape, poiché React effettua in maniera predefinita l'escape di tutte le stringhe visualizzate per prevenire un'ampia gamma di attacchi XSS. |
|||
|
|||
```javascript |
|||
// Male: Mostra "Primo · Secondo" |
|||
<div>{'Primo · Secondo'}</div> |
|||
``` |
|||
|
|||
Esistono molte maniere di aggirare questo problema. La più facile è scrivere i caratteri Unicode direttamente in JavaScript. Dovrai assicurarti che il file sia salvato come UTF-8 e che le appropriate direttive UTF-8 siano impostate in modo che il browser li visualizzi correttamente. |
|||
|
|||
```javascript |
|||
<div>{'Primo · Secondo'}</div> |
|||
``` |
|||
|
|||
Un'alternativa più sicura consiste nel trovare il [codice Unicode corrispondente all'entità](http://www.fileformat.info/info/unicode/char/b7/index.htm) e usarlo all'interno di una stringa JavaScript. |
|||
|
|||
```javascript |
|||
<div>{'Primo \u00b7 Secondo'}</div> |
|||
<div>{'Primo ' + String.fromCharCode(183) + ' Secondo'}</div> |
|||
``` |
|||
|
|||
Puoi usare array misti con stringhe ed elementi JSX. |
|||
|
|||
```javascript |
|||
<div>{['Primo ', <span>·</span>, ' Secondo']}</div> |
|||
``` |
|||
|
|||
Come ultima risorsa, puoi sempre [inserire HTML nativo](/react/tips/dangerously-set-inner-html.html). |
|||
|
|||
```javascript |
|||
<div dangerouslySetInnerHTML={{'{{'}}__html: 'Primo · Secondo'}} /> |
|||
``` |
|||
|
|||
|
|||
## Attributi HTML Personalizzati |
|||
|
|||
Se passi proprietà che non esistono nella specifica HTML ad elementi HTML nativi, React li ignorerà. Se vuoi usare un attributo personalizzato, devi prefiggerlo con `data-`. |
|||
|
|||
```javascript |
|||
<div data-custom-attribute="foo" /> |
|||
``` |
|||
|
|||
Gli attributi per [l'Accessibilità del Web](http://www.w3.org/WAI/intro/aria) che iniziano per `aria-` saranno gestiti correttamente. |
|||
|
|||
```javascript |
|||
<div aria-hidden={true} /> |
|||
``` |
@ -1,68 +0,0 @@ |
|||
--- |
|||
id: jsx-gotchas |
|||
title: JSXの理解 |
|||
permalink: docs/jsx-gotchas-ja-JP.html |
|||
prev: jsx-spread-ja-JP.html |
|||
next: interactivity-and-dynamic-uis-ja-JP.html |
|||
|
|||
--- |
|||
|
|||
JSXはHTMLに似ていますが、重要な違いがいくつかあります。 |
|||
|
|||
> 注意: |
|||
> インラインの `style` 属性のようなDOMの違いについては、[こちら](/react/docs/dom-differences.html)を確認してください。 |
|||
|
|||
## HTMLのエンティティ |
|||
|
|||
以下のように、JSXの文字のテキストの中にHTMLのエンティティを挿入することができます。 |
|||
|
|||
```javascript |
|||
<div>First · Second</div> |
|||
``` |
|||
|
|||
動的なコンテンツとしてHTMLのエンティティを表示する際に、ダブルエスケープを書いてしまうことがあるかと思いますが、Reactはデフォルトで広い範囲のXSS攻撃を防ぐために表示しようとしている全ての文字列をエスケープします。 |
|||
|
|||
```javascript |
|||
// 悪い例: 以下は "First · Second" を表示します。 |
|||
<div>{'First · Second'}</div> |
|||
``` |
|||
|
|||
この問題を防止するためにはいくつかの方法があります。最も簡単な方法は、unicodeの文字を直でJavaScriptに記述する方法です。その際には、ファイルがUTF-8で保存されていることと、ブラウザが正しく表示できるように、UTF-8で表示する命令が正しくセットされていることを確認してください。 |
|||
|
|||
```javascript |
|||
<div>{'First · Second'}</div> |
|||
``` |
|||
|
|||
さらに安全な代替の方法は、[エンティティに対応するunicodeの数値](http://www.fileformat.info/info/unicode/char/b7/index.htm)を見つけて、JavaScriptの文字列の中でそれを使うことです。 |
|||
|
|||
```javascript |
|||
<div>{'First \u00b7 Second'}</div> |
|||
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div> |
|||
``` |
|||
|
|||
配列と文字列とJSXの要素を混ぜて使うこともできます。 |
|||
|
|||
```javascript |
|||
<div>{['First ', <span>·</span>, ' Second']}</div> |
|||
``` |
|||
|
|||
最後の手段として、常に[生のHTMLを挿入](/react/tips/dangerously-set-inner-html.html)することもできます。 |
|||
|
|||
```javascript |
|||
<div dangerouslySetInnerHTML={{'{{'}}__html: 'First · Second'}} /> |
|||
``` |
|||
|
|||
|
|||
## カスタムされたHTMLの属性 |
|||
|
|||
HTMLの仕様書に存在しない要素をネイティブなHTML要素に渡した場合は、Reactはそれらをレンダリングしません。カスタムした属性を使う場合は、 `data-` を頭につけてください。 |
|||
|
|||
```javascript |
|||
<div data-custom-attribute="foo" /> |
|||
``` |
|||
|
|||
`aria-` から始まる[Webアクセシビリティ](http://www.w3.org/WAI/intro/aria)属性はプロパティをレンダリングします。 |
|||
|
|||
```javascript |
|||
<div aria-hidden={true} /> |
|||
``` |
@ -1,68 +0,0 @@ |
|||
--- |
|||
id: jsx-gotchas-ko-KR |
|||
title: JSX Gotchas |
|||
permalink: docs/jsx-gotchas-ko-KR.html |
|||
prev: jsx-spread-ko-KR.html |
|||
next: interactivity-and-dynamic-uis-ko-KR.html |
|||
--- |
|||
|
|||
JSX는 HTML처럼 보이지만, 작업하다 보면 마주치게 될 몇 가지 중요한 차이점이 있습니다. |
|||
|
|||
> 주의: |
|||
> |
|||
> 인라인 `style` 어트리뷰트 같은 DOM과의 차이점은 [여기](/react/tips/dangerously-set-inner-html-ko-KR.html)를 보세요. |
|||
|
|||
## HTML 엔티티 |
|||
|
|||
JSX의 리터럴 텍스트에 HTML 엔티티를 넣을 수 있습니다. |
|||
|
|||
```javascript |
|||
<div>First · Second</div> |
|||
``` |
|||
|
|||
동적 콘텐츠 안에 HTML 엔티티를 표시하려 할 때, React에서는 XSS 공격을 광범위하게 막기 위해서 기본적으로 모든 표시하는 문자열을 이스케이프 하기 때문에 더블 이스케이프 문제에 부딪히게 됩니다. |
|||
|
|||
```javascript |
|||
// 나쁨: "First · Second"를 표시 |
|||
<div>{'First · Second'}</div> |
|||
``` |
|||
|
|||
이 이슈를 피해 갈 방법은 여럿 있지만, 가장 쉬운 방법은 유니코드 문자를 JavaScript에 직접 쓰는 것입니다. 브라우저가 올바르게 표시하도록 파일이 UTF-8으로 저장되어 있고 올바른 UTF-8 지시자를 사용하고 있는지 확인해야 합니다. |
|||
|
|||
```javascript |
|||
<div>{'First · Second'}</div> |
|||
``` |
|||
|
|||
더 안전한 대안으로 [엔티티에 대응하는 유니코드 숫자](http://www.fileformat.info/info/unicode/char/b7/index.htm)를 찾아 JavaScript 문자열 안에서 사용하는 방법도 있습니다. |
|||
|
|||
```javascript |
|||
<div>{'First \u00b7 Second'}</div> |
|||
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div> |
|||
``` |
|||
|
|||
문자열과 JSX 엘리먼트를 혼합한 배열을 사용할 수도 있습니다. |
|||
|
|||
```javascript |
|||
<div>{['First ', <span>·</span>, ' Second']}</div> |
|||
``` |
|||
|
|||
최후의 수단으로, 항상 [생 HTML을 삽입](/react/docs/dom-differences-ko-KR.html)할 수 있습니다. |
|||
|
|||
```javascript |
|||
<div dangerouslySetInnerHTML={{'{{'}}__html: 'First · Second'}} /> |
|||
``` |
|||
|
|||
|
|||
## 커스텀 HTML 어트리뷰트 |
|||
|
|||
프로퍼티를 HTML 사양에는 없는 네이티브 HTML 엘리먼트에 넘기면, React는 그 프로퍼티를 렌더하지 않습니다. 커스텀 어트리뷰트를 사용하고 싶다면, 접두사로 `data-`를 붙이셔야 합니다. |
|||
|
|||
```javascript |
|||
<div data-custom-attribute="foo" /> |
|||
``` |
|||
|
|||
`aria-`로 시작하는 [Web 접근성](http://www.w3.org/WAI/intro/aria) 어트리뷰트는 제대로 렌더될 것입니다. |
|||
|
|||
```javascript |
|||
<div aria-hidden={true} /> |
|||
``` |
@ -1,74 +0,0 @@ |
|||
--- |
|||
id: jsx-gotchas |
|||
title: JSX Gotchas |
|||
permalink: docs/jsx-gotchas.html |
|||
prev: jsx-spread.html |
|||
next: interactivity-and-dynamic-uis.html |
|||
--- |
|||
|
|||
JSX looks like HTML but there are some important differences you may run into. |
|||
|
|||
> Note: |
|||
> |
|||
> For DOM differences, such as the inline `style` attribute, check [here](/react/docs/dom-differences.html). |
|||
|
|||
## HTML Entities |
|||
|
|||
You can insert HTML entities within literal text in JSX: |
|||
|
|||
```javascript |
|||
<div>First · Second</div> |
|||
``` |
|||
|
|||
If you want to display an HTML entity within dynamic content, you will run into double escaping issues as React escapes all the strings you are displaying in order to prevent a wide range of XSS attacks by default. |
|||
|
|||
```javascript |
|||
// Bad: It displays "First · Second" |
|||
<div>{'First · Second'}</div> |
|||
``` |
|||
|
|||
There are various ways to work-around this issue. The easiest one is to write Unicode characters directly in JavaScript. You need to make sure that the file is saved as UTF-8 and that the proper UTF-8 directives are set so the browser will display it correctly. |
|||
|
|||
```javascript |
|||
<div>{'First · Second'}</div> |
|||
``` |
|||
|
|||
A safer alternative is to find the [unicode number corresponding to the entity](http://www.fileformat.info/info/unicode/char/b7/index.htm) and use it inside of a JavaScript string. |
|||
|
|||
```javascript |
|||
<div>{'First \u00b7 Second'}</div> |
|||
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div> |
|||
``` |
|||
|
|||
You can use mixed arrays with strings and JSX elements. Each JSX element in the array needs a unique key. |
|||
|
|||
```javascript |
|||
<div>{['First ', <span key="middot">·</span>, ' Second']}</div> |
|||
``` |
|||
|
|||
As a last resort, you always have the ability to [insert raw HTML](/react/tips/dangerously-set-inner-html.html). |
|||
|
|||
```javascript |
|||
<div dangerouslySetInnerHTML={{'{{'}}__html: 'First · Second'}} /> |
|||
``` |
|||
|
|||
|
|||
## Custom HTML Attributes |
|||
|
|||
If you pass properties to native HTML elements that do not exist in the HTML specification, React will not render them. If you want to use a custom attribute, you should prefix it with `data-`. |
|||
|
|||
```javascript |
|||
<div data-custom-attribute="foo" /> |
|||
``` |
|||
|
|||
However, arbitrary attributes are supported on custom elements (those with a hyphen in the tag name or an `is="..."` attribute). |
|||
|
|||
```javascript |
|||
<x-my-component custom-attribute="foo" /> |
|||
``` |
|||
|
|||
[Web Accessibility](http://www.w3.org/WAI/intro/aria) attributes starting with `aria-` will be rendered properly. |
|||
|
|||
```javascript |
|||
<div aria-hidden={true} /> |
|||
``` |
@ -1,74 +0,0 @@ |
|||
--- |
|||
id: jsx-gotchas-zh-CN |
|||
title: JSX 陷阱 |
|||
permalink: docs/jsx-gotchas-zh-CN.html |
|||
prev: jsx-spread-zh-CN.html |
|||
next: interactivity-and-dynamic-uis-zh-CN.html |
|||
--- |
|||
|
|||
JSX 与 HTML 非常相似,但是有些关键区别要注意。 |
|||
|
|||
> 注意: |
|||
> |
|||
> 关于 DOM 的区别,如行内样式属性 `style`,参考 [DOM 区别](/react/docs/dom-differences.html) |
|||
|
|||
## HTML 实体 |
|||
|
|||
HTML 实体可以插入到 JSX 的文本中。 |
|||
|
|||
```javascript |
|||
<div>First · Second</div> |
|||
``` |
|||
|
|||
如果想在 JSX 表达式中显示 HTML 实体,可以会遇到二次转义的问题,因为 React 默认会转义所有字符串,为了防止各种 XSS 攻击。 |
|||
|
|||
```javascript |
|||
// 错误: 会显示 “First · Second” |
|||
<div>{'First · Second'}</div> |
|||
``` |
|||
|
|||
有多种绕过的方法。最简单的是直接用 Unicode 字符。这时要确保文件是 UTF-8 编码且网页也指定为 UTF-8 编码。 |
|||
|
|||
```javascript |
|||
<div>{'First · Second'}</div> |
|||
``` |
|||
|
|||
安全的做法是先找到 [实体的 Unicode 编号](http://www.fileformat.info/info/unicode/char/b7/index.htm) ,然后在 JavaScript 字符串里使用。 |
|||
|
|||
```javascript |
|||
<div>{'First \u00b7 Second'}</div> |
|||
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div> |
|||
``` |
|||
|
|||
可以在数组里混合使用字符串和 JSX 元素。 |
|||
|
|||
```javascript |
|||
<div>{['First ', <span>·</span>, ' Second']}</div> |
|||
``` |
|||
|
|||
万不得已,可以直接[插入原始HTML](/react/tips/dangerously-set-inner-html.html)。 |
|||
|
|||
```javascript |
|||
<div dangerouslySetInnerHTML={{'{{'}}__html: 'First · Second'}} /> |
|||
``` |
|||
|
|||
|
|||
## 自定义 HTML 属性 |
|||
|
|||
如果往原生 HTML 元素里传入 HTML 规范里不存在的属性,React 不会显示它们。如果需要使用自定义属性,要加 `data-` 前缀。 |
|||
|
|||
```javascript |
|||
<div data-custom-attribute="foo" /> |
|||
``` |
|||
|
|||
然而,在自定义元素中任意的属性都是被支持的 (那些在tag名里带有连接符或者 `is="..."` 属性的) |
|||
|
|||
```javascript |
|||
<x-my-component custom-attribute="foo" /> |
|||
``` |
|||
|
|||
以 `aria-` 开头的 [网络无障碍](http://www.w3.org/WAI/intro/aria) 属性可以正常使用。 |
|||
|
|||
```javascript |
|||
<div aria-hidden={true} /> |
|||
``` |
@ -1,84 +0,0 @@ |
|||
--- |
|||
id: interactivity-and-dynamic-uis-it-IT |
|||
title: Interattività e UI Dinamiche |
|||
permalink: docs/interactivity-and-dynamic-uis-it-IT.html |
|||
prev: jsx-gotchas-it-IT.html |
|||
next: multiple-components-it-IT.html |
|||
--- |
|||
|
|||
Hai già [imparato a mostrare dati](/react/docs/displaying-data-it-IT.html) con React. Adesso vediamo come rendere le nostre UI interattive. |
|||
|
|||
|
|||
## Un Esempio Semplice |
|||
|
|||
```javascript |
|||
var LikeButton = React.createClass({ |
|||
getInitialState: function() { |
|||
return {liked: false}; |
|||
}, |
|||
handleClick: function(event) { |
|||
this.setState({liked: !this.state.liked}); |
|||
}, |
|||
render: function() { |
|||
var text = this.state.liked ? 'mi piace' : 'non mi piace'; |
|||
return ( |
|||
<p onClick={this.handleClick}> |
|||
You {text} this. Click to toggle. |
|||
</p> |
|||
); |
|||
} |
|||
}); |
|||
|
|||
ReactDOM.render( |
|||
<LikeButton />, |
|||
document.getElementById('example') |
|||
); |
|||
``` |
|||
|
|||
|
|||
## Gestione degli Eventi ed Eventi Sintetici |
|||
|
|||
Con React devi semplicemente passare il tuo gestore di eventi come una proprietà camelCased in modo simile a come faresti nel normale HTML. React si assicura che tutti gli eventi si comportano in maniera identica in IE8 e successivi implementando un sistema di eventi sintetici. Ovvero, React sa come propagare e catturare eventi secondo la specifica, e garantisce che gli eventi passati ai tuoi gestori di eventi siano consistenti con la [specifica W3C](http://www.w3.org/TR/DOM-Level-3-Events/), qualunque browser tu stia utilizzando. |
|||
|
|||
|
|||
## Dietro le Quinte: Binding Automatico e Delega degli Eventi |
|||
|
|||
Dietro le quinte, React esegue alcune operazioni per mantenere il tuo codice ad alte prestazioni e facile da comprendere. |
|||
|
|||
**Binding automatico:** Quando crei le callback in JavaScript, solitamente devi fare il binding esplicito del metodo alla sua istanza, in modo che il valore di `this` sia corretto. Con React, ogni metodo è automaticamente legato alla propria istanza del componente (eccetto quando si usa la sintassi delle classi ES6). React immagazzina il metodo legato in maniera tale da essere estremamente efficiente in termini di CPU e memoria. Ti permette anche di scrivere meno codice! |
|||
|
|||
**Delega degli eventi:** React non associa realmente i gestori di eventi ai nodi stessi. Quando React si avvia, comincia ad ascoltare tutti gli eventi a livello globale usando un singolo event listener. Quando un componente viene montato o smontato, i gestori di eventi sono semplicemente aggiunti o rimossi da un mapping interno. Quando si verifica un evento, React sa come inoltrarlo utilizzando questo mapping. Quando non ci sono più gestori di eventi rimasti nel mapping, i gestori di eventi di React sono semplici operazioni fittizie. Per saperne di più sul perché questo approccio è veloce, leggi [l'eccellente articolo sul blog di David Walsh](http://davidwalsh.name/event-delegate). |
|||
|
|||
|
|||
## I Componenti Sono Macchine a Stati Finiti |
|||
|
|||
React considera le UI come semplici macchine a stati finiti. Pensando alla UI come in uno di tanti stati diversi e visualizzando questi stati, è facile mantenere la UI consistente. |
|||
|
|||
In React, aggiorni semplicemente lo stato di un componente, e quindi visualizzi una nuova UI basata su questo nuovo stato. React si occupa di aggiornare il DOM al tuo posto nella maniera più efficiente. |
|||
|
|||
|
|||
## Come Funziona lo Stato |
|||
|
|||
Una maniera comune di informare React di un cambiamento nei dati è chiamare `setState(data, callback)`. Questo metodo effettua il merge di `data` in `this.state` e ridisegna il componente. Quando il componente ha terminato la fase di ri-rendering, la `callback` opzionale viene invocata. Nella maggior parte dei casi non avrai bisogno di fornire una `callback` dal momento che React si occuperà di mantenere la UI aggiornata per te. |
|||
|
|||
|
|||
## Quali Componenti Devono Avere uno Stato? |
|||
|
|||
La maggior parte dei tuoi componenti dovrebbero semplicemente ricevere dei dati da `props` e visualizzarli. Tuttavia, a volte hai bisogno di reagire all'input dell'utente, una richiesta al server o il trascorrere del tempo. In questi casi utilizzi lo stato. |
|||
|
|||
**Prova a mantenere il maggior numero possibile dei tuoi componenti privi di stato.** Facendo ciò, isolerai lo stato nel suo luogo logicamente corretto e minimizzerai la ridondanza, rendendo più semplice ragionare sulla tua applicazione. |
|||
|
|||
Un pattern comune è quello di creare diversi componenti privi di stato che mostrano semplicemente dati, e di avere un componente dotato di stato al di sopra di essi nella gerarchia, che passa il proprio stato ai suoi figli tramite le `props`. Il componente dotato di stato incapsula tutta la logica di interazione, mentre i componenti privi di stato si occupano della visualizzazione dei dati in maniera dichiarativa. |
|||
|
|||
|
|||
## Cosa *Dovrebbe* Contenere lo Stato? |
|||
|
|||
**Lo stato dovrebbe contenere dati che i gestori di eventi del componente possono modificare per scatenare un aggiornamento della UI.** In applicazioni reali, questi dati tendono ad essere molto limitati e serializzabili come JSON. Quando costruisci un componente dotato di stato, pensa alla minima rappresentazione possibile del suo stato, e conserva solo quelle proprietà in `this.state`. All'interno di `render()` calcola quindi ogni altra informazione necessaria basandoti sullo stato. Ti accorgerai che pensare e scrivere applicazioni in questo modo porta alla scrittura dell'applicazione più corretta, dal momento che aggiungere valori ridondanti o calcolati allo stato significherebbe doverli mantenere sincronizzati esplicitamente, anziché affidarti a React perché li calcoli al tuo posto. |
|||
|
|||
## Cosa *Non Dovrebbe* Contenere lo Stato? |
|||
|
|||
`this.state` dovrebbe contenere soltanto la quantità minima di dati indispensabile a rappresentare lo stato della tua UI. In quanto tale, non dovrebbe contenere: |
|||
|
|||
* **Dati calcolati:** Non preoccuparti di precalcolare valori basati sullo stato — è più semplice assicurarti che la tua UI sia consistente se effettui tutti i calcoli all'interno di `render()`. Per esempio, se lo stato contiene un array di elementi di una lista, e vuoi mostrare il numero di elementi come stringa, mostra semplicemente `this.state.listItems.length + ' elementi nella lista'` nel tuo metodo `render()` anziché conservarlo nello stato. |
|||
* **Componenti React:** Costruiscili in `render()` basandoti sulle proprietà e sullo stato del componente. |
|||
* **Dati duplicati dalle proprietà:** Prova ad utilizzare le proprietà come fonte di verità ove possibile. Un uso valido dello stato per i valori delle proprietà è conservarne il valore precedente quando le proprietà cambiano nel tempo. |
@ -1,84 +0,0 @@ |
|||
--- |
|||
id: interactivity-and-dynamic-uis |
|||
title: 相互作用と動的なUI |
|||
permalink: docs/interactivity-and-dynamic-uis-ja-JP.html |
|||
prev: jsx-gotchas-ja-JP.html |
|||
next: multiple-components-ja-JP.html |
|||
--- |
|||
|
|||
Reactで[どうやってデータを表示するか](/react/docs/displaying-data-ja-JP.html)については既に学んでいます。これからは、どうやって相互に作用するUIを作成するかを見ていきましょう。 |
|||
|
|||
|
|||
## 単純な例 |
|||
|
|||
```javascript |
|||
var LikeButton = React.createClass({ |
|||
getInitialState: function() { |
|||
return {liked: false}; |
|||
}, |
|||
handleClick: function(event) { |
|||
this.setState({liked: !this.state.liked}); |
|||
}, |
|||
render: function() { |
|||
var text = this.state.liked ? 'liked' : 'haven\'t liked'; |
|||
return ( |
|||
<p onClick={this.handleClick}> |
|||
You {text} this. Click to toggle. |
|||
</p> |
|||
); |
|||
} |
|||
}); |
|||
|
|||
ReactDOM.render( |
|||
<LikeButton />, |
|||
document.getElementById('example') |
|||
); |
|||
``` |
|||
|
|||
|
|||
## イベントハンドリングとイベントの組み合わせ |
|||
|
|||
Reactでは、普通のHTMLで行っているように単純にキャメルケースのpropとしてイベントハンドラを渡します。ReactはIE8と同じように全てのイベントが動作することと、組み合わされたイベントシステムが実行されることを保証します。これは、Reactが、イベントがどのように発生して、仕様にそってそれをキャプチャする方法を知っていることと、イベントはイベントハンドラに渡されて、どのブラウザを使っていても、[W3Cの仕様](http://www.w3.org/TR/DOM-Level-3-Events/)と一致することを保証することを意味します。 |
|||
|
|||
## 中身を見る: オートバインディングとイベントの委譲 |
|||
|
|||
中身を見ていくと、Reactはコードの性能と、理解しやすさを保つためにいくつかのことを行っています。 |
|||
|
|||
**オートバインディング:** JavaScriptでコールバックを作成するときには、普通は `this` の値が正しくなるように、インスタンスにメソッドをはっきりとバインドする必要があります。 |
|||
Reactでは、全てのメソッドが自動でコンポーネントのインスタンスにバインドされます。ReactはCPUとメモリを効率的に使えるように、バインドするメソッドを持っています。これによって、タイピングの量を少なくすることもできます! |
|||
|
|||
**イベントの委譲:** Reactは実際はノード自体にイベントハンドラをアタッチはしません。Reactを立ち上げる時、1つのイベントリスナを使って最上位で全てのイベントをリスニングし始めます。コンポーネントがマウントされたり、アンマウントされた時は、イベントハンドラは内部のマッピングを単純に加えたり減らしたりします。イベントが起こった時には、Reactはこのマッピングを使ってどのようにディスパッチするかを知っています。マッピングの中にイベントハンドラが無い場合は、Reactのイベントハンドラは何も行いません。なぜこれの速度が速いかについて詳しく知るためには、[David Walshの素晴らしいブログの投稿](http://davidwalsh.name/event-delegate)をご覧ください。 |
|||
|
|||
## コンポーネントは静的なマシーンに過ぎない |
|||
|
|||
ReactはUIをただの静的なマシーンと考えます。UIがたくさんのstateの中にあり、それらのstateをレンダリングするものだと考えることで、UIの一貫性を保ちやすくなります。 |
|||
|
|||
Reactでは、コンポーネントのstateをアップデートするだけで、新しいstateに基づいた新しいUIをレンダリングします。Reactは最も効率的な方法でDOMをアップデートする面倒を見てくれます。 |
|||
|
|||
|
|||
## どのようにStateが働くか |
|||
|
|||
Reactがデータの変更を通知する共通な方法は `setState(data, callback)` を呼ぶことです。このメソッドは `data` を `this.state` にマージし、コンポーネントを再度レンダリングします。コンポーネントが再度レンダリングし終わったら、オプションの `callback` が呼ばれます。ほとんどの場合、 `callback` を提供する必要はありません。ReactがUIを最新に保ってくれるからです。 |
|||
|
|||
|
|||
## どのコンポーネントがStateを持っているべきでしょうか? |
|||
|
|||
コンポーネントは単純に `props` からデータを取得し、レンダリングすべきです。しかし、時々、ユーザのインプットやサーバのリクエストや、時間の経過に反応する必要が有ります。このような場合にstateを使うのです。 |
|||
|
|||
**コンポーネントの多くを、可能な限りステートレスに保つよう試みてください。** このようにすることで、stateを最もロジックに近い場所から離し、冗長性を減らすことができ、アプリケーションが理解しやすくなります。 |
|||
|
|||
共通なパターンはただデータをレンダリングするいくつかのステートレスなコンポーネントを構築することで、 `props` を通してその子要素にstateを渡す階級でステートフルなコンポーネントを持つことです。ステートフルなコンポーネントは、ステートレスなコンポーネントが叙述的な方法でデータをレンダリングする助けを行う一方で、全ての相互作用のロジックを持ちます。 |
|||
|
|||
## stateで何が行われる *べき* でしょうか? |
|||
|
|||
**stateはUIのアップデートのトリガーとなるコンポーネントのイベントハンドラとしてのデータを保持するべきです。** 現実のアプリでは、このデータはとても小さく、JSONでシリアライズできるものになります。ステートフルなコンポーネントを構築する時は、このstateの表現をできるだけ小さくなるように、また、 `this.state` の中だけにそれらのプロパティを貯めこむように考えてください。 `render()` の中では、このstateに基づく、他の必要な情報をただ計算してください。このように考えたりアプリケーションを記述したりすることが最も正しいアプリケーションへの道であると発見するでしょう。stateに余剰な値や、計算後の値を加えることはReactがそれらを計算してくれるのに頼るのではなく、同期的にそれらを明白に保つ必要があることを意味します。 |
|||
|
|||
|
|||
## stateで何が行われる *べきではない* でしょうか? |
|||
|
|||
`this.state` UIのstateを表す必要がある最小限の量のデータだけを保持するべきです。このような点で以下のようなものは保持するべきではありません。 |
|||
|
|||
* **計算されたデータ:** |
|||
stateに基づく事前に計算された値について心配は要りません。 `render()` を用いて、全ての計算を行って、UIの一貫性を保証するよりも簡単です。例えば、stateにリスト化されたアイテムの配列を持っていて、文字列としてその数をレンダリングしたいとして、それらをstateに保持するよりも `render()` メソッドに `this.state.listItems.length + ' list items'` を単純にレンダリングすれば良いのです。 |
|||
* **Reactのコンポーネント:** 隠れたpropsとstateに基づいて `render()` でそれらをビルドしてください。 |
|||
* **propsからコピーしたデータ:** 可能であれば、propsを真のソースとして使ってみてください。propsは時とともに変化し得るので、正しくstateにpropsを保持する使い方は、以前の値を知っていることになり得ます。 |
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue