├── docs ├── RunningOnDeviceIOS.md ├── AndroidUIPerformance.md ├── RunningOnDeviceAndroid.md ├── NativeMethodsMixin.md ├── RunningOnSimulatorIOS-portuguese.md ├── PixelRatio-portuguese.md ├── PullRequestGuidelines.md ├── UnderstandingCLI-portuguese.md ├── HandlingTextInput-portuguese.md ├── HeadlessJSAndroid.md ├── Style-portuguese.md ├── State-portuguese.md ├── HeightAndWidth-portuguese.md ├── Props-portuguese.md ├── LinkingLibraries.md ├── PlatformSpecificInformation.md ├── IssueGuidelines.md ├── UsingAScrollView-portuguese.md ├── Tutorial-portuguese.md ├── UsingAListView-portuguese.md ├── MoreResources.md ├── Timers-portuguese.md ├── BuildingForAppleTV.md ├── GestureResponderSystem.md ├── LayoutWithFlexbox-portuguese.md ├── SignedAPKAndroid.md ├── Troubleshooting.md ├── JavaScriptEnvironment-portuguese.md ├── Navigation.md ├── Text.md ├── Upgrading.md ├── AndroidBuildingFromSource.md ├── Networking.md ├── HandlingTouches.md ├── Colors-portuguese.md ├── Testing.md ├── ComponentsAndAPIs.md ├── Images.md ├── NativeComponentsAndroid.md ├── DirectManipulation.md ├── Accessibility.md └── Accessibility-portuguese.md └── README.md /docs/RunningOnDeviceIOS.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: running-on-device-ios 3 | title: Running On Device 4 | layout: redirect 5 | permalink: docs/running-on-device-ios.html 6 | destinationUrl: running-on-device.html 7 | --- 8 | -------------------------------------------------------------------------------- /docs/AndroidUIPerformance.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: android-ui-performance 3 | title: Profiling Android UI Performance 4 | layout: redirect 5 | permalink: docs/android-ui-performance.html 6 | destinationUrl: performance.html 7 | --- 8 | -------------------------------------------------------------------------------- /docs/RunningOnDeviceAndroid.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: running-on-device-android 3 | title: Running On Device 4 | layout: redirect 5 | permalink: docs/running-on-device-android.html 6 | destinationUrl: running-on-device.html 7 | --- 8 | -------------------------------------------------------------------------------- /docs/NativeMethodsMixin.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: NativeMethodsMixin 3 | title: NativeMethodsMixin 4 | layout: redirect 5 | permalink: docs/nativemethodsmixin.html 6 | destinationUrl: direct-manipulation.html#other-native-methods 7 | --- 8 | -------------------------------------------------------------------------------- /docs/RunningOnSimulatorIOS-portuguese.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: running-on-simulator-ios 3 | title: Running On Simulator 4 | layout: docs 5 | category: Guides (iOS) 6 | permalink: docs/running-on-simulator-ios.html 7 | banner: ejected 8 | next: communication-ios 9 | previous: linking-libraries-ios 10 | --- 11 | 12 | ## Iniciando o simulador 13 | 14 | Tão logo tenha iniciado o seu projeto em React Native, você já pode executar `react-native run-ios` dentro do diretório do projeto recém-criado. Se tudo estiver configurado corretamente, você deve de ver o seu novo app rodando no iOS Simulator logo em breve. 15 | 16 | ## Especificando um dispositivo 17 | 18 | Você pode especificar o dispositivo que o simulador deveria rodar com a flag `--simulator`, seguido pelo nome do dispositivo como um string. O default é `"iPhone 6"`. Se você desejar rodar o seu app num iPhone 4s, apenas execute `react-native run-ios --simulator="iPhone 4s"`. 19 | 20 | Os nomes de dispositivo correspondem à lista de dispositivos disponíveis no Xcode. Você pode verificar os seus dispositivos disponíveis ao executar `xcrun simctl list devices` a partir do console. 21 | -------------------------------------------------------------------------------- /docs/PixelRatio-portuguese.md: -------------------------------------------------------------------------------- 1 | ## Alinhamento de Pixels na Grade 2 | 3 | No iOS, você pode especificar as posições e as dimensões para os elementos com uma precisão arbitrária qualquer; por exemplo 29.674825. Porém, contudo, o display físico tem somente um número fixo de pixels; por exemplo 640×960 para o iPhone 4 ou 750×1334 para o iPhone 6. O iOS tenta ser tão fiel quanto possível ao valor do usuário ao propagar um pixel originário em múltiplos para enganar o olho. A desvantagem desta técnica é que ela faz com que o elemento assim obtido pareça borrado. 4 | 5 | Na prática, descobrimos que os desenvolvedores não querem esta funcionalidade, e que eles têm que trabalhar em torno disto fazendo arredondamento manual no intuito de evitar de ter os elementos borrados. No React Native, estamos arredondando todos os pixels automaticamente. 6 | 7 | Temos que ser cuidadosos quando fizermos este arredondamento. Você jamais vai querer trabalhar com valores com & sem arredondamento ao mesmo tempo, que com o tempo você vai acumulando erros de arredondamento. Mesmo tendo um único erro de arredondamento pode se revelar mortal; pois uma borda de apenas um pixel pode desaparecer, ou acabar ficando duas vezes maior. 8 | 9 | No React Native, tudo em JS e dentro do motor de layout trabalham com números arbitrários de precisão. É somente quando definimos a posição e as dimensões do elemento nativo no thread principal é que nós arredondamos. Além disso, o arredondamento é feito relativo à raiz ao invés do progenitor; novamente para se evitar de acumular erros de arredondamento. 10 | -------------------------------------------------------------------------------- /docs/PullRequestGuidelines.md: -------------------------------------------------------------------------------- 1 | ## Tips on reviewing pull requests 2 | 3 | Does the PR miss info required in the [Pull request template](https://github.com/facebook/react-native/blob/master/.github/PULL_REQUEST_TEMPLATE.md)? Example: [#6395](https://github.com/facebook/react-native/pull/6395). Add labels 'Needs revision' and 'Needs response from author'. Add a response like: 4 | 5 | > Hey @author, thanks for sending the pull request. 6 | > Can you please add all the info specified in the [template](https://github.com/facebook/react-native/blob/master/.github/PULL_REQUEST_TEMPLATE.md)? This is necessary for people to be able to understand and review your pull request. 7 | 8 | Does the code style match the [Style guide](https://github.com/facebook/react-native/blob/master/CONTRIBUTING.md#style-guide), especially consistency (formatting, naming) with the rest of the codebase? If not, link to the style guide and add the label 'Needs revision'. 9 | 10 | Does the pull request add a completely new feature we don't want to add to the core and maintain? Ask the author to release it a separate npm module and close the PR. Example: [#2648](https://github.com/facebook/react-native/pull/2648). 11 | 12 | Does the pull request do several unrelated things at the same time? Ask the author to split it. 13 | 14 | Is the PR old and need rebasing? Ask the author "Can you rebase please?" and add the label "Needs response from author". 15 | 16 | Is a PR waiting for a response from author (usually has label "Needs response from author") and there's no reply in last 30 days? Close it with the [bookmarklet](https://github.com/facebook/react-native/blob/master/bots/pr-inactivity-bookmarklet.js). Examples: [#3066](https://github.com/facebook/react-native/pull/3066), [#1099](https://github.com/facebook/react-native/pull/1099). 17 | 18 | Is the PR old and waiting for review? Review it or cc someone who might be able to review. 19 | -------------------------------------------------------------------------------- /docs/UnderstandingCLI-portuguese.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: understanding-cli 3 | title: Understanding the CLI 4 | layout: docs 5 | category: Guides 6 | permalink: docs/understanding-cli.html 7 | banner: ejected 8 | next: native-modules-ios 9 | previous: testing 10 | --- 11 | 12 | Embora você possa ter instalado o `react-native-cli` via npm como um módulo separado, ele é um shell para accessar o CLI integrado 13 | ao React Native de cada projeto. Os seus comandos e os efeitos deles são dependentes da versão do módulo do `react-native` 14 | no contexto do projeto. Este guia dará uma breve visão geral do CLI no módulo. 15 | 16 | # O CLI local 17 | 18 | O React Native tem uma pasta [`local-cli`](https://github.com/facebook/react-native/tree/master/local-cli) com um arquivo chamado 19 | [`cliEntry.js`](https://github.com/facebook/react-native/blob/master/local-cli/cliEntry.js). Daqui, os comandos são lidos 20 | do `commands.js` e adicionados como possíveis comandos de CLI. Como por exemplo o comando `react-native link` existe na pasta [`react-native/local-cli/link`](https://github.com/facebook/react-native/blob/master/local-cli/link/), e é 21 | requisitado em `commands.js`, o qual o registrará como um comando documentado a ser exposto ao CLI. 22 | 23 | # Definições dos comandos 24 | 25 | No final de cada entrada de comando tem um export. O export é um objeto com uma função para executar, a descrição do comando, e o nome do comando. A estrutura do objeto para o comando `link` parece assim: 26 | 27 | ```js 28 | module.exports = { 29 | func: link, 30 | description: 'links all native dependencies', 31 | name: 'link [packageName]', 32 | }; 33 | ``` 34 | 35 | ### Parâmetros 36 | 37 | O nome do comando identifica os parâmetros que um comando esperaria. Quando o parâmetro do comando estiver envolto pelos símbolos maior-que e menor-que `< >`, isto indica que o parâmetro é esperado. Quando um parâmetro do comando estiver envolto por colchetes `[ ]`, isto indica que o parâmetro é opcional. 38 | -------------------------------------------------------------------------------- /docs/HandlingTextInput-portuguese.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: handling-text-input 3 | title: Handling Text Input 4 | layout: docs 5 | category: The Basics 6 | permalink: docs/handling-text-input.html 7 | next: handling-touches 8 | previous: flexbox 9 | --- 10 | 11 | O [`TextInput`](docs/textinput.html#content) é um componente básico que permite ao usuário entrar com textos. Ele tem uma prop `onChangeText` que aceita uma função a ser chamada toda vez que o texto mudar, e uma prop `onSubmitEditing` que aceita uma função a ser chamada quando o texto for submetido. 12 | 13 | Por exemplo, digamos que à medida que o usuário digita, você esteja traduzindo suas palavras em uma língua diferente. Neste novo idioma, cada palavra individual é escrita da mesma maneira: 🍕. Portanto a sentença "Hello there Bob" seria traduzida como "🍕🍕🍕". 14 | 15 | ```ReactNativeWebPlayer 16 | import React, { Component } from 'react'; 17 | import { AppRegistry, Text, TextInput, View } from 'react-native'; 18 | 19 | export default class PizzaTranslator extends Component { 20 | constructor(props) { 21 | super(props); 22 | this.state = {text: ''}; 23 | } 24 | 25 | render() { 26 | return ( 27 | 28 | this.setState({text})} 32 | /> 33 | 34 | {this.state.text.split(' ').map(word => word && '🍕').join(' ')} 35 | 36 | 37 | ); 38 | } 39 | } 40 | 41 | // skip this line if using Create React Native App 42 | AppRegistry.registerComponent('AwesomeProject', () => PizzaTranslator); 43 | ``` 44 | 45 | Neste exemplo, armazenamos o `text` no `state`, porque ele muda com o tempo. 46 | 47 | Tem muito mais coisas que você poderia querer fazer com um input de texto. Por exemplo, você poderia validar o texto dentro enquanto o usuário digita. Para mais exemplos detalhados, visite os [docs de React sobre componentes controlados](https://facebook.github.io/react/docs/forms.html), ou os [docs de referência para TextInput](docs/textinput.html). 48 | 49 | Entrada de textos é provavelmente o exemplo mais simples dum componente cujo estado muda naturalmente com o tempo. A seguir, vamos dar uma olhada em um outro tipo de componente assim como este que controla o layout, e [aprender sobre o ScrollView](docs/using-a-scrollview.html). 50 | -------------------------------------------------------------------------------- /docs/HeadlessJSAndroid.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: headless-js-android 3 | title: Headless JS 4 | layout: docs 5 | category: Guides (Android) 6 | permalink: docs/headless-js-android.html 7 | banner: ejected 8 | next: signed-apk-android 9 | previous: native-components-android 10 | --- 11 | 12 | Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music. 13 | 14 | ## The JS API 15 | 16 | A task is a simple async function that you register on `AppRegistry`, similar to registering React applications: 17 | 18 | ```js 19 | AppRegistry.registerHeadlessTask('SomeTaskName', () => require('SomeTaskName')); 20 | ``` 21 | 22 | Then, in `SomeTaskName.js`: 23 | 24 | ```js 25 | module.exports = async (taskData) => { 26 | // do stuff 27 | } 28 | ``` 29 | 30 | You can do anything in your task as long as it doesn't touch UI: network requests, timers and so on. Once your task completes (i.e. the promise is resolved), React Native will go into "paused" mode (unless there are other tasks running, or there is a foreground app). 31 | 32 | ## The Java API 33 | 34 | Yes, this does still require some native code, but it's pretty thin. You need to extend `HeadlessJsTaskService` and override `getTaskConfig`, e.g.: 35 | 36 | ```java 37 | public class MyTaskService extends HeadlessJsTaskService { 38 | 39 | @Override 40 | protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) { 41 | Bundle extras = intent.getExtras(); 42 | if (extras != null) { 43 | return new HeadlessJsTaskConfig( 44 | "SomeTaskName", 45 | Arguments.fromBundle(extras), 46 | 5000); 47 | } 48 | return null; 49 | } 50 | } 51 | ``` 52 | 53 | Now, whenever you [start your service][0], e.g. as a periodic task or in response to some system event / broadcast, JS will spin up, run your task, then spin down. 54 | 55 | ## Caveats 56 | 57 | * By default, your app will crash if you try to run a task while the app is in the foreground. This is to prevent developers from shooting themselves in the foot by doing a lot of work in a task and slowing the UI. There is a way around this. 58 | * If you start your service from a `BroadcastReceiver`, make sure to call `HeadlessJsTaskService.acquireWakelockNow()` before returning from `onReceive()`. 59 | 60 | [0]: https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent) 61 | -------------------------------------------------------------------------------- /docs/Style-portuguese.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: style 3 | title: Style 4 | layout: docs 5 | category: The Basics 6 | permalink: docs/style.html 7 | next: height-and-width 8 | previous: state 9 | --- 10 | 11 | Com o React Native, você não usa nenhuma linguagem ou sintaxe especiais para definir estilos. Você simplesmente estiliza as suas aplicações usando o JavaScript. Todos os componentes-base aceitam uma prop chamada `style`. Os nomes e [valores](docs/colors.html) de estilo normalmente coincidem com o funcionamento do CSS na web, com a exceção de que os nomes são escritos usando minúscula/maiúscula em camelo; e.g. `backgroundColor` ao invés de `background-color`. 12 | 13 | A prop de `style` pode ser um objeto de JavaScript comum de sempre. Esse é o mais simples e o que nós geralmente utilizamos como código dos exemplos. Você pode igualmente passar um array de estilos - o último estilo no array tem precedência, então você pode utilizar isto para herdar estilos. 14 | 15 | À medida em que um componente cresce em complexidade, freqüentemente é mais limpo utilizar `StyleSheet.create` para definir vários estilos em um só lugar. Aqui está um exemplo: 16 | 17 | ```ReactNativeWebPlayer 18 | import React, { Component } from 'react'; 19 | import { AppRegistry, StyleSheet, Text, View } from 'react-native'; 20 | 21 | export default class LotsOfStyles extends Component { 22 | render() { 23 | return ( 24 | 25 | just red 26 | just bigblue 27 | bigblue, then red 28 | red, then bigblue 29 | 30 | ); 31 | } 32 | } 33 | 34 | const styles = StyleSheet.create({ 35 | bigblue: { 36 | color: 'blue', 37 | fontWeight: 'bold', 38 | fontSize: 30, 39 | }, 40 | red: { 41 | color: 'red', 42 | }, 43 | }); 44 | 45 | // skip this line if using Create React Native App 46 | AppRegistry.registerComponent('AwesomeProject', () => LotsOfStyles); 47 | ``` 48 | 49 | Um padrão bem comum é fazer com que o seu componente aceite uma prop de `style`, que por sua vez é usada para estilizar os subcomponentes. Você pode utilizar isto para fazer os estilos "descerem em cascata" do mesmo jeito que eles ocorrem no CSS. 50 | 51 | Há ainda muito mais maneiras para se customizar estilos de texto. Confira a [Referência para Componentes de Texto](docs/text.html) para uma lista completa. 52 | 53 | Agora você pode fazer que o seu texto fique bonito. O próximo passo em se tornar um mestre dos estilos é [aprender como controlar o tamanho dos componentes](docs/height-and-width.html). 54 | -------------------------------------------------------------------------------- /docs/State-portuguese.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: state 3 | title: State 4 | layout: docs 5 | category: The Basics 6 | permalink: docs/state.html 7 | next: style 8 | previous: props 9 | --- 10 | 11 | Existem dois tipos de dados que controlam um componente: `props` e `state`. `props` são definidos pelo progenitor e mantêm-se fixos durante todo o tempo de existência dum componente. Para os dados que vão se modificar, temos que utilizar `state`. 12 | 13 | Em geral, você deve inicializar o `state` no construtor, e então chamar `setState` quando quiser modificá-lo. 14 | 15 | Por exemplo, digamos que desejemos criar textos que pisquem o tempo todo. O texto em si é configurado uma vez só quando o componente de piscagem for criado; portanto o texto é em si uma `prop`. O "se acaso o texto esteje no momento ligado ou desligado" modifica-se com o tempo; logo isso deve ser guardado em `state`. 16 | 17 | ```ReactNativeWebPlayer 18 | import React, { Component } from 'react'; 19 | import { AppRegistry, Text, View } from 'react-native'; 20 | 21 | class Blink extends Component { 22 | constructor(props) { 23 | super(props); 24 | this.state = {showText: true}; 25 | 26 | // Toggle the state every second 27 | setInterval(() => { 28 | this.setState(previousState => { 29 | return { showText: !previousState.showText }; 30 | }); 31 | }, 1000); 32 | } 33 | 34 | render() { 35 | let display = this.state.showText ? this.props.text : ' '; 36 | return ( 37 | {display} 38 | ); 39 | } 40 | } 41 | 42 | export default class BlinkApp extends Component { 43 | render() { 44 | return ( 45 | 46 | 47 | 48 | 49 | 50 | 51 | ); 52 | } 53 | } 54 | 55 | // skip this line if using Create React Native App 56 | AppRegistry.registerComponent('AwesomeProject', () => BlinkApp); 57 | ``` 58 | 59 | Num aplicativo de verdade, você provavelmente não estará a reajustar o estado com um temporizador. Você poderia reajustar o estado quando você tivesse novos dados chegando do servidor, ou de entradas do usuário. Você pode também utilizar um contêiner de estados tais como o [Redux](http://redux.js.org/index.html) para controlar o seu fluxo de dados. Nesse caso você utilizaria o Redux para modificar o seu estado no lugar de chamar o `setState` diretamente. 60 | 61 | Quando o setState for chamado, BlinkApp re-renderizará o seu Component. Ao invocar setState de dentro do Timer, o componente re-renderizará toda vez que o Timer der tique-taque. 62 | 63 | O estado funciona da mesma forma como acontece no React; então para mais detalhes em como lidar com o estado, você pode dar uma olhada no [API do React.Component](https://facebook.github.io/react/docs/component-api.html). 64 | Nesta altura, você poderia estar chateado que a maioria dos nossos exemplos até agora utilizam monótonos textos pretos default. Para deixar as coisas mais bonitas, você terá que [aprender sobre Style](docs/style.html). 65 | -------------------------------------------------------------------------------- /docs/HeightAndWidth-portuguese.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: height-and-width 3 | title: Height and Width 4 | layout: docs 5 | category: The Basics 6 | permalink: docs/height-and-width.html 7 | next: flexbox 8 | previous: style 9 | --- 10 | 11 | O width e o height de um componente determina o seu tamanho na tela. 12 | 13 | #### Dimensões Fixas 14 | 15 | A maneira mais simples para definir as dimensões dum componente é adicionando `width` e `height` fixas ao estilo. Todas as dimensões no React Native não possuem unidades de medida, e representam tão somente pixels com densidade autônoma. 16 | 17 | ```ReactNativeWebPlayer 18 | import React, { Component } from 'react'; 19 | import { AppRegistry, View } from 'react-native'; 20 | 21 | export default class FixedDimensionsBasics extends Component { 22 | render() { 23 | return ( 24 | 25 | 26 | 27 | 28 | 29 | ); 30 | } 31 | } 32 | 33 | // skip this line if using Create React Native App 34 | AppRegistry.registerComponent('AwesomeProject', () => FixedDimensionsBasics); 35 | ``` 36 | 37 | Definir dimensões desta forma é comum para componentes que devem sempre renderizar com exatamente o mesmo tamanho, independentemente das dimensões da tela. 38 | 39 | #### Dimensões Flex 40 | 41 | Use `flex` num estilo de componente para fazer com que o componente expanda-se e encolha-se dinamicamente baseado no espaço disponível. Normalmente você utilizará `flex: 1`, que diz a um componente para ocupar todo o espaço disponível, repartido uniformemente por entre cada outro componente com o mesmo progenitor. Quanto maior o `flex` dado, mais elevado a proporção de espaço que um componente tomará em relação aos seus irmãos. 42 | 43 | > Um componente pode somente se expandir para preencher o espaço disponível se o seu progenitor tiver dimensões maiores do que 0. Se um progenitor não tiver nem o `width` e o `height` fixos nem o `flex`, este progenitor terá as dimensões de 0 e os seus filhos `flex` não serão visíveis. 44 | 45 | ```ReactNativeWebPlayer 46 | import React, { Component } from 'react'; 47 | import { AppRegistry, View } from 'react-native'; 48 | 49 | export default class FlexDimensionsBasics extends Component { 50 | render() { 51 | return ( 52 | // Try removing the `flex: 1` on the parent View. 53 | // The parent will not have dimensions, so the children can't expand. 54 | // What if you add `height: 300` instead of `flex: 1`? 55 | 56 | 57 | 58 | 59 | 60 | ); 61 | } 62 | } 63 | 64 | // skip this line if using Create React Native App 65 | AppRegistry.registerComponent('AwesomeProject', () => FlexDimensionsBasics); 66 | ``` 67 | 68 | Logo que você conseguir controlar o tamanho de um componente, o próximo passo é [aprender como posicioná-lo na tela](docs/flexbox.html). 69 | -------------------------------------------------------------------------------- /docs/Props-portuguese.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: props 3 | title: Props 4 | layout: docs 5 | category: The Basics 6 | permalink: docs/props.html 7 | next: state 8 | previous: tutorial 9 | --- 10 | 11 | A maioria dos componentes podem ser customizados quando são criados, usando diferentes parâmetros. Estes parâmetros na criação são chamados de `props`. 12 | 13 | Por exemplo, um componente básico no React Native é o `Image`. Quando você 14 | cria uma imagem, você pode usar uma prop chamada `source` para controlar o que a imagem mostra. 15 | 16 | ```ReactNativeWebPlayer 17 | import React, { Component } from 'react'; 18 | import { AppRegistry, Image } from 'react-native'; 19 | 20 | export default class Bananas extends Component { 21 | render() { 22 | let pic = { 23 | uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg' 24 | }; 25 | return ( 26 | 27 | ); 28 | } 29 | } 30 | 31 | // skip this line if using Create React Native App 32 | AppRegistry.registerComponent('AwesomeProject', () => Bananas); 33 | ``` 34 | 35 | Note que `{pic}` é envolto por chaves para inserir a variável `pic` dentro do JSX. Você pode pôr qualquer expressão de JavaScript dentro de chaves no JSX. 36 | 37 | Os seus próprios componentes podem também usar `props`. Isto permite-lhe criar um componente simples, que é então usado em muitos lugares diferentes no seu app, com propriedades ligeiramente diferentes em cada lugar. Apenas refira ao `this.props` na sua função `render`. Aqui está um exemplo: 38 | 39 | ```ReactNativeWebPlayer 40 | import React, { Component } from 'react'; 41 | import { AppRegistry, Text, View } from 'react-native'; 42 | 43 | class Greeting extends Component { 44 | render() { 45 | return ( 46 | Hello {this.props.name}! 47 | ); 48 | } 49 | } 50 | 51 | export default class LotsOfGreetings extends Component { 52 | render() { 53 | return ( 54 | 55 | 56 | 57 | 58 | 59 | ); 60 | } 61 | } 62 | 63 | // skip this line if using Create React Native App 64 | AppRegistry.registerComponent('AwesomeProject', () => LotsOfGreetings); 65 | ``` 66 | 67 | Usando `name` como uma prop permite-nos customizar o componente `Greeting`; daí podemos reutilizar esse componente para cada greeting nosso. Este exemplo usa também o componente `Greeting` no JSX como se fosse componentes embutidos. O poder de se fazer isto é o que faz do React tão massa - se você se achar desejando que tivesse uma seleção diferente de primitivos de UI com que trabalhar, você simplesmente inventa novos! 68 | 69 | A outra novidade acontecendo aqui é o componente [`View`](docs/view.html). Um [`View`](docs/view.html) é útil 70 | como um contêiner para outros componentes, para ajudar a controlar o estilo e o layout. 71 | 72 | Com `props` e os componentes básicos [`Text`](docs/text.html), [`Image`](docs/image.html) e [`View`](docs/view.html), você pode 73 | desenvolver uma ampla variedade de telas estáticas. Para aprender como fazer o seu app mudar com o tempo, você necessita [aprender sobre State](docs/state.html). 74 | -------------------------------------------------------------------------------- /docs/LinkingLibraries.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: linking-libraries-ios 3 | title: Linking Libraries 4 | layout: docs 5 | category: Guides (iOS) 6 | permalink: docs/linking-libraries-ios.html 7 | banner: ejected 8 | next: running-on-simulator-ios 9 | previous: native-components-ios 10 | --- 11 | 12 | Not every app uses all the native capabilities, and including the code to support 13 | all those features would impact the binary size... But we still want to make it 14 | easy to add these features whenever you need them. 15 | 16 | With that in mind we exposed many of these features as independent static libraries. 17 | 18 | For most of the libs it will be as simple as dragging two files, sometimes a third 19 | step will be necessary, but no more than that. 20 | 21 | _All the libraries we ship with React Native live on the `Libraries` folder in 22 | the root of the repository. Some of them are pure JavaScript, and you only need 23 | to `require` it. Other libraries also rely on some native code, in that case 24 | you'll have to add these files to your app, otherwise the app will throw an 25 | error as soon as you try to use the library._ 26 | 27 | ## Here the few steps to link your libraries that contain native code 28 | 29 | ### Automatic linking 30 | 31 | #### Step 1 32 | 33 | Install a library with native dependencies: 34 | ```bash 35 | $ npm install --save 36 | ``` 37 | 38 | **Note:** _`--save` or `--save-dev` flag is very important for this step. React Native will link 39 | your libs based on `dependencies` and `devDependencies` in your `package.json` file._ 40 | 41 | #### Step 2 42 | 43 | Link your native dependencies: 44 | ```bash 45 | $ react-native link 46 | ``` 47 | 48 | Done! All libraries with native dependencies should be successfully linked to your iOS/Android project. 49 | 50 | ### Manual linking 51 | 52 | #### Step 1 53 | 54 | If the library has native code, there must be a `.xcodeproj` file inside it's 55 | folder. 56 | Drag this file to your project on Xcode (usually under the `Libraries` group 57 | on Xcode); 58 | 59 | ![](img/AddToLibraries.png) 60 | 61 | #### Step 2 62 | 63 | Click on your main project file (the one that represents the `.xcodeproj`) 64 | select `Build Phases` and drag the static library from the `Products` folder 65 | inside the Library you are importing to `Link Binary With Libraries` 66 | 67 | ![](img/AddToBuildPhases.png) 68 | 69 | #### Step 3 70 | 71 | Not every library will need this step, what you need to consider is: 72 | 73 | _Do I need to know the contents of the library at compile time?_ 74 | 75 | What that means is, are you using this library on the native side or only in 76 | JavaScript? If you are only using it in JavaScript, you are good to go! 77 | 78 | This step is not necessary for libraries that we ship with React Native with the 79 | exception of `PushNotificationIOS` and `Linking`. 80 | 81 | In the case of the `PushNotificationIOS` for example, you have to call a method 82 | on the library from your `AppDelegate` every time a new push notification is 83 | received. 84 | 85 | For that we need to know the library's headers. To achieve that you have to go 86 | to your project's file, select `Build Settings` and search for `Header Search 87 | Paths`. There you should include the path to your library (if it has relevant 88 | files on subdirectories remember to make it `recursive`, like `React` on the 89 | example). 90 | 91 | ![](img/AddToSearchPaths.png) 92 | -------------------------------------------------------------------------------- /docs/PlatformSpecificInformation.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: platform-specific-code 3 | title: Platform Specific Code 4 | layout: docs 5 | category: Guides 6 | permalink: docs/platform-specific-code.html 7 | next: navigation 8 | previous: components 9 | --- 10 | 11 | When building a cross-platform app, you'll want to re-use as much code as possible. Scenarios may arise where it makes sense for the code to be different, for example you may want to implement separate visual components for iOS and Android. 12 | 13 | React Native provides two ways to easily organize your code and separate it by platform: 14 | 15 | * Using the [`Platform` module](docs/platform-specific-code.html#platform-module). 16 | * Using [platform-specific file extensions](docs/platform-specific-code.html#platform-specific-extensions). 17 | 18 | Certain components may have properties that work on one platform only. All of these props are annotated with `@platform` and have a small badge next to them on the website. 19 | 20 | 21 | ## Platform module 22 | 23 | React Native provides a module that detects the platform in which the app is running. You can use the detection logic to implement platform-specific code. Use this option when only small parts of a component are platform-specific. 24 | 25 | ```javascript 26 | import { Platform, StyleSheet } from 'react-native'; 27 | 28 | const styles = StyleSheet.create({ 29 | height: (Platform.OS === 'ios') ? 200 : 100, 30 | }); 31 | ``` 32 | 33 | `Platform.OS` will be `ios` when running on iOS and `android` when running on Android. 34 | 35 | There is also a `Platform.select` method available, that given an object containing Platform.OS as keys, returns the value for the platform you are currently running on. 36 | 37 | ```javascript 38 | import { Platform, StyleSheet } from 'react-native'; 39 | 40 | const styles = StyleSheet.create({ 41 | container: { 42 | flex: 1, 43 | ...Platform.select({ 44 | ios: { 45 | backgroundColor: 'red', 46 | }, 47 | android: { 48 | backgroundColor: 'blue', 49 | }, 50 | }), 51 | }, 52 | }); 53 | ``` 54 | 55 | This will result in a container having `flex: 1` on both platforms, a red background color on iOS, and a blue background color on Android. 56 | 57 | Since it accepts `any` value, you can also use it to return platform specific component, like below: 58 | 59 | ```javascript 60 | const Component = Platform.select({ 61 | ios: () => require('ComponentIOS'), 62 | android: () => require('ComponentAndroid'), 63 | })(); 64 | 65 | ; 66 | ``` 67 | 68 | ### Detecting the Android version 69 | 70 | On Android, the `Platform` module can also be used to detect the version of the Android Platform in which the app is running: 71 | 72 | ```javascript 73 | import { Platform } from 'react-native'; 74 | 75 | if (Platform.Version === 25) { 76 | console.log('Running on Nougat!'); 77 | } 78 | ``` 79 | 80 | ## Platform-specific extensions 81 | 82 | When your platform-specific code is more complex, you should consider splitting the code out into separate files. React Native will detect when a file has a `.ios.` or `.android.` extension and load the relevant platform file when required from other components. 83 | 84 | For example, say you have the following files in your project: 85 | 86 | ```sh 87 | BigButton.ios.js 88 | BigButton.android.js 89 | ``` 90 | 91 | You can then require the component as follows: 92 | 93 | ```javascript 94 | const BigButton = require('./BigButton'); 95 | ``` 96 | 97 | React Native will automatically pick up the right file based on the running platform. 98 | -------------------------------------------------------------------------------- /docs/IssueGuidelines.md: -------------------------------------------------------------------------------- 1 | ## Tips on managing GitHub issues efficiently 2 | 3 | ### An issue is a duplicate of another issue 4 | Comment e.g. `@facebook-github-bot duplicate #123`. This will add a comment and close the issue. 5 | Example: [#5977](https://github.com/facebook/react-native/issues/5977) 6 | 7 | ### An issue is a question 8 | Questions should absolutely be asked on StackOverflow rather than GitHub. 9 | Comment `@facebook-github-bot stack-overflow` to close the issue. 10 | Examples: [#6378](https://github.com/facebook/react-native/issues/6378), [#6015](https://github.com/facebook/react-native/issues/6015), [#6059](https://github.com/facebook/react-native/issues/6059), [#6062](https://github.com/facebook/react-native/issues/6062). 11 | Feel free to also answer some [SO questions](stackoverflow.com/questions/tagged/react-native), you'll get rep :) 12 | 13 | ### An issue is a question that's been answered 14 | Sometimes and issue has been resolved in the comments. 15 | Comment `@facebook-github-bot answered` to close it. 16 | Example: [#6045](https://github.com/facebook/react-native/issues/6045) 17 | 18 | ### An issue needs more information 19 | It is impossible to understand and reproduce the issue without more information, e.g. a short code sample, screenshot. 20 | Do the following: 21 | - Explain what additional info you need to understand the issue 22 | - Comment `@facebook-github-bot label Needs more information` 23 | Examples: [#6056](https://github.com/facebook/react-native/issues/6056), [#6008](https://github.com/facebook/react-native/issues/6008), [#5491](https://github.com/facebook/react-native/issues/5491) 24 | 25 | ### An issue with label 'Needs more information' has been open for more than a week 26 | Comment mentioning the author asking if they plan to provide the additional information. If they don't come back close the issue using `@facebook-github-bot no-reply`. 27 | Example: [#6056](https://github.com/facebook/react-native/issues/6056) 28 | 29 | ### An issue is a valid bug report 30 | Valid bug reports with good repro steps are some of the best issues! Thank the author for finding it, explain that React Native is a community project and **ask them if they would be up for sending a fix**. 31 | 32 | ### An issue is a feature request. The feature shouldn't be in the code and don't want to maintain it. 33 | This especially includes **new modules** Facebook doesn't use in production. Explain that those modules should be released to npm separately and that everyone will still be able to use the module super easily that way. 34 | 35 | ### An issue is a feature request, you're pretty sure we should maintain this feature as part of RN 36 | This should be rare - adding a new feature means maintaining it. 37 | Tell the author something like: "Pull requests are welcome. In case you're not up for sending a PR, you should post to [Canny](https://react-native.canny.io/feature-requests). It has a voting system and if the feature gets upvoted enough it might get implemented." 38 | 39 | ### How to add a label 40 | Add any relevant labels, for example 'Android', 'iOS'. 41 | Comment e.g. `@facebook-github-bot label Android` 42 | 43 | ### How to reopen a closed issue 44 | For example an issue was closed waiting for the author, the author replied and it turns out this is indeed a bug. 45 | Comment `@facebook-github-bot reopen` 46 | 47 | ### What are all the available commands for the bot? 48 | When you mention the bot, it follows the commands defined in [IssueCommands.txt](https://github.com/facebook/react-native/blob/master/bots/IssueCommands.txt). 49 | 50 | ### How can I help manage issues? 51 | Thank you for wanting to take the time to help us with managing GitHub issues. To have access to the bot please add your GitHub username to the first line of [IssueCommands.txt](https://github.com/facebook/react-native/blob/master/bots/IssueCommands.txt), in alphabetical order, by submitting a Pull Request. 52 | -------------------------------------------------------------------------------- /docs/UsingAScrollView-portuguese.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: using-a-scrollview 3 | title: Using a ScrollView 4 | layout: docs 5 | category: The Basics 6 | permalink: docs/using-a-scrollview.html 7 | next: using-a-listview 8 | previous: handling-touches 9 | --- 10 | 11 | O [ScrollView](docs/scrollview.html) é um contêiner genérico para rolagem que pode hospedar múltiplos componentes e visualizadores. Os itens roláveis não precisam ser homogênios, e você pode rolar tanto verticalmente quanto horizontalmente (ao definir a propriedade `horizontal`). 12 | 13 | Este exemplo cria um `ScrollView` vertical misturando imagens e textos juntos. 14 | 15 | ```ReactNativeWebPlayer 16 | import React, { Component } from 'react'; 17 | import { AppRegistry, ScrollView, Image, Text } from 'react-native'; 18 | 19 | export default class IScrolledDownAndWhatHappenedNextShockedMe extends Component { 20 | render() { 21 | return ( 22 | 23 | Scroll me plz 24 | 25 | 26 | 27 | 28 | 29 | If you like 30 | 31 | 32 | 33 | 34 | 35 | Scrolling down 36 | 37 | 38 | 39 | 40 | 41 | What's the best 42 | 43 | 44 | 45 | 46 | 47 | Framework around? 48 | 49 | 50 | 51 | 52 | 53 | React Native 54 | 55 | ); 56 | } 57 | } 58 | 59 | // skip these lines if using Create React Native App 60 | AppRegistry.registerComponent( 61 | 'AwesomeProject', 62 | () => IScrolledDownAndWhatHappenedNextShockedMe); 63 | ``` 64 | 65 | ScrollViews podem ser configurados para permitir paginação por gestos de deslizamento através de visualizadores ao usarmos as propriedades `pagingEnabled`. Deslizar horizontalmente por entre visualizadores pode também ser implementado no Android usando o componente [ViewPagerAndroid](docs/viewpagerandroid.html). 66 | 67 | Um ScrollView num item individual pode ser usado para permitir ao usuário dar zoom no conteúdo. Configure as propriedades `maximumZoomScale` e `minimumZoomScale` e o seu usuário será capaz de usar os gestos expandir e beliscar para aumentar e diminuir o zoom. 68 | 69 | O ScrollView funciona melhor para apresentar uma quantidade pequena de coisas com tamanhos limitados. Todos os elementos e visualizadores de um `ScrollView` são renderizados, mesmo quando não estiverem sendo mostrados na tela. Se você tiver uma lista longa com mais itens que conseguem caber na tela, você deveria usar uma `FlatList` no lugar. Portanto vamos [aprender sobre visualizadores de listas](docs/using-a-listview.html) em seguida. 70 | -------------------------------------------------------------------------------- /docs/Tutorial-portuguese.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: tutorial 3 | title: Tutorial 4 | layout: docs 5 | category: The Basics 6 | permalink: docs/tutorial.html 7 | next: props 8 | previous: getting-started 9 | --- 10 | 11 | React Native é como React; mas ele usa componentes nativos no lugar de componentes web como elementos fundamentais. Assim, para compreender a estrutura básica dum app de React Native, você necessita entender alguns dos conceitos básicos de React, tais como JSX, componentes, `state` e `props`. Se você já conhece React, você ainda precisa aprender algumas paradas específicas de React Native, tais como os seus componentes nativos. Este tutorial é voltado para todas as audiências, tenha você experiência com React ou não. 12 | 13 | Vamos lá fazer este treco! 14 | 15 | ## Alô Mundo (Hello World) 16 | 17 | Em conformidade com as tradições antigas de nosso povo, devemos primeiro desenvolver um app que não faça nada exceto dizer "Hello world". Aqui está ele: 18 | 19 | ```ReactNativeWebPlayer 20 | import React, { Component } from 'react'; 21 | import { AppRegistry, Text } from 'react-native'; 22 | 23 | export default class HelloWorldApp extends Component { 24 | render() { 25 | return ( 26 | Hello world! 27 | ); 28 | } 29 | } 30 | 31 | // skip this line if using Create React Native App 32 | AppRegistry.registerComponent('AwesomeProject', () => HelloWorldApp); 33 | ``` 34 | 35 | Se você estiver se sentindo curioso, você já pode brincar com o programa-exemplo diretamente nos simuladores de web. Você pode igualmente colá-lo dentro do seu arquivo `App.js`, `index.ios.js`, ou `index.android.js` para criar um app de verdade na sua máquina local. 36 | 37 | ## O que está se passando aqui? 38 | 39 | Algumas das coisas daqui podem não parecer muito com JavaScript pra você. Não se desespere! _Isto é o futuro_. 40 | 41 | Primeiro de tudo, o ES2015 (também conhecido como ES6) é um conjunto de melhoramentos para o JavaScript que é agora parte do padrão oficial, mas não ainda supportado por todos os navegadores, que muitas das vezes ainda não se é usado no desenvolvimento web. React Native vem acompanhado com suporte a ES2015; portanto você pode usar todo este material sem se preocupar sobre compatibilidade. `import`, `from`, `class`, `extends` e a sintaxe `() =>` no exemplo acima são todos funcionalidades do ES2015. Se você ainda não estiver familiarizado com o ES2015, você pode provavelmente assimilá-lo apenas por ler atentamente exemplos de código como este tutorial possui. Se quiser, [esta página](https://babeljs.io/learn-es2015/) tem um bom apanhado das funcionalidades do ES2015. 42 | 43 | A outra coisa inusitada neste exemplo de código é `Hello world!`. Este é o JSX - uma sintaxe para incorporar XML dentro do JavaScript. Muitos frameworks usam uma linguagem especial de templates que lhe permite inserir códigos dentro da linguagem de markup. Em React, isto é o reverso. O JSX permite que você escreva a sua linguagem de markup dentro do programa. Parece igual HTML na web, exceto que no lugar de coisas de web como `
` or ``, você usa componentes React. Neste caso, `` é um componente embutido que apenas exibe algum texto. 44 | 45 | ## Componentes 46 | 47 | Então este programa está definindo o `HelloWorldApp`, um `Component` novo. Quando você estiver desenvolvendo um app em React Native, você estará criando novos componentes abundantemente. Qualquer coisa que você enxergar na tela é algum tipo de componente. Um componente pode ser bastante simples - a única coisa que é exigida é uma função para `render`, a qual retorna algum JSX para renderizar. 48 | 49 | ## Projetos só com código nativo 50 | 51 | No exemplo particular acima, o `HelloWorldApp` está registrado com o `AppRegistry`. O `AppRegistry` apenas diz ao React Native qual componente é a raiz para a aplicação inteira. Está incluído nestes exemplos; portanto você pode colar a coisa toda dentro do seu arquivo `index.ios.js` ou `index.android.js` e tê-la já rodando. Se você tiver um projeto de Create React Native App, isto é gerido automaticamente para você e não é necessário chamar `AppRegistry` no seu programa. 52 | 53 | ## Este app não faz muitíssimo 54 | 55 | Boa observação! Para fazer os componentes produzirem coisas mais interessantes, você necessita [aprender sobre Props](docs/props.html). 56 | -------------------------------------------------------------------------------- /docs/UsingAListView-portuguese.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: using-a-listview 3 | title: Using List Views 4 | layout: docs 5 | category: The Basics 6 | permalink: docs/using-a-listview.html 7 | next: network 8 | previous: using-a-scrollview 9 | --- 10 | 11 | O React Native fornece um conjunto de componentes para apresentação de listas de dados. Geralmente você vai querer usar ou a [FlatList](docs/flatlist.html) ou então a [SectionList](docs/sectionlist.html). 12 | 13 | O componente `FlatList` exibe uma lista rolável de dados dinâmicos, mas similarmente estruturados. A `FlatList` funciona bem para as listas de dados longas, onde o número de itens pode mudar com o tempo. Diferente do mais genérico [`ScrollView`](docs/using-a-scrollview.html), a `FlatList` apenas processa os elementos que estão sendo mostrados na tela, não todos os elementos de uma vez. 14 | 15 | O componente `FlatList` requer duas propriedades: `data` e `renderItem`. `data` é a fonte da informação para a lista. `renderItem` pega um item da fonte e retorna um componente formatado para renderizar. 16 | 17 | Este exemplo cria uma `FlatList` simples com os dados já diretamente inseridos. Cada item nas propriedades de `data` é renderizado como um componente `Text`. O componente `FlatListBasics` então renderiza a `FlatList` e todos os componentes `Text`. 18 | 19 | ```SnackPlayer?name=FlatList%20Basics 20 | import React, { Component } from 'react'; 21 | import { AppRegistry, FlatList, StyleSheet, Text, View } from 'react-native'; 22 | 23 | export default class FlatListBasics extends Component { 24 | render() { 25 | return ( 26 | 27 | {item.key}} 39 | /> 40 | 41 | ); 42 | } 43 | } 44 | 45 | const styles = StyleSheet.create({ 46 | container: { 47 | flex: 1, 48 | paddingTop: 22 49 | }, 50 | item: { 51 | padding: 10, 52 | fontSize: 18, 53 | height: 44, 54 | }, 55 | }) 56 | 57 | // skip this line if using Create React Native App 58 | AppRegistry.registerComponent('AwesomeProject', () => FlatListBasics); 59 | ``` 60 | 61 | Se você quiser processar um conjunto de dados repartidos em seções lógicas, talvez com cabeçalhos das seções, similar ao `UITableView`s no iOS, então uma [SectionList](docs/sectionlist.html) é o caminho a seguir. 62 | 63 | ```SnackPlayer?name=SectionList%20Basics 64 | import React, { Component } from 'react'; 65 | import { AppRegistry, SectionList, StyleSheet, Text, View } from 'react-native'; 66 | 67 | export default class SectionListBasics extends Component { 68 | render() { 69 | return ( 70 | 71 | {item}} 77 | renderSectionHeader={({section}) => {section.title}} 78 | /> 79 | 80 | ); 81 | } 82 | } 83 | 84 | const styles = StyleSheet.create({ 85 | container: { 86 | flex: 1, 87 | paddingTop: 22 88 | }, 89 | sectionHeader: { 90 | paddingTop: 2, 91 | paddingLeft: 10, 92 | paddingRight: 10, 93 | paddingBottom: 2, 94 | fontSize: 14, 95 | fontWeight: 'bold', 96 | backgroundColor: 'rgba(247,247,247,1.0)', 97 | }, 98 | item: { 99 | padding: 10, 100 | fontSize: 18, 101 | height: 44, 102 | }, 103 | }) 104 | 105 | // skip this line if using Create React Native App 106 | AppRegistry.registerComponent('AwesomeProject', () => SectionListBasics); 107 | ``` 108 | 109 | Um dos usos mais comuns para um visualizador de listas é exibir os dados que você busca de um servidor. Para fazer isso, você precisará [aprender sobre trabalhos em rede (networking) no React Native](docs/network.html). 110 | -------------------------------------------------------------------------------- /docs/MoreResources.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: more-resources 3 | title: More Resources 4 | layout: docs 5 | category: The Basics 6 | permalink: docs/more-resources.html 7 | next: components 8 | previous: network 9 | --- 10 | 11 | If you just read through this website, you should be able to build a pretty cool React Native app. But React Native isn't just a product made by one company - it's a community of thousands of developers. So if you're interested in React Native, here's some related stuff you might want to check out. 12 | 13 | ## Popular Libraries 14 | 15 | If you're using React Native, you probably already know about [React](https://facebook.github.io/react/). So I feel a bit silly mentioning this. But if you haven't, check out React - it's the best way to build a modern website. 16 | 17 | One common question is how to handle the "state" of your React Native application. The most popular library for this is [Redux](http://redux.js.org/). Don't be afraid of how often Redux uses the word "reducer" - it's a pretty simple library, and there's also a nice [series of videos](https://egghead.io/courses/getting-started-with-redux) explaining it. 18 | 19 | If you're looking for a library that does a specific thing, check out [Awesome React Native](http://www.awesome-react-native.com/), a curated list of components that also has demos, articles, and other stuff. 20 | 21 | ## Example Apps 22 | 23 | There are some [example apps on GitHub](https://github.com/ReactNativeNews/React-Native-Apps). You can run the apps on a simulator or device, and you can see the source code for these apps, which is neat. 24 | 25 | The folks who built the app for Facebook's F8 conference in 2016 also [open-sourced the code](https://github.com/fbsamples/f8app) and wrote up a [detailed series of tutorials](http://makeitopen.com/tutorials/building-the-f8-app/planning/). This is useful if you want a more in-depth example that's more realistic than most sample apps out there. 26 | 27 | ## Development Tools 28 | 29 | [Nuclide](https://nuclide.io/) is the IDE that Facebook uses internally for React Native development. The killer feature of Nuclide is its debugging ability. It also has great inline Flow support. 30 | 31 | [Ignite](https://github.com/infinitered/ignite) is a starter kit that uses Redux and a few different common UI libraries. It has a CLI to generate apps, components, and containers. If you like all of the individual tech choices, Ignite could be perfect for you. 32 | 33 | [CodePush](https://microsoft.github.io/code-push/) is a service from Microsoft that makes it easy to deploy live updates to your React Native app. If you don't like going through the app store process to deploy little tweaks, and you also don't like setting up your own backend, give CodePush a try. 34 | 35 | [Expo](https://docs.expo.io) is a development environment plus application that focuses on letting you build React Native apps in the Expo development environment, without ever touching Xcode or Android Studio. If you wish React Native was even more JavaScripty and webby, check out Expo. 36 | 37 | ## Where React Native People Hang Out 38 | 39 | The [React Native Community](https://www.facebook.com/groups/react.native.community) Facebook group has thousands of developers, and it's pretty active. Come there to show off your project, or ask how other people solved similar problems. 40 | 41 | [Reactiflux](https://discord.gg/0ZcbPKXt5bZjGY5n) is a Discord chat where a lot of React-related discussion happens, including React Native. Discord is just like Slack except it works better for open source projects with a zillion contributors. Check out the #react-native channel. 42 | 43 | The [React Twitter account](https://twitter.com/reactjs) covers both React and React Native. Follow the React Native [Twitter account](https://twitter.com/reactnative) and [blog](/react-native/blog/) to find out what's happening in the world of React Native. 44 | 45 | There are a lot of [React Native Meetups](http://www.meetup.com/topics/react-native/) that happen around the world. Often there is React Native content in React meetups as well. 46 | 47 | Sometimes we have React conferences. We posted the [videos from React.js Conf 2017](https://www.youtube.com/playlist?list=PLb0IAmt7-GS3fZ46IGFirdqKTIxlws7e0) and [React.js Conf 2016](https://www.youtube.com/playlist?list=PLb0IAmt7-GS0M8Q95RIc2lOM6nc77q1IY), and we'll probably have more conferences in the future, too. Stay tuned. You can also find a list of dedicated React Native conferences [here](http://www.awesome-react-native.com/#conferences). 48 | -------------------------------------------------------------------------------- /docs/Timers-portuguese.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: timers 3 | title: Timers 4 | layout: docs 5 | category: Guides 6 | permalink: docs/timers.html 7 | next: debugging 8 | previous: accessibility 9 | --- 10 | 11 | Os temporizadores são uma parte importante dum aplicativo e o React Native implementa os [temporizadores do navegador](https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Timers). 12 | 13 | ## Temporizadores (Timers) 14 | 15 | - setTimeout, clearTimeout 16 | - setInterval, clearInterval 17 | - setImmediate, clearImmediate 18 | - requestAnimationFrame, cancelAnimationFrame 19 | 20 | `requestAnimationFrame(fn)` não é o mesmo que `setTimeout(fn, 0)` - o anterior disparará depois que todo o quadro tiver se escoado; ao passo que o último disparará tão rapidamente quanto possível (acima de 1000x por segundo num iPhone 5S). 21 | 22 | `setImmediate` é executado ao final do bloco de execução corrente do JavaScript, imediadamente antes de mandar a resposta em lote de volta ao nativo. Note que se você chamar `setImmediate` de dentro duma callback de `setImmediate`, ela será executada imediatamente, não cederá de volta ao nativo entre os intervalos. 23 | 24 | A implementação `Promise` utiliza `setImmediate` como o seu primitivo de assincronicidade. 25 | 26 | 27 | ## Gerenciador de Interações (InteractionManager) 28 | 29 | Uma razão do porquê dos apps nativos bem produzidos sentem-se tão fluidos é por evitarem operações pesadas durante as interações e animações. No React Native, atualmente temos uma limitação de que existe somente um único thread de execução no JS; mas você pode utilizar `InteractionManager` para assegurar que os trabalhos de execução com longa duração sejam agendados para iniciarem-se após quaisquer interações/animações tenham se finalizados. 30 | 31 | Aplicativos podem agendar tarefas para rodarem após as interações com o seguinte: 32 | 33 | ```javascript 34 | InteractionManager.runAfterInteractions(() => { 35 | // ...long-running synchronous task... 36 | }); 37 | ``` 38 | 39 | Compare isto com as outras alternativas de agendamento: 40 | 41 | - requestAnimationFrame(): para código que anima uma visualização ao longo do tempo. 42 | - setImmediate/setTimeout/setInterval(): roda o código mais tarde; notando que isto pode retardar as animações. 43 | - runAfterInteractions(): roda o código mais tarde, mas sem retardar as animações ativas. 44 | 45 | O sistema para manejo de toques considera que um ou mais toques ativos sejam uma 'interaction', e protelará os callbacks de `runAfterInteractions()` até que todos os toques tenham terminado ou sido cancelados. 46 | 47 | O InteractionManager permite igualmente aos aplicativos registrarem animações ao criar um 'handle' de interação no começo da animação, e então limpá-lo uma vez concluído: 48 | 49 | ```javascript 50 | var handle = InteractionManager.createInteractionHandle(); 51 | // run animation... (`runAfterInteractions` tasks are queued) 52 | // later, on animation completion: 53 | InteractionManager.clearInteractionHandle(handle); 54 | // queued tasks run if all handles were cleared 55 | ``` 56 | 57 | 58 | ## Mixin de Temporizadores (TimerMixin) 59 | 60 | Descobrimos que a causa primária das fatalidades nos apps criados com React Native era devido aos temporizadores dispararem após um componente ter sido desmontado. Para resolver esta questão recorrente, introduzimos o `TimerMixin`. Se você incluir o `TimerMixin`, então você pode substituir as suas chamadas ao `setTimeout(fn, 500)` com o `this.setTimeout(fn, 500)` (apenas adicione `this.` na frente) e tudo será adequadamente arrumado para você quando o componente se desmontar. 61 | 62 | Esta biblioteca não acompanha o React Native - de modo que para usá-la no seu projeto, você necessitará de instalá-la com `npm i react-timer-mixin --save` a partir do diretório do projeto. 63 | 64 | ```javascript 65 | import TimerMixin from 'react-timer-mixin'; 66 | 67 | var Component = React.createClass({ 68 | mixins: [TimerMixin], 69 | componentDidMount: function() { 70 | this.setTimeout( 71 | () => { console.log('I do not leak!'); }, 72 | 500 73 | ); 74 | } 75 | }); 76 | ``` 77 | 78 | Isto eliminará muito do trabalho árduo de rastrear os bugs, tais como os travamentos causados por timeouts disparando após um componente ter sido desmontado. 79 | 80 | Tenha em mente que se você utizar classes do ES6 para os seus componentes React [não existe API integrado para mixins](https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#mixins). Para utilizar `TimerMixin` com classes do ES6, recomendamos o [react-mixin](https://github.com/brigand/react-mixin). 81 | -------------------------------------------------------------------------------- /docs/BuildingForAppleTV.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: building-for-apple-tv 3 | title: Building For Apple TV 4 | layout: docs 5 | category: Guides (iOS) 6 | permalink: docs/building-for-apple-tv.html 7 | banner: ejected 8 | next: native-modules-android 9 | previous: communication-ios 10 | --- 11 | 12 | Apple TV support has been implemented with the intention of making existing React Native iOS applications "just work" on tvOS, with few or no changes needed in the JavaScript code for the applications. 13 | 14 | The RNTester app supports Apple TV; use the `RNTester-tvOS` build target to build for tvOS. 15 | 16 | ## Build changes 17 | 18 | - *Native layer*: React Native Xcode projects all now have Apple TV build targets, with names ending in the string '-tvOS'. 19 | 20 | - *react-native init*: New React Native projects created with `react-native init` will have Apple TV target automatically created in their XCode projects. 21 | 22 | - *JavaScript layer*: Support for Apple TV has been added to `Platform.ios.js`. You can check whether code is running on AppleTV by doing 23 | 24 | ```js 25 | var Platform = require('Platform'); 26 | var running_on_apple_tv = Platform.isTVOS; 27 | ``` 28 | 29 | ## Code changes 30 | 31 | - *General support for tvOS*: Apple TV specific changes in native code are all wrapped by the TARGET_OS_TV define. These include changes to suppress APIs that are not supported on tvOS (e.g. web views, sliders, switches, status bar, etc.), and changes to support user input from the TV remote or keyboard. 32 | 33 | - *Common codebase*: Since tvOS and iOS share most Objective-C and JavaScript code in common, most documentation for iOS applies equally to tvOS. 34 | 35 | - *Access to touchable controls*: When running on Apple TV, the native view class is `RCTTVView`, which has additional methods to make use of the tvOS focus engine. The `Touchable` mixin has code added to detect focus changes and use existing methods to style the components properly and initiate the proper actions when the view is selected using the TV remote, so `TouchableHighlight` and `TouchableOpacity` will "just work". In particular: 36 | 37 | - `touchableHandleActivePressIn` will be executed when the touchable view goes into focus 38 | - `touchableHandleActivePressOut` will be executed when the touchable view goes out of focus 39 | - `touchableHandlePress` will be executed when the touchable view is actually selected by pressing the "select" button on the TV remote. 40 | 41 | - *TV remote/keyboard input*: A new native class, `RCTTVRemoteHandler`, sets up gesture recognizers for TV remote events. When TV remote events occur, this class fires notifications that are picked up by `RCTTVNavigationEventEmitter` (a subclass of `RCTEventEmitter`), that fires a JS event. This event will be picked up by instances of the `TVEventHandler` JavaScript object. Application code that needs to implement custom handling of TV remote events can create an instance of `TVEventHandler` and listen for these events, as in the following code: 42 | 43 | ```js 44 | var TVEventHandler = require('TVEventHandler'); 45 | 46 | . 47 | . 48 | . 49 | 50 | class Game2048 extends React.Component { 51 | _tvEventHandler: any; 52 | 53 | _enableTVEventHandler() { 54 | this._tvEventHandler = new TVEventHandler(); 55 | this._tvEventHandler.enable(this, function(cmp, evt) { 56 | if (evt && evt.eventType === 'right') { 57 | cmp.setState({board: cmp.state.board.move(2)}); 58 | } else if(evt && evt.eventType === 'up') { 59 | cmp.setState({board: cmp.state.board.move(1)}); 60 | } else if(evt && evt.eventType === 'left') { 61 | cmp.setState({board: cmp.state.board.move(0)}); 62 | } else if(evt && evt.eventType === 'down') { 63 | cmp.setState({board: cmp.state.board.move(3)}); 64 | } else if(evt && evt.eventType === 'playPause') { 65 | cmp.restartGame(); 66 | } 67 | }); 68 | } 69 | 70 | _disableTVEventHandler() { 71 | if (this._tvEventHandler) { 72 | this._tvEventHandler.disable(); 73 | delete this._tvEventHandler; 74 | } 75 | } 76 | 77 | componentDidMount() { 78 | this._enableTVEventHandler(); 79 | } 80 | 81 | componentWillUnmount() { 82 | this._disableTVEventHandler(); 83 | } 84 | 85 | ``` 86 | 87 | - *TV remote animations*: `RCTTVView` native code implements Apple-recommended parallax animations to help guide the eye as the user navigates through views. The animations can be disabled or adjusted with new optional view properties. 88 | 89 | - *Back navigation with the TV remote menu button*: The `BackHandler` component, originally written to support the Android back button, now also supports back navigation on the Apple TV using the menu button on the TV remote. 90 | 91 | - *Known issues*: 92 | 93 | - [ListView scrolling](https://github.com/facebook/react-native/issues/12793). The issue can be easily worked around by setting `removeClippedSubviews` to false in ListView and similar components. For more discussion of this issue, see [this PR](https://github.com/facebook/react-native/pull/12944). 94 | -------------------------------------------------------------------------------- /docs/GestureResponderSystem.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: gesture-responder-system 3 | title: Gesture Responder System 4 | layout: docs 5 | category: Guides 6 | permalink: docs/gesture-responder-system.html 7 | next: javascript-environment 8 | previous: performance 9 | --- 10 | 11 | The gesture responder system manages the lifecycle of gestures in your app. A touch can go through several phases as the app determines what the user's intention is. For example, the app needs to determine if the touch is scrolling, sliding on a widget, or tapping. This can even change during the duration of a touch. There can also be multiple simultaneous touches. 12 | 13 | The touch responder system is needed to allow components to negotiate these touch interactions without any additional knowledge about their parent or child components. This system is implemented in `ResponderEventPlugin.js`, which contains further details and documentation. 14 | 15 | ### Best Practices 16 | 17 | To make your app feel great, every action should have the following attributes: 18 | 19 | - Feedback/highlighting- show the user what is handling their touch, and what will happen when they release the gesture 20 | - Cancel-ability- when making an action, the user should be able to abort it mid-touch by dragging their finger away 21 | 22 | These features make users more comfortable while using an app, because it allows people to experiment and interact without fear of making mistakes. 23 | 24 | ### TouchableHighlight and Touchable* 25 | 26 | The responder system can be complicated to use. So we have provided an abstract `Touchable` implementation for things that should be "tappable". This uses the responder system and allows you to easily configure tap interactions declaratively. Use `TouchableHighlight` anywhere where you would use a button or link on web. 27 | 28 | 29 | ## Responder Lifecycle 30 | 31 | A view can become the touch responder by implementing the correct negotiation methods. There are two methods to ask the view if it wants to become responder: 32 | 33 | - `View.props.onStartShouldSetResponder: (evt) => true,` - Does this view want to become responder on the start of a touch? 34 | - `View.props.onMoveShouldSetResponder: (evt) => true,` - Called for every touch move on the View when it is not the responder: does this view want to "claim" touch responsiveness? 35 | 36 | If the View returns true and attempts to become the responder, one of the following will happen: 37 | 38 | - `View.props.onResponderGrant: (evt) => {}` - The View is now responding for touch events. This is the time to highlight and show the user what is happening 39 | - `View.props.onResponderReject: (evt) => {}` - Something else is the responder right now and will not release it 40 | 41 | If the view is responding, the following handlers can be called: 42 | 43 | - `View.props.onResponderMove: (evt) => {}` - The user is moving their finger 44 | - `View.props.onResponderRelease: (evt) => {}` - Fired at the end of the touch, ie "touchUp" 45 | - `View.props.onResponderTerminationRequest: (evt) => true` - Something else wants to become responder. Should this view release the responder? Returning true allows release 46 | - `View.props.onResponderTerminate: (evt) => {}` - The responder has been taken from the View. Might be taken by other views after a call to `onResponderTerminationRequest`, or might be taken by the OS without asking (happens with control center/ notification center on iOS) 47 | 48 | `evt` is a synthetic touch event with the following form: 49 | 50 | - `nativeEvent` 51 | + `changedTouches` - Array of all touch events that have changed since the last event 52 | + `identifier` - The ID of the touch 53 | + `locationX` - The X position of the touch, relative to the element 54 | + `locationY` - The Y position of the touch, relative to the element 55 | + `pageX` - The X position of the touch, relative to the root element 56 | + `pageY` - The Y position of the touch, relative to the root element 57 | + `target` - The node id of the element receiving the touch event 58 | + `timestamp` - A time identifier for the touch, useful for velocity calculation 59 | + `touches` - Array of all current touches on the screen 60 | 61 | ### Capture ShouldSet Handlers 62 | 63 | `onStartShouldSetResponder` and `onMoveShouldSetResponder` are called with a bubbling pattern, where the deepest node is called first. That means that the deepest component will become responder when multiple Views return true for `*ShouldSetResponder` handlers. This is desirable in most cases, because it makes sure all controls and buttons are usable. 64 | 65 | However, sometimes a parent will want to make sure that it becomes responder. This can be handled by using the capture phase. Before the responder system bubbles up from the deepest component, it will do a capture phase, firing `on*ShouldSetResponderCapture`. So if a parent View wants to prevent the child from becoming responder on a touch start, it should have a `onStartShouldSetResponderCapture` handler which returns true. 66 | 67 | - `View.props.onStartShouldSetResponderCapture: (evt) => true,` 68 | - `View.props.onMoveShouldSetResponderCapture: (evt) => true,` 69 | 70 | ### PanResponder 71 | 72 | For higher-level gesture interpretation, check out [PanResponder](docs/panresponder.html). 73 | -------------------------------------------------------------------------------- /docs/LayoutWithFlexbox-portuguese.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: flexbox 3 | title: Layout with Flexbox 4 | layout: docs 5 | category: The Basics 6 | permalink: docs/flexbox.html 7 | next: handling-text-input 8 | previous: height-and-width 9 | --- 10 | 11 | Os componentes podem especificar o layout dos seus descendentes usando o algoritmo flexbox. O Flexbox é projetado para prover um layout consistente para diferentes tamanhos de tela. 12 | 13 | Você normalmente utilizará uma combinação de `flexDirection`, `alignItems`, e `justifyContent` para se chegar ao layout correto. 14 | 15 | > O Flexbox funciona da mesma forma no React Native quanto no CSS na web, com algumas poucas exceções. Os defaults são diferentes; com o `flexDirection` predefinido com `column` ao invés de `row`, e o parâmetro `flex` com suporte apenas de um só número. 16 | 17 | #### Direcionamento Flex 18 | 19 | Adicionar `flexDirection` a um `style` do componente determina o **eixo primário** de seu layout. É para os descendentes serem organizados horizontalmente (`row`) ou verticalmente (`column`)? O default é `column`. 20 | 21 | ```ReactNativeWebPlayer 22 | import React, { Component } from 'react'; 23 | import { AppRegistry, View } from 'react-native'; 24 | 25 | export default class FlexDirectionBasics extends Component { 26 | render() { 27 | return ( 28 | // Try setting `flexDirection` to `column`. 29 | 30 | 31 | 32 | 33 | 34 | ); 35 | } 36 | }; 37 | 38 | // skip this line if using Create React Native App 39 | AppRegistry.registerComponent('AwesomeProject', () => FlexDirectionBasics); 40 | ``` 41 | 42 | #### Justificar Conteúdo 43 | 44 | Adicionar `justifyContent` a um `style` do componente determina a **distribuição** dos descendentes ao longo do **eixo primário**. É para os descendentes serem distribuídos pelo começo, pelo centro, pelo final, ou espaçados uniformemente? As opções disponíveis são `flex-start`, `center`, `flex-end`, `space-around`, e `space-between`. 45 | 46 | ```ReactNativeWebPlayer 47 | import React, { Component } from 'react'; 48 | import { AppRegistry, View } from 'react-native'; 49 | 50 | export default class JustifyContentBasics extends Component { 51 | render() { 52 | return ( 53 | // Try setting `justifyContent` to `center`. 54 | // Try setting `flexDirection` to `row`. 55 | 60 | 61 | 62 | 63 | 64 | ); 65 | } 66 | }; 67 | 68 | // skip this line if using Create React Native App 69 | AppRegistry.registerComponent('AwesomeProject', () => JustifyContentBasics); 70 | ``` 71 | 72 | #### Alinhar Itens 73 | 74 | Adicionar `alignItems` a um `style` do componente determina o **alinhamento** dos descendentes ao longo do **eixo secundário** (se o eixo primário for `row`, então o secundário é `column`, e vice-versa). É para os descendentes serem alinhados pelo começo, pelo centro, pelo final, or alargados para ocupar tudo? As opções disponíveis são `flex-start`, `center`, `flex-end`, e `stretch`. 75 | 76 | > Para que o `stretch` tenha algum efeito, os descendentes não devem ter dimensão fixa ao longo do eixo secundário. No exemplo a seguir, definir `alignItems: stretch` não faz nada até que o `width: 50` seja removido dos descendentes. 77 | 78 | ```ReactNativeWebPlayer 79 | import React, { Component } from 'react'; 80 | import { AppRegistry, View } from 'react-native'; 81 | 82 | export default class AlignItemsBasics extends Component { 83 | render() { 84 | return ( 85 | // Try setting `alignItems` to 'flex-start' 86 | // Try setting `justifyContent` to `flex-end`. 87 | // Try setting `flexDirection` to `row`. 88 | 94 | 95 | 96 | 97 | 98 | ); 99 | } 100 | }; 101 | 102 | // skip this line if using Create React Native App 103 | AppRegistry.registerComponent('AwesomeProject', () => AlignItemsBasics); 104 | ``` 105 | 106 | #### Indo Mais Fundo 107 | 108 | Cobrimos o básico; porém há muitos outros estilos que você pode precisar para os layouts. A lista completa das props que controlam o layout está documentada [aqui](./docs/layout-props.html). 109 | 110 | Estamos já chegando perto de sermos capazes de desenvolver um aplicativo de verdade. Uma coisa que ainda está nos faltando é uma maneira de pegar o input do usuário; então vamos prosseguir para [aprendermos como operar a entrada de textos com o componente TextInput](docs/handling-text-input.html). 111 | -------------------------------------------------------------------------------- /docs/SignedAPKAndroid.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: signed-apk-android 3 | title: Generating Signed APK 4 | layout: docs 5 | category: Guides (Android) 6 | permalink: docs/signed-apk-android.html 7 | banner: ejected 8 | next: android-building-from-source 9 | previous: headless-js-android 10 | --- 11 | 12 | Android requires that all apps be digitally signed with a certificate before they can be installed, so to distribute your Android application via [Google Play store](https://play.google.com/store), you'll need to generate a signed release APK. The [Signing Your Applications](https://developer.android.com/tools/publishing/app-signing.html) page on Android Developers documentation describes the topic in detail. This guide covers the process in brief, as well as lists the steps required to packaging the JavaScript bundle. 13 | 14 | ### Generating a signing key 15 | 16 | You can generate a private signing key using `keytool`. On Windows `keytool` must be run from `C:\Program Files\Java\jdkx.x.x_x\bin`. 17 | 18 | $ keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000 19 | 20 | This command prompts you for passwords for the keystore and key, and to provide the Distinguished Name fields for your key. It then generates the keystore as a file called `my-release-key.keystore`. 21 | 22 | The keystore contains a single key, valid for 10000 days. The alias is a name that you will use later when signing your app, so remember to take note of the alias. 23 | 24 | _Note: Remember to keep your keystore file private and never commit it to version control._ 25 | 26 | ### Setting up gradle variables 27 | 28 | 1. Place the `my-release-key.keystore` file under the `android/app` directory in your project folder. 29 | 2. Edit the file `~/.gradle/gradle.properties` and add the following (replace `*****` with the correct keystore password, alias and key password), 30 | 31 | ``` 32 | MYAPP_RELEASE_STORE_FILE=my-release-key.keystore 33 | MYAPP_RELEASE_KEY_ALIAS=my-key-alias 34 | MYAPP_RELEASE_STORE_PASSWORD=***** 35 | MYAPP_RELEASE_KEY_PASSWORD=***** 36 | ``` 37 | 38 | These are going to be global gradle variables, which we can later use in our gradle config to sign our app. 39 | 40 | > __Note about saving the keystore:__ 41 | 42 | > Once you publish the app on the Play Store, you will need to republish your app under a different package name (losing all downloads and ratings) if you want to change the signing key at any point. So backup your keystore and don't forget the passwords. 43 | 44 | _Note about security: If you are not keen on storing your passwords in plaintext and you are running OSX, you can also [store your credentials in the Keychain Access app](https://pilloxa.gitlab.io/posts/safer-passwords-in-gradle/). Then you can skip the two last rows in `~/.gradle/gradle.properties`._ 45 | 46 | 47 | ### Adding signing config to your app's gradle config 48 | 49 | Edit the file `android/app/build.gradle` in your project folder and add the signing config, 50 | 51 | ```gradle 52 | ... 53 | android { 54 | ... 55 | defaultConfig { ... } 56 | signingConfigs { 57 | release { 58 | if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) { 59 | storeFile file(MYAPP_RELEASE_STORE_FILE) 60 | storePassword MYAPP_RELEASE_STORE_PASSWORD 61 | keyAlias MYAPP_RELEASE_KEY_ALIAS 62 | keyPassword MYAPP_RELEASE_KEY_PASSWORD 63 | } 64 | } 65 | } 66 | buildTypes { 67 | release { 68 | ... 69 | signingConfig signingConfigs.release 70 | } 71 | } 72 | } 73 | ... 74 | ``` 75 | 76 | ### Generating the release APK 77 | 78 | Simply run the following in a terminal: 79 | 80 | ```sh 81 | $ cd android && ./gradlew assembleRelease 82 | ``` 83 | 84 | Gradle's `assembleRelease` will bundle all the JavaScript needed to run your app into the APK. If you need to change the way the JavaScript bundle and/or drawable resources are bundled (e.g. if you changed the default file/folder names or the general structure of the project), have a look at `android/app/build.gradle` to see how you can update it to reflect these changes. 85 | 86 | The generated APK can be found under `android/app/build/outputs/apk/app-release.apk`, and is ready to be distributed. 87 | 88 | ### Testing the release build of your app 89 | 90 | Before uploading the release build to the Play Store, make sure you test it thoroughly. Install it on the device using: 91 | 92 | ```sh 93 | $ react-native run-android --variant=release 94 | ``` 95 | 96 | Note that `--variant=release` is only available if you've set up signing as described above. 97 | 98 | You can kill any running packager instances, all your framework and JavaScript code is bundled in the APK's assets. 99 | 100 | ### Enabling Proguard to reduce the size of the APK (optional) 101 | 102 | Proguard is a tool that can slightly reduce the size of the APK. It does this by stripping parts of the React Native Java bytecode (and its dependencies) that your app is not using. 103 | 104 | _**IMPORTANT**: Make sure to thoroughly test your app if you've enabled Proguard. Proguard often requires configuration specific to each native library you're using. See `app/proguard-rules.pro`._ 105 | 106 | To enable Proguard, edit `android/app/build.gradle`: 107 | 108 | ```gradle 109 | /** 110 | * Run Proguard to shrink the Java bytecode in release builds. 111 | */ 112 | def enableProguardInReleaseBuilds = true 113 | ``` 114 | -------------------------------------------------------------------------------- /docs/Troubleshooting.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: troubleshooting 3 | title: Troubleshooting 4 | layout: docs 5 | category: Quick Start 6 | permalink: docs/troubleshooting.html 7 | --- 8 | 9 | These are some common issues you may run into while setting up React Native. If you encounter something that is not listed here, try [searching for the issue in GitHub](https://github.com/facebook/react-native/issues/). 10 | 11 | ### Port already in use 12 | 13 | The React Native packager runs on port 8081. If another process is already using that port, you can either terminate that process, or change the port that the packager uses. 14 | 15 | #### Terminating a process on port 8081 16 | 17 | Run the following command on a Mac to find the id for the process that is listening on port 8081: 18 | 19 | ``` 20 | $ sudo lsof -i :8081 21 | ``` 22 | 23 | Then run the following to terminate the process: 24 | 25 | ``` 26 | $ kill -9 27 | ``` 28 | 29 | On Windows you can find the process using port 8081 using [Resource Monitor](https://stackoverflow.com/questions/48198/how-can-you-find-out-which-process-is-listening-on-a-port-on-windows) and stop it using Task Manager. 30 | 31 | #### Using a port other than 8081 32 | 33 | You can configure the packager to use a port other than 8081 by using the `port` parameter: 34 | 35 | ``` 36 | $ react-native start --port=8088 37 | ``` 38 | 39 | You will also need to update your applications to load the JavaScript bundle from the new port. 40 | 41 | ### NPM locking error 42 | 43 | If you encounter an error such as `npm WARN locking Error: EACCES` while using the React Native CLI, try running the following: 44 | 45 | ``` 46 | sudo chown -R $USER ~/.npm 47 | sudo chown -R $USER /usr/local/lib/node_modules 48 | ``` 49 | 50 | ### Missing libraries for React 51 | 52 | If you added React Native manually to your project, make sure you have included all the relevant dependencies that you are using, like `RCTText.xcodeproj`, `RCTImage.xcodeproj`. Next, the binaries built by these dependencies have to be linked to your app binary. Use the `Linked Frameworks and Binaries` section in the Xcode project settings. More detailed steps are here: [Linking Libraries](docs/linking-libraries-ios.html#content). 53 | 54 | If you are using CocoaPods, verify that you have added React along with the subspecs to the `Podfile`. For example, if you were using the ``, `` and `fetch()` APIs, you would need to add these in your `Podfile`: 55 | 56 | ``` 57 | pod 'React', :path => '../node_modules/react-native', :subspecs => [ 58 | 'RCTText', 59 | 'RCTImage', 60 | 'RCTNetwork', 61 | 'RCTWebSocket', 62 | ] 63 | ``` 64 | 65 | Next, make sure you have run `pod install` and that a `Pods/` directory has been created in your project with React installed. CocoaPods will instruct you to use the generated `.xcworkspace` file henceforth to be able to use these installed dependencies. 66 | 67 | #### Argument list too long: recursive header expansion failed 68 | 69 | In the project's build settings, `User Search Header Paths` and `Header Search Paths` are two configs that specify where Xcode should look for `#import` header files specified in the code. For Pods, CocoaPods uses a default array of specific folders to look in. Verify that this particular config is not overwritten, and that none of the folders configured are too large. If one of the folders is a large folder, Xcode will attempt to recursively search the entire directory and throw above error at some point. 70 | 71 | To revert the `User Search Header Paths` and `Header Search Paths` build settings to their defaults set by CocoaPods - select the entry in the Build Settings panel, and hit delete. It will remove the custom override and return to the CocoaPod defaults. 72 | 73 | ### No transports available 74 | 75 | React Native implements a polyfill for WebSockets. These [polyfills](https://github.com/facebook/react-native/blob/master/Libraries/Core/InitializeCore.js) are initialized as part of the react-native module that you include in your application through `import React from 'react'`. If you load another module that requires WebSockets, such as [Firebase](https://github.com/facebook/react-native/issues/3645), be sure to load/require it after react-native: 76 | 77 | ``` 78 | import React from 'react'; 79 | import Firebase from 'firebase'; 80 | ``` 81 | 82 | ## Shell Command Unresponsive Exception 83 | 84 | If you encounter a ShellCommandUnresponsiveException exception such as: 85 | 86 | ``` 87 | Execution failed for task ':app:installDebug'. 88 | com.android.builder.testing.api.DeviceException: com.android.ddmlib.ShellCommandUnresponsiveException 89 | ``` 90 | 91 | Try [downgrading your Gradle version to 1.2.3](https://github.com/facebook/react-native/issues/2720) in `android/build.gradle`. 92 | 93 | ## react-native init hangs 94 | 95 | If you run into issues where running `react-native init` hangs in your system, try running it again in verbose mode and refering to [#2797](https://github.com/facebook/react-native/issues/2797) for common causes: 96 | 97 | ``` 98 | react-native init --verbose 99 | ``` 100 | 101 | ## Unable to start react-native package manager (on Linux) 102 | ### Case 1: Error "code":"ENOSPC","errno":"ENOSPC" 103 | 104 | Issue caused by the number of directories [inotify](https://github.com/guard/listen/wiki/Increasing-the-amount-of-inotify-watchers) (used by watchman on Linux) can monitor. To solve it, just run this command in your terminal window 105 | ``` 106 | echo fs.inotify.max_user_watches=582222 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p 107 | ``` 108 | -------------------------------------------------------------------------------- /docs/JavaScriptEnvironment-portuguese.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: javascript-environment 3 | title: JavaScript Environment 4 | layout: docs 5 | category: Guides 6 | permalink: docs/javascript-environment.html 7 | next: direct-manipulation 8 | previous: gesture-responder-system 9 | --- 10 | 11 | ## Runtime de JavaScript 12 | 13 | Quando estiver usando o React Native, você vai estar rodando o seu código em JavaScript em dois ambientes: 14 | 15 | * Para emuladores e dispositivos de iOS e Android, o React Native utiliza o [JavaScriptCore](http://trac.webkit.org/wiki/JavaScriptCore), que é o motor de JavaScript que move o Safari. No iOS, o JSC não utiliza JIT devido à ausência de memória executável gravável nos apps para iOS. 16 | * Ao utilizar a depuração do Chrome, ele roda todo o código de JavaScript dentro do próprio Chrome, e se comunica com o código nativo via WebSocket. Logo, você está utilizando o [V8](https://code.google.com/p/v8/). 17 | 18 | Ao passo que ambos os ambientes são muito similares, você pode acabar se deparando com algumas inconsistências. Provavelmente iremos experimentar outros motores de JS no futuro; portanto é melhor evitar contar com as particularidades de quaisquer runtimes. 19 | 20 | ## Transformadores de Sintaxe para JavaScript 21 | 22 | Os transformadores de sintaxe faz do ato de escrever código mais aprazível, ao permite-lhe utilizar a nova sintaxe do JavaScript sem ter que aguardar pelo seu suporte para todos os interpretadores. 23 | 24 | Desde a sua versão 0.5.0, o React Native vem com o [compilador de JavaScript Babel](https://babeljs.io). Consulte a [documentação do Babel](https://babeljs.io/docs/plugins/#transform-plugins) sobre as transformações suportadas para mais detalhes. 25 | 26 | Aqui está uma lista completa das [transformações habilitadas](https://github.com/facebook/react-native/blob/master/babel-preset/configs/main.js#L16) do React Native. 27 | 28 | ES5 29 | 30 | * Palavras Reservadas: `promise.catch(function() { });` 31 | 32 | ES6 33 | 34 | * [Arrow functions](http://babeljs.io/docs/learn-es2015/#arrows): ` this.setState({pressed: true})}` 35 | * [Block scoping](https://babeljs.io/docs/learn-es2015/#let-const): `let greeting = 'hi';` 36 | * [Call spread](http://babeljs.io/docs/learn-es2015/#default-rest-spread): `Math.max(...array);` 37 | * [Classes](http://babeljs.io/docs/learn-es2015/#classes): `class C extends React.Component { render() { return ; } }` 38 | * [Constants](https://babeljs.io/docs/learn-es2015/#let-const): `const answer = 42;` 39 | * [Destructuring](http://babeljs.io/docs/learn-es2015/#destructuring): `var {isActive, style} = this.props;` 40 | * [for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of): `for (var num of [1, 2, 3]) {}` 41 | * [Modules](http://babeljs.io/docs/learn-es2015/#modules): `import React, { Component } from 'react';` 42 | * [Computed Properties](http://babeljs.io/docs/learn-es2015/#enhanced-object-literals): `var key = 'abc'; var obj = {[key]: 10};` 43 | * [Object Concise Method](http://babeljs.io/docs/learn-es2015/#enhanced-object-literals): `var obj = { method() { return 10; } };` 44 | * [Object Short Notation](http://babeljs.io/docs/learn-es2015/#enhanced-object-literals): `var name = 'vjeux'; var obj = { name };` 45 | * [Rest Params](https://github.com/sebmarkbage/ecmascript-rest-spread): `function(type, ...args) { }` 46 | * [Template Literals](http://babeljs.io/docs/learn-es2015/#template-strings): ``var who = 'world'; var str = `Hello ${who}`;`` 47 | 48 | ES7 49 | 50 | * [Object Spread](https://github.com/sebmarkbage/ecmascript-rest-spread): `var extended = { ...obj, a: 10 };` 51 | * [Function Trailing Comma](https://github.com/jeffmo/es-trailing-function-commas): `function f(a, b, c,) { }` 52 | * [Async Functions](https://github.com/tc39/ecmascript-asyncawait): `async function doStuffAsync() { const foo = await doOtherStuffAsync(); }`; 53 | 54 | Específicos 55 | 56 | * [JSX](https://facebook.github.io/react/docs/jsx-in-depth.html): `` 57 | * [Flow](http://flowtype.org/): `function foo(x: ?number): string {}` 58 | 59 | 60 | ## Polyfills 61 | 62 | Muitas funções padrões estão também disponíveis para todos os runtimes de JavaScript suportados. 63 | 64 | Navegador 65 | 66 | * [console.{log, warn, error, info, trace, table}](https://developer.chrome.com/devtools/docs/console-api) 67 | * [CommonJS require](https://nodejs.org/docs/latest/api/modules.html) 68 | * [XMLHttpRequest, fetch](docs/network.html#content) 69 | * [{set, clear}{Timeout, Interval, Immediate}, {request, cancel}AnimationFrame](docs/timers.html#content) 70 | * [navigator.geolocation](docs/geolocation.html#content) 71 | 72 | ES6 73 | 74 | * [Object.assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) 75 | * String.prototype.{[startsWith](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith), [endsWith](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith), [repeat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeats), [includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes)} 76 | * [Array.from](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) 77 | * Array.prototype.{[find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find), [findIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex), [includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)} 78 | 79 | ES7 80 | 81 | * Object.{[entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries), [values](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values)} 82 | 83 | Específico 84 | 85 | * `__DEV__` 86 | -------------------------------------------------------------------------------- /docs/Navigation.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: navigation 3 | title: Navigating Between Screens 4 | layout: docs 5 | category: Guides 6 | permalink: docs/navigation.html 7 | next: images 8 | previous: platform-specific-code 9 | --- 10 | 11 | Mobile apps are rarely made up of a single screen. Managing the presentation of, and transition between, multiple screens is typically handled by what is known as a navigator. 12 | 13 | This guide covers the various navigation components available in React Native. 14 | If you are just getting started with navigation, you will probably want to use [React Navigation](docs/navigation.html#react-navigation). React Navigation provides an easy to use navigation solution, with the ability to present common stack navigation and tabbed navigation patterns on both iOS and Android. As this is a JavaScript implementation, it provides the greatest amount of configurability as well as flexibility when integrating with state management libraries such as [redux](https://reactnavigation.org/docs/guides/redux). 15 | 16 | If you're only targeting iOS, you may want to also check out [NavigatorIOS](docs/navigation.html#navigatorios) as a way of providing a native look and feel with minimal configuration, as it provides a wrapper around the native `UINavigationController` class. This component will not work on Android, however. 17 | 18 | If you'd like to achieve a native look and feel on both iOS and Android, or you're integrating React Native into an app that already manages navigation natively, the following libraries provide native navigation on both platforms: [native-navigation](http://airbnb.io/native-navigation/), [react-native-navigation](https://github.com/wix/react-native-navigation). 19 | 20 | ## React Navigation 21 | 22 | The community solution to navigation is a standalone library that allows developers to set up the screens of an app with just a few lines of code. 23 | 24 | The first step is to install in your project: 25 | 26 | ``` 27 | npm install --save react-navigation 28 | ``` 29 | 30 | Then you can quickly create an app with a home screen and a profile screen: 31 | 32 | ``` 33 | import { 34 | StackNavigator, 35 | } from 'react-navigation'; 36 | 37 | const App = StackNavigator({ 38 | Home: { screen: HomeScreen }, 39 | Profile: { screen: ProfileScreen }, 40 | }); 41 | ``` 42 | 43 | Each screen component can set navigation options such as the header title. It can use action creators on the `navigation` prop to link to other screens: 44 | 45 | ``` 46 | class HomeScreen extends React.Component { 47 | static navigationOptions = { 48 | title: 'Welcome', 49 | }; 50 | render() { 51 | const { navigate } = this.props.navigation; 52 | return ( 53 |