React-native-quick-guide
React Native-概要
React Nativeの概念をよりよく理解するために、公式ドキュメントから数行を借ります-
React Nativeでは、JavaScriptのみを使用してモバイルアプリを構築できます。 Reactと同じデザインを使用して、宣言型コンポーネントからリッチモバイルUIを作成できます。 React Nativeでは、モバイルWebアプリ、HTML5アプリ、またはハイブリッドアプリを作成しません。 Objective-CまたはJavaを使用して構築されたアプリと区別できない実際のモバイルアプリを構築します。 React Nativeは、通常のiOSおよびAndroidアプリと同じ基本的なUIビルディングブロックを使用します。 JavaScriptとReactを使用して、これらの構成要素をまとめます。
React Native機能
以下はReact Nativeの機能です-
- React -これは、JavaScriptを使用してWebおよびモバイルアプリを構築するためのフレームワークです。
- ネイティブ-JavaScriptによって制御されるネイティブコンポーネントを使用できます。
- プラットフォーム-React NativeはIOSおよびAndroidプラットフォームをサポートしています。
React Nativeの利点
React Nativeの利点は次のとおりです-
- JavaScript -既存のJavaScriptの知識を使用して、ネイティブモバイルアプリを構築できます。
- コード共有-コードのほとんどを異なるプラットフォームで共有できます。
- コミュニティ-ReactおよびReact Nativeの周りのコミュニティは大きく、必要な答えを見つけることができます。
React Nativeの制限
React Nativeの制限は次のとおりです-
- ネイティブコンポーネント-まだ作成されていないネイティブ機能を作成する場合は、プラットフォーム固有のコードを記述する必要があります。
React Native-環境設定
React Nativeの環境をセットアップするためにインストールする必要があるものがいくつかあります。 OSXを構築プラットフォームとして使用します。
Sr.No. | Software | Description |
---|---|---|
1 | NodeJS and NPM | You can follow our NodeJS Environment Setup tutorial to install NodeJS. |
ステップ1:create-react-native-appをインストールする
NodeJSとNPMをシステムに正常にインストールしたら、create-react-native-appのインストールを続行できます(以下に示すようにグローバルに)。
C:\Users\finddevguides> npm install -g create-react-native-app
ステップ2:プロジェクトを作成する
以下に示すように、必要なフォルダーを参照し、新しい反応ネイティブプロジェクトを作成します。
C:\Users\finddevguides>cd Desktop
C:\Users\finddevguides\Desktop>create-react-native-app MyReactNative
上記のコマンドを実行すると、次の内容の名前が指定されたフォルダーが作成されます。
ステップ3:NodeJS Python Jdk8
Python NodeJSとjdk8がシステムにインストールされていることを確認し、インストールされていない場合はインストールします。 これらに加えて、特定の問題を回避するために最新バージョンのyarnをインストールすることをお勧めします。
ステップ4:React Native CLIをインストールする
以下に示すようにinstall -g react-native-cliコマンドを使用して、npmにreactネイティブコマンドラインインターフェースをインストールできます。
npm install -g react-native-cli
ステップ5:反応ネイティブを開始する
インストールを確認するには、プロジェクトフォルダを参照し、startコマンドを使用してプロジェクトを開始してみてください。
C:\Users\finddevguides\Desktop>cd MyReactNative
C:\Users\finddevguides\Desktop\MyReactNative>npm start
すべてがうまくいった場合、以下に示すようにQRコードを取得します。
指示されているように、Androidデバイスでネイティブアプリを反応させる1つの方法は、expoを使用することです。 Androidデバイスにexpoクライアントをインストールし、上記で取得したQRコードをスキャンします。
ステップ6:プロジェクトを取り出す
Android Studioを使用してAndroidエミュレータを実行する場合は、 ctrl + c を押して現在のコマンドラインから抜けます。
次に、run eject command を実行します
npm run eject
これにより、排出するオプションが表示され、矢印を使用して最初のオプションを選択し、Enterキーを押します。
次に、ホーム画面でアプリの名前と、AndroidスタジオおよびXcodeプロジェクトのプロジェクト名を提案する必要があります。
プロジェクトは正常にイジェクトされますが、エラーが表示される場合があります-
このエラーを無視して、次のコマンドを使用してAndroid用にreact nativeを実行します-
react-native run-android
ただし、その前にAndroid Studioをインストールする必要があります。
ステップ7:Android Studioのインストール
Webページhttps://developer.android.com/studio/にアクセスして、Android Studioをダウンロードします。
そのインストールファイルをダウンロードした後、それをダブルクリックしてインストールを続行します。
ステップ8:AVD Managerの構成
AVD Managerを設定するには、メニューバーのそれぞれのアイコンをクリックします。
ステップ9:AVD Managerの構成
デバイス定義を選択してください。Nexus5Xが推奨されます。
[次へ]ボタンをクリックすると、システムイメージウィンドウが表示されます。 x86 Images タブを選択します。
次に、マシュマロを選択し、次をクリックします。
最後に、[完了]ボタンをクリックして、AVD設定を完了します。
仮想デバイスを構成したら、[アクション]列の下にある再生ボタンをクリックして、Androidエミュレーターを起動します。
ステップ10:Androidを実行する
コマンドプロンプトを開き、プロジェクトフォルダーを参照して、 react-native run-android コマンドを実行します。
次に、アプリの実行が別のプロンプトで開始され、そのステータスを確認できます。
あなたのアンドロイドエミュレータでは、デフォルトアプリの実行を次のように見ることができます-
ステップ11:local.properties
プロジェクトフォルダー SampleReactNative/android (この場合)の android フォルダーを開きます。 local.properties という名前のファイルを作成し、次のパスを追加します。
sdk.dir =/C:\\Users\\finddevguides\\AppData\\Local\\Android\\Sdk
ここで、 finddevguides をユーザー名に置き換えます。
ステップ12:ホットリロード
そして、アプリケーションをビルドするためにApp.jsを変更すると、Androidエミュレーターで変更が自動的に更新されます。
そうでない場合は、Androidエミュレーターをクリックして ctrl + m を押してから、 Enable Hot Reloading オプションを選択します。
React Native-アプリ
デフォルトのアプリを開くと、app.jsファイルが次のようになっていることがわかります。
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default class App extends React.Component {
render() {
return (
<View style = {styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<Text>Changes you make will automatically reload.</Text>
<Text>Shake your phone to open the developer menu.</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
出力
こんにちは世界
「Welcome to finddevguides」という簡単なメッセージを表示するには、CSSパーツを削除し、次に示すように<view> </view>内の<text> </text>タグでラップして印刷するメッセージを挿入します。
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default class App extends React.Component {
render() {
return (
<View>
<Text>Welcome to finddevguides</Text>
</View>
);
}
}
React Native-状態
React Components内のデータは、 state および props によって管理されます。 この章では、*状態*について説明します。
状態と小道具の違い
*state* は可変ですが、 *props* は不変です。 つまり、 *state* は将来更新できますが、propsは更新できません。
状態を使用する
これがルートコンポーネントです。 ほとんどの章で使用される Home をインポートしています。
*App.js*
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default class App extends React.Component {
state = {
myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, used do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.'
}
render() {
return (
<View>
<Text> {this.state.myState} </Text>
</View>
);
}
}
次のスクリーンショットのように、エミュレータテキストで状態を確認できます。
状態の更新
状態は可変なので、 deleteState 関数を作成して更新し、 onPress = \ {this.deleteText} イベントを使用して呼び出すことができます。
*Home.js*
import React, { Component } from 'react'
import { Text, View } from 'react-native'
class Home extends Component {
state = {
myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.'
}
updateState = () ⇒ this.setState({ myState: 'The state is updated' })
render() {
return (
<View>
<Text onPress = {this.updateState}>
{this.state.myState}
</Text>
</View>
);
}
}
export default Home;
注-すべての章で、ステートフル(コンテナ)コンポーネントにはクラス構文を、ステートレス(プレゼンテーション)コンポーネントには関数構文を使用します。 次の章でコンポーネントの詳細を学びます。
また、 updateState の矢印関数構文の使用方法も学習します。 この構文では字句スコープが使用され、 this キーワードは環境オブジェクト(クラス)にバインドされることに注意してください。 これにより、予期しない動作が発生する場合があります。
メソッドを定義するもう1つの方法はEC5関数を使用することですが、その場合はコンストラクタで this を手動でバインドする必要があります。 これを理解するには、次の例を検討してください。
class Home extends Component {
constructor() {
super()
this.updateState = this.updateState.bind(this)
}
updateState() {
//
}
render() {
//
}
}
React Native-小道具
前回の章では、可変*状態*の使用方法を示しました。 この章では、状態と props を組み合わせる方法を示します。
プレゼンテーションコンポーネントは、 props を渡すことですべてのデータを取得する必要があります。 コンテナコンポーネントのみに state が必要です。
コンテナコンポーネント
ここで、コンテナコンポーネントとは何か、またどのように機能するかを理解します。
理論
次に、コンテナコンポーネントを更新します。 このコンポーネントは状態を処理し、小道具をプレゼンテーションコンポーネントに渡します。
コンテナコンポーネントは、状態の処理にのみ使用されます。 ビューに関連するすべての機能(スタイリングなど)は、プレゼンテーションコンポーネントで処理されます。
例
前の章の例を使用する場合、この要素はユーザーにテキストを提示するために使用されるため、レンダリング関数から Text 要素を削除する必要があります。 これは、プレゼンテーションコンポーネント内にある必要があります。
以下の例のコードを確認してみましょう。 PresentationalComponent をインポートして、レンダリング関数に渡します。
*PresentationalComponent* をインポートしてrender関数に渡した後、propsを渡す必要があります。 *myText = \ {this.state.myText}* および *deleteText = \ {this.deleteText}* を *<PresentationalComponent>* に追加して、小道具を渡します。 これで、プレゼンテーションコンポーネント内でこれにアクセスできるようになります。
*App.js*
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import PresentationalComponent from './PresentationalComponent'
export default class App extends React.Component {
state = {
myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, used do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.'
}
updateState = () => {
this.setState({ myState: 'The state is updated' })
}
render() {
return (
<View>
<PresentationalComponent myState = {this.state.myState} updateState = {this.updateState}/>
</View>
);
}
}
プレゼンテーションコンポーネント
これから、プレゼンテーションコンポーネントとは何か、またその仕組みについても理解します。
理論
プレゼンテーションコンポーネントは、ユーザーにビューを表示するためにのみ使用する必要があります。 これらのコンポーネントには状態がありません。 すべてのデータと機能を小道具として受け取ります。
ベストプラクティスは、できるだけ多くのプレゼンテーションコンポーネントを使用することです。
例
前の章で述べたように、プレゼンテーションコンポーネントにはEC6関数構文を使用しています。
コンポーネントは小道具を受け取り、ビュー要素を返し、 \ {props.myText} を使用してテキストを提示し、ユーザーがテキストをクリックすると \ {props.deleteText} 関数を呼び出します。
*PresentationalComponent.js*
import React, { Component } from 'react'
import { Text, View } from 'react-native'
const PresentationalComponent = (props) => {
return (
<View>
<Text onPress = {props.updateState}>
{props.myState}
</Text>
</View>
)
}
export default PresentationalComponent
これで、 State の章と同じ機能を使用できます。 唯一の違いは、コードをコンテナとプレゼンテーションコンポーネントにリファクタリングしたことです。
次のスクリーンショットのように、アプリを実行してテキストを表示できます。
テキストをクリックすると、画面から削除されます。
React Native-スタイリング
React Nativeで要素をスタイルするには、いくつかの方法があります。
*style* プロパティを使用して、スタイルをインラインで追加できます。 ただし、コードを読むのが難しい場合があるため、これはベストプラクティスではありません。
この章では、スタイリングに Stylesheet を使用します。
コンテナコンポーネント
このセクションでは、前の章のコンテナコンポーネントを簡素化します。
*App.js*
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import PresentationalComponent from './PresentationalComponent'
export default class App extends React.Component {
state = {
myState: 'This is my state'
}
render() {
return (
<View>
<PresentationalComponent myState = {this.state.myState}/>
</View>
);
}
}
プレゼンテーションコンポーネント
次の例では、 StyleSheet をインポートします。 ファイルの下部で、スタイルシートを作成し、それを styles 定数に割り当てます。 スタイルは camelCase にあり、スタイリングには px または%を使用しないことに注意してください。
テキストにスタイルを適用するには、 style = \ {styles.myText} プロパティを Text 要素に追加する必要があります。
*PresentationalComponent.js*
import React, { Component } from 'react'
import { Text, View, StyleSheet } from 'react-native'
const PresentationalComponent = (props) => {
return (
<View>
<Text style = {styles.myState}>
{props.myState}
</Text>
</View>
)
}
export default PresentationalComponent
const styles = StyleSheet.create ({
myState: {
marginTop: 20,
textAlign: 'center',
color: 'blue',
fontWeight: 'bold',
fontSize: 20
}
})
アプリを実行すると、次の出力が表示されます。
React Native-フレックスボックス
さまざまな画面サイズに対応するために、React Nativeは Flexbox サポートを提供しています。
*React Native-Styling* の章で使用したものと同じコードを使用します。 *PresentationalComponent* のみを変更します。
レイアウト
目的のレイアウトを実現するために、flexboxには3つの主要なプロパティがあります- flexDirection justifyContent および alignItems 。
次の表は、可能なオプションを示しています。
Property | Values | Description |
---|---|---|
flexDirection | 'column', 'row' | Used to specify if elements will be aligned vertically or horizontally. |
justifyContent | 'center', 'flex-start', 'flex-end', 'space-around', 'space-between' | Used to determine how should elements be distributed inside the container. |
alignItems | 'center', 'flex-start', 'flex-end', 'stretched' | Used to determine how should elements be distributed inside the container along the secondary axis (opposite of flexDirection) |
アイテムを垂直に揃えて一元化する場合は、次のコードを使用できます。
*App.js*
import React, { Component } from 'react'
import { View, StyleSheet } from 'react-native'
const Home = (props) => {
return (
<View style = {styles.container}>
<View style = {styles.redbox}/>
<View style = {styles.bluebox}/>
<View style = {styles.blackbox}/>
</View>
)
}
export default Home
const styles = StyleSheet.create ({
container: {
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'grey',
height: 600
},
redbox: {
width: 100,
height: 100,
backgroundColor: 'red'
},
bluebox: {
width: 100,
height: 100,
backgroundColor: 'blue'
},
blackbox: {
width: 100,
height: 100,
backgroundColor: 'black'
},
})
出力
アイテムを右側に移動し、それらの間にスペースを追加する必要がある場合は、次のコードを使用できます。
*App.js*
import React, { Component } from 'react'
import { View, StyleSheet } from 'react-native'
const App = (props) => {
return (
<View style = {styles.container}>
<View style = {styles.redbox}/>
<View style = {styles.bluebox}/>
<View style = {styles.blackbox}/>
</View>
)
}
export default App
const styles = StyleSheet.create ({
container: {
flexDirection: 'column',
justifyContent: 'space-between',
alignItems: 'flex-end',
backgroundColor: 'grey',
height: 600
},
redbox: {
width: 100,
height: 100,
backgroundColor: 'red'
},
bluebox: {
width: 100,
height: 100,
backgroundColor: 'blue'
},
blackbox: {
width: 100,
height: 100,
backgroundColor: 'black'
},
})
React Native-ListView
この章では、React Nativeでリストを作成する方法を示します。 Home コンポーネントに List をインポートし、画面に表示します。
*App.js*
import React from 'react'
import List from './List.js'
const App = () => {
return (
<List/>
)
}
export default App
リストを作成するには、* map()*メソッドを使用します。 これにより、アイテムの配列が反復処理され、各アイテムがレンダリングされます。
*List.js*
import React, { Component } from 'react'
import { Text, View, TouchableOpacity, StyleSheet } from 'react-native'
class List extends Component {
state = {
names: [
{
id: 0,
name: 'Ben',
},
{
id: 1,
name: 'Susan',
},
{
id: 2,
name: 'Robert',
},
{
id: 3,
name: 'Mary',
}
]
}
alertItemName = (item) => {
alert(item.name)
}
render() {
return (
<View>
{
this.state.names.map((item, index) => (
<TouchableOpacity
key = {item.id}
style = {styles.container}
onPress = {() => this.alertItemName(item)}>
<Text style = {styles.text}>
{item.name}
</Text>
</TouchableOpacity>
))
}
</View>
)
}
}
export default List
const styles = StyleSheet.create ({
container: {
padding: 10,
marginTop: 3,
backgroundColor: '#d9f9b1',
alignItems: 'center',
},
text: {
color: '#4f603c'
}
})
アプリを実行すると、名前のリストが表示されます。
リスト内の各アイテムをクリックして、名前でアラートをトリガーできます。
React Native-テキスト入力
この章では、React Nativeで TextInput 要素を操作する方法を示します。
Homeコンポーネントは、入力をインポートしてレンダリングします。
App.js
import React from 'react';
import Inputs from './inputs.js'
const App = () => {
return (
<Inputs/>
)
}
export default App
入力
初期状態を定義します。
初期状態を定義した後、 handleEmail および handlePassword 関数を作成します。 これらの関数は、状態を更新するために使用されます。
- login()*関数は、状態の現在の値を警告するだけです。
また、他のプロパティをテキスト入力に追加して、自動大文字化を無効にし、Androidデバイスの下部の境界線を削除して、プレースホルダーを設定します。
inputs.js
import React, { Component } from 'react'
import { View, Text, TouchableOpacity, TextInput, StyleSheet } from 'react-native'
class Inputs extends Component {
state = {
email: '',
password: ''
}
handleEmail = (text) => {
this.setState({ email: text })
}
handlePassword = (text) => {
this.setState({ password: text })
}
login = (email, pass) => {
alert('email: ' + email + ' password: ' + pass)
}
render() {
return (
<View style = {styles.container}>
<TextInput style = {styles.input}
underlineColorAndroid = "transparent"
placeholder = "Email"
placeholderTextColor = "#9a73ef"
autoCapitalize = "none"
onChangeText = {this.handleEmail}/>
<TextInput style = {styles.input}
underlineColorAndroid = "transparent"
placeholder = "Password"
placeholderTextColor = "#9a73ef"
autoCapitalize = "none"
onChangeText = {this.handlePassword}/>
<TouchableOpacity
style = {styles.submitButton}
onPress = {
() => this.login(this.state.email, this.state.password)
}>
<Text style = {styles.submitButtonText}> Submit </Text>
</TouchableOpacity>
</View>
)
}
}
export default Inputs
const styles = StyleSheet.create({
container: {
paddingTop: 23
},
input: {
margin: 15,
height: 40,
borderColor: '#7a42f4',
borderWidth: 1
},
submitButton: {
backgroundColor: '#7a42f4',
padding: 10,
margin: 15,
height: 40,
},
submitButtonText:{
color: 'white'
}
})
入力フィールドのいずれかを入力するたびに、状態が更新されます。 Submit ボタンをクリックすると、入力からのテキストがダイアログボックス内に表示されます。
入力フィールドのいずれかを入力するたびに、状態が更新されます。 Submit ボタンをクリックすると、入力からのテキストがダイアログボックス内に表示されます。
React Native-ScrollView
この章では、 ScrollView 要素の使用方法を示します。
再度 ScrollViewExample.js を作成し、 Home にインポートします。
App.js
import React from 'react';
import ScrollViewExample from './scroll_view.js';
const App = () => {
return (
<ScrollViewExample/>
)
}
Scrollviewは名前のリストをレンダリングします。 状態で作成します。
ScrollView.js
import React, { Component } from 'react';
import { Text, Image, View, StyleSheet, ScrollView } from 'react-native';
class ScrollViewExample extends Component {
state = {
names: [
{'name': 'Ben', 'id': 1},
{'name': 'Susan', 'id': 2},
{'name': 'Robert', 'id': 3},
{'name': 'Mary', 'id': 4},
{'name': 'Daniel', 'id': 5},
{'name': 'Laura', 'id': 6},
{'name': 'John', 'id': 7},
{'name': 'Debra', 'id': 8},
{'name': 'Aron', 'id': 9},
{'name': 'Ann', 'id': 10},
{'name': 'Steve', 'id': 11},
{'name': 'Olivia', 'id': 12}
]
}
render() {
return (
<View>
<ScrollView>
{
this.state.names.map((item, index) => (
<View key = {item.id} style = {styles.item}>
<Text>{item.name}</Text>
</View>
))
}
</ScrollView>
</View>
)
}
}
export default ScrollViewExample
const styles = StyleSheet.create ({
item: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
padding: 30,
margin: 2,
borderColor: '#2a4944',
borderWidth: 1,
backgroundColor: '#d2f7f1'
}
})
アプリを実行すると、スクロール可能な名前のリストが表示されます。
React Native-画像
この章では、React Nativeで画像を操作する方法を理解します。
画像を追加する
*src* フォルダー内に新しいフォルダー *img* を作成しましょう。 このフォルダー内に画像( *myImage.png* )を追加します。
ホーム画面に画像を表示します。
App.js
import React from 'react';
import ImagesExample from './ImagesExample.js'
const App = () => {
return (
<ImagesExample/>
)
}
export default App
ローカルイメージには、次の構文を使用してアクセスできます。
image_example.js
import React, { Component } from 'react'
import { Image } from 'react-native'
const ImagesExample = () => (
<Image source = {require('C:/Users/finddevguides/Desktop/NativeReactSample/logo.png')}/>
)
export default ImagesExample
出力
スクリーン密度
React Nativeは、 @ 2x、@ 3x サフィックスを使用して、さまざまなデバイスの画像を最適化する方法を提供します。 アプリは、特定の画面密度に必要な画像のみを読み込みます。
以下は、 img フォルダー内の画像の名前になります。
[email protected]
[email protected]
ネットワーク画像
*require* の代わりにネットワークイメージを使用する場合、 *source* プロパティが必要です。 ネットワークイメージの *width* および *height* を定義することをお勧めします。
App.js
import React from 'react';
import ImagesExample from './image_example.js'
const App = () => {
return (
<ImagesExample/>
)
}
export default App
image_example.js
import React, { Component } from 'react'
import { View, Image } from 'react-native'
const ImagesExample = () => (
<Image source = {{uri:'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png'}}
style = {{ width: 200, height: 200 }}
/>
)
export default ImagesExample
出力
React Native-HTTP
この章では、ネットワークリクエストを処理するために fetch を使用する方法を示します。
App.js
import React from 'react';
import HttpExample from './http_example.js'
const App = () => {
return (
<HttpExample/>
)
}
export default App
フェッチの使用
コンポーネントがマウントされるとすぐに、 componentDidMount ライフサイクルメソッドを使用して、サーバーからデータをロードします。 この関数は、GETリクエストをサーバーに送信し、JSONデータを返し、出力をコンソールに記録し、状態を更新します。
http_example.js
import React, { Component } from 'react'
import { View, Text } from 'react-native'
class HttpExample extends Component {
state = {
data: ''
}
componentDidMount = () => {
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'GET'
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
data: responseJson
})
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<View>
<Text>
{this.state.data.body}
</Text>
</View>
)
}
}
export default HttpExample
出力
React Native-ボタン
この章では、React Nativeのタッチ可能なコンポーネントを示します。 組み込みのアニメーションを提供し、タッチイベントの処理に onPress プロップを使用できるため、「タッチ可能」と呼びます。
Facebookは、汎用ボタンとして使用できる Button コンポーネントを提供しています。 同じことを理解するには、次の例を検討してください。
App.js
import React, { Component } from 'react'
import { Button } from 'react-native'
const App = () => {
const handlePress = () => false
return (
<Button
onPress = {handlePress}
title = "Red button!"
color = "red"
/>
)
}
export default App
デフォルトの Button コンポーネントがニーズに合わない場合は、代わりに次のコンポーネントのいずれかを使用できます。
タッチ可能な不透明度
この要素は、タッチされると要素の不透明度を変更します。
App.js
import React from 'react'
import { TouchableOpacity, StyleSheet, View, Text } from 'react-native'
const App = () => {
return (
<View style = {styles.container}>
<TouchableOpacity>
<Text style = {styles.text}>
Button
</Text>
</TouchableOpacity>
</View>
)
}
export default App
const styles = StyleSheet.create ({
container: {
alignItems: 'center',
},
text: {
borderWidth: 1,
padding: 25,
borderColor: 'black',
backgroundColor: 'red'
}
})
タッチ可能なハイライト
ユーザーが要素を押すと、要素が暗くなり、下にある色が透けて見えます。
App.js
import React from 'react'
import { View, TouchableHighlight, Text, StyleSheet } from 'react-native'
const App = (props) => {
return (
<View style = {styles.container}>
<TouchableHighlight>
<Text style = {styles.text}>
Button
</Text>
</TouchableHighlight>
</View>
)
}
export default App
const styles = StyleSheet.create ({
container: {
alignItems: 'center',
},
text: {
borderWidth: 1,
padding: 25,
borderColor: 'black',
backgroundColor: 'red'
}
})
タッチ可能なネイティブフィードバック
これは、要素が押されたときのインクアニメーションをシミュレートします。
App.js
import React from 'react'
import { View, TouchableNativeFeedback, Text, StyleSheet } from 'react-native'
const Home = (props) => {
return (
<View style = {styles.container}>
<TouchableNativeFeedback>
<Text style = {styles.text}>
Button
</Text>
</TouchableNativeFeedback>
</View>
)
}
export default Home
const styles = StyleSheet.create ({
container: {
alignItems: 'center',
},
text: {
borderWidth: 1,
padding: 25,
borderColor: 'black',
backgroundColor: 'red'
}
})
フィードバックなしでタッチ可能
これは、アニメーションなしでタッチイベントを処理する場合に使用する必要があります。通常、このコンポーネントはあまり使用されません。
<TouchableWithoutFeedback>
<Text>
Button
</Text>
</TouchableWithoutFeedback>
React Native-アニメーション
この章では、React Nativeで LayoutAnimation を使用する方法を示します。
アニメーションコンポーネント
状態のプロパティとして myStyle を設定します。 このプロパティは、 PresentationalAnimationComponent 内の要素のスタイル設定に使用されます。
また、 expandElement と collapseElement の2つの関数を作成します。 これらの関数は、状態から値を更新します。 最初のアニメーションは spring プリセットアニメーションを使用し、2番目のアニメーションは linear プリセットを使用します。 これらも小道具として渡します。 Expand および Collapse ボタンは、* expandElement()および collapseElement()*関数を呼び出します。
この例では、ボックスの幅と高さを動的に変更します。 Home コンポーネントは同じであるため、 Animations コンポーネントのみを変更します。
この例では、ボックスの幅と高さを動的に変更します。 Home コンポーネントは同じであるため、 Animations コンポーネントのみを変更します。
App.js
import React, { Component } from 'react'
import { View, StyleSheet, Animated, TouchableOpacity } from 'react-native'
class Animations extends Component {
componentWillMount = () => {
this.animatedWidth = new Animated.Value(50)
this.animatedHeight = new Animated.Value(100)
}
animatedBox = () => {
Animated.timing(this.animatedWidth, {
toValue: 200,
duration: 1000
}).start()
Animated.timing(this.animatedHeight, {
toValue: 500,
duration: 500
}).start()
}
render() {
const animatedStyle = { width: this.animatedWidth, height: this.animatedHeight }
return (
<TouchableOpacity style = {styles.container} onPress = {this.animatedBox}>
<Animated.View style = {[styles.box, animatedStyle]}/>
</TouchableOpacity>
)
}
}
export default Animations
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
alignItems: 'center'
},
box: {
backgroundColor: 'blue',
width: 50,
height: 100
}
})
React Native-デバッグ
React Nativeには、コードのデバッグに役立つメソッドがいくつか用意されています。
アプリ開発者メニュー内
IOSコマンドで開発者メニューを開くには、 command + D を押します。
Androidエミュレーターでは、 command + M を押す必要があります。
React Native Debugging Developerメニュー
- Reload -シミュレータのリロードに使用されます。 ショートカット command + R を使用できます
- * JSをリモートでデバッグ*-ブラウザ開発者コンソール内でデバッグをアクティブ化するために使用されます。
- ライブリロードを有効にする-コードが保存されるたびにライブリロードを有効にするために使用されます。 デバッガーは localhost:8081/debugger-ui で開きます。
- Start Systrace -Androidマーカーベースのプロファイリングツールの起動に使用されます。
- Show Inspector -コンポーネントに関する情報を見つけることができるインスペクターを開くために使用されます。 ショートカット command + I を使用できます
- パフォーマンスモニターの表示-パフォーマンスモニターは、アプリのパフォーマンスを追跡するために使用されます。
React Native-ルーター
この章では、React Nativeのナビゲーションを理解します。
ステップ1:ルーターをインストールする
まず、 Router をインストールする必要があります。 この章では、React Native Router Fluxを使用します。 プロジェクトフォルダーからターミナルで次のコマンドを実行できます。
npm i react-native-router-flux --save
ステップ2:アプリケーション全体
ルーターにアプリケーション全体を処理させるため、 index.ios.js に追加します。 Androidの場合、 index.android.js でも同じことができます。
App.js
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
import Routes from './Routes.js'
class reactTutorialApp extends Component {
render() {
return (
<Routes/>
)
}
}
export default reactTutorialApp
AppRegistry.registerComponent('reactTutorialApp', () => reactTutorialApp)
ステップ3:ルーターを追加する
ここで、コンポーネントフォルダー内に Routes コンポーネントを作成します。 いくつかのシーンを持つ Router を返します。 各シーンには key、component および title が必要です。 ルーターはキープロパティを使用してシーンを切り替え、コンポーネントが画面にレンダリングされ、タイトルがナビゲーションバーに表示されます。 また、 initial プロパティを、最初にレンダリングされるシーンに設定することもできます。
Routes.js
import React from 'react'
import { Router, Scene } from 'react-native-router-flux'
import Home from './Home.js'
import About from './About.js'
const Routes = () => (
<Router>
<Scene key = "root">
<Scene key = "home" component = {Home} title = "Home" initial = {true}/>
<Scene key = "about" component = {About} title = "About"/>
</Scene>
</Router>
)
export default Routes
ステップ4:コンポーネントを作成する
前の章の Home コンポーネントが既にあります。ここで、 About コンポーネントを追加する必要があります。 goToAbout および goToHome 関数を追加して、シーンを切り替えます。
Home.js
import React from 'react'
import { TouchableOpacity, Text } from 'react-native';
import { Actions } from 'react-native-router-flux';
const Home = () => {
const goToAbout = () => {
Actions.about()
}
return (
<TouchableOpacity style = {{ margin: 128 }} onPress = {goToAbout}>
<Text>This is HOME!</Text>
</TouchableOpacity>
)
}
export default Home
About.js
import React from 'react'
import { TouchableOpacity, Text } from 'react-native'
import { Actions } from 'react-native-router-flux'
const About = () => {
const goToHome = () => {
Actions.home()
}
return (
<TouchableOpacity style = {{ margin: 128 }} onPress = {goToHome}>
<Text>This is ABOUT</Text>
</TouchableOpacity>
)
}
export default About
アプリは最初の*ホーム*画面をレンダリングします。
ボタンを押すと、About画面に切り替えることができます。 戻る矢印が表示されます。それを使用して前の画面に戻ることができます。
React Native-IOSの実行
IOSシミュレーターでアプリをテストする場合、ターミナルでアプリのルートフォルダーを開いて実行するだけです-
react-native run-ios
上記のコマンドは、シミュレーターを起動し、アプリを実行します。
使用するデバイスを指定することもできます。
react-native run-ios --simulator "iPhone 5s
シミュレータでアプリを開いた後、IOSで command + D を押すと、開発者メニューを開くことができます。 詳細については、*デバッグ*の章をご覧ください。
*command&plus;を押してIOSシミュレーターをリロードすることもできます。 R* 。
React Native-Androidの実行
ターミナルで次のコードを実行することで、AndroidプラットフォームでReact Nativeアプリを実行できます。
react-native run-android
Androidデバイスでアプリを実行する前に、 Developer Options 内で USB Debugging を有効にする必要があります。
- USBデバッグ*が有効になっている場合、デバイスを接続して上記のコードスニペットを実行できます。
ネイティブAndroidエミュレーターは遅いです。 アプリをテストするには、https://www.genymotion.com/[Genymotion]をダウンロードすることをお勧めします。
開発者メニューにアクセスするには、 command&plus;を押します。 M 。
React Native-ビュー
ビューは、React Nativeで最も一般的な要素です。 これは、Web開発で使用される div 要素に相当すると考えることができます。
ユースケース
次に、いくつかの一般的な使用例を見てみましょう。
- コンテナ内に要素をラップする必要がある場合、 View をコンテナ要素として使用できます。
- 親要素内により多くの要素をネストする場合、親と子の両方を*表示*にすることができます。 必要な数の子を持つことができます。
- さまざまな要素のスタイルを設定する場合、 style プロパティ、 flexbox などをサポートしているため、それらを View 内に配置できます。
- View は、さまざまな目的に役立つ合成タッチイベントもサポートしています。
前の章ではすでに View を使用していましたが、ほぼすべての後続の章でも使用します。 View は、React Nativeのデフォルト要素と見なすことができます。 以下の例では、2つのビューと1つのテキストをネストします。
App.js
import React, { Component } from 'react'
import { View, Text } from 'react-native'
const App = () => {
return (
<View>
<View>
<Text>This is my text</Text>
</View>
</View>
)
}
export default App
出力
React Native-WebView
この章では、WebViewの使用方法を学習します。 Webページをモバイルアプリにインラインでレンダリングする場合に使用します。
WebViewを使用する
*HomeContainer* はコンテナコンポーネントになります。
App.js
import React, { Component } from 'react'
import WebViewExample from './web_view_example.js'
const App = () => {
return (
<WebViewExample/>
)
}
export default App;
*src/components/home* フォルダー内に *WebViewExample.js* という新しいファイルを作成します。
web_view_example.js
import React, { Component } from 'react'
import { View, WebView, StyleSheet }
from 'react-native'
const WebViewExample = () => {
return (
<View style = {styles.container}>
<WebView
source = {{ uri:
'https://www.google.com/?gws_rd=cr,ssl&ei=SICcV9_EFqqk6ASA3ZaABA#q=finddevguides' }}
/>
</View>
)
}
export default WebViewExample;
const styles = StyleSheet.create({
container: {
height: 350,
}
})
上記のプログラムは、次の出力を生成します。
React Native-モーダル
この章では、React Nativeでモーダルコンポーネントを使用する方法を示します。
新しいファイル ModalExample.js を作成しましょう。
*ModalExample* 内にロジックを配置します。 *toggleModal* を実行して、初期状態を更新できます。
*toggleModal* を実行して初期状態を更新した後、 *visible* プロパティをモーダルに設定します。 このプロップは、状態が変化すると更新されます。
*onRequestClose* はAndroidデバイスに必要です。
App.js
import React, { Component } from 'react'
import WebViewExample from './modal_example.js'
const Home = () => {
return (
<WebViewExample/>
)
}
export default Home;
modal_example.js
import React, { Component } from 'react';
import { Modal, Text, TouchableHighlight, View, StyleSheet}
from 'react-native'
class ModalExample extends Component {
state = {
modalVisible: false,
}
toggleModal(visible) {
this.setState({ modalVisible: visible });
}
render() {
return (
<View style = {styles.container}>
<Modal animationType = {"slide"} transparent = {false}
visible = {this.state.modalVisible}
onRequestClose = {() => { console.log("Modal has been closed.") } }>
<View style = {styles.modal}>
<Text style = {styles.text}>Modal is open!</Text>
<TouchableHighlight onPress = {() => {
this.toggleModal(!this.state.modalVisible)}}>
<Text style = {styles.text}>Close Modal</Text>
</TouchableHighlight>
</View>
</Modal>
<TouchableHighlight onPress = {() => {this.toggleModal(true)}}>
<Text style = {styles.text}>Open Modal</Text>
</TouchableHighlight>
</View>
)
}
}
export default ModalExample
const styles = StyleSheet.create ({
container: {
alignItems: 'center',
backgroundColor: '#ede3f2',
padding: 100
},
modal: {
flex: 1,
alignItems: 'center',
backgroundColor: '#f7021a',
padding: 100
},
text: {
color: '#3f2949',
marginTop: 10
}
})
開始画面は次のようになります-
ボタンをクリックすると、モーダルが開きます。
React Native-ActivityIndicator
この章では、React Nativeでアクティビティインジケーターを使用する方法を示します。
ステップ1:アプリ
*App* コンポーネントは、 *ActivityIndicator* のインポートと表示に使用されます。
App.js
import React from 'react'
import ActivityIndicatorExample from './activity_indicator_example.js'
const Home = () => {
return (
<ActivityIndicatorExample/>
)
}
export default Home
ステップ2:ActivityIndicatorExample
アニメーションプロパティは、アクティビティインジケーターを表示するために使用されるブール値です。 後者は、コンポーネントが取り付けられてから6秒後に閉じます。 これは、* closeActivityIndicator()*関数を使用して行われます。
activity_indicator_example.js
import React, { Component } from 'react';
import { ActivityIndicator, View, Text, TouchableOpacity, StyleSheet } from 'react-native';
class ActivityIndicatorExample extends Component {
state = { animating: true }
closeActivityIndicator = () => setTimeout(() => this.setState({
animating: false }), 60000)
componentDidMount = () => this.closeActivityIndicator()
render() {
const animating = this.state.animating
return (
<View style = {styles.container}>
<ActivityIndicator
animating = {animating}
color = '#bc2b78'
size = "large"
style = {styles.activityIndicator}/>
</View>
)
}
}
export default ActivityIndicatorExample
const styles = StyleSheet.create ({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
marginTop: 70
},
activityIndicator: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
height: 80
}
})
アプリを実行すると、画面にローダーが表示されます。 6秒後に消えます。
React Native Activity Indicator
React Native-ピッカー
この章では、2つの利用可能なオプションを備えた単純なピッカーを作成します。
ステップ1:ファイルを作成する
ここでは、 App.js フォルダーがプレゼンテーションコンポーネントとして使用されます。
App.js
import React from 'react'
import PickerExample from './PickerExample.js'
const App = () => {
return (
<PickerExample/>
)
}
export default App
ステップ2:ロジック
*this.state.user* は、ピッカーコントロールに使用されます。
*updateUser* 関数は、ユーザーが選択されるとトリガーされます。
PickerExample.js
import React, { Component } from 'react';
import { View, Text, Picker, StyleSheet } from 'react-native'
class PickerExample extends Component {
state = {user: ''}
updateUser = (user) => {
this.setState({ user: user })
}
render() {
return (
<View>
<Picker selectedValue = {this.state.user} onValueChange = {this.updateUser}>
<Picker.Item label = "Steve" value = "steve"/>
<Picker.Item label = "Ellen" value = "ellen"/>
<Picker.Item label = "Maria" value = "maria"/>
</Picker>
<Text style = {styles.text}>{this.state.user}</Text>
</View>
)
}
}
export default PickerExample
const styles = StyleSheet.create({
text: {
fontSize: 30,
alignSelf: 'center',
color: 'red'
}
})
出力
名前をクリックすると、3つのオプションすべてが表示されます-
そして、それらのいずれかを選択すると、出力は次のようになります。
React Native-ステータスバー
この章では、React Nativeでステータスバーの外観を制御する方法を示します。
ステータスバーは使いやすく、プロパティを設定して変更するだけです。
*hidden* プロパティを使用して、ステータスバーを非表示にできます。 この例では、 *false* に設定されています。 これはデフォルト値です。
*barStyle* には、 *dark-content、light-content* 、および *default* の3つの値があります。
このコンポーネントには、使用可能な他のプロパティがいくつかあります。 それらのいくつかは、AndroidまたはIOS固有です。 公式ドキュメントで確認できます。
App.js
import React, { Component } from 'react';
import { StatusBar } from 'react-native'
const App = () => {
return (
<StatusBar barStyle = "dark-content" hidden = {false} backgroundColor = "#00BCD4" translucent = {true}/>
)
}
export default App
アプリを実行すると、ステータスバーが表示され、コンテンツの色が濃くなります。
出力
React Native-スイッチ
この章では、2つのステップで Switch コンポーネントについて説明します。
ステップ1:ファイルを作成する
ロジックには HomeContainer コンポーネントを使用しますが、プレゼンテーションコンポーネントを作成する必要があります。
新しいファイル SwitchExample.js を作成しましょう。
ステップ2:ロジック
スイッチ状態を Switch コンポーネントに切り替えるための state および関数から値を渡します。 状態の更新にはトグル機能が使用されます。
App.js
import React, { Component } from 'react'
import { View } from 'react-native'
import SwitchExample from './switch_example.js'
export default class HomeContainer extends Component {
constructor() {
super();
this.state = {
switch1Value: false,
}
}
toggleSwitch1 = (value) => {
this.setState({switch1Value: value})
console.log('Switch 1 is: ' + value)
}
render() {
return (
<View>
<SwitchExample
toggleSwitch1 = {this.toggleSwitch1}
switch1Value = {this.state.switch1Value}/>
</View>
);
}
}
ステップ3:プレゼンテーション
スイッチコンポーネントは2つの小道具を取ります。 onValueChange propは、ユーザーがスイッチを押した後にトグル機能をトリガーします。 value propは HomeContainer コンポーネントの状態にバインドされます。
switch_example.js
import React, { Component } from 'react'
import { View, Switch, StyleSheet }
from 'react-native'
export default SwitchExample = (props) => {
return (
<View style = {styles.container}>
<Switch
onValueChange = {props.toggleSwitch1}
value = {props.switch1Value}/>
</View>
)
}
const styles = StyleSheet.create ({
container: {
flex: 1,
alignItems: 'center',
marginTop: 100
}
})
スイッチを押すと、状態が更新されます。 コンソールで値を確認できます。
出力
React Native-テキスト
この章では、React Nativeの Text コンポーネントについて説明します。
このコンポーネントはネストでき、親から子にプロパティを継承できます。 これは多くの点で役立ちます。 最初の文字を大文字にする、単語やテキストの一部をスタイリングするなどの例を示します。
ステップ1:ファイルを作成する
作成するファイルは text_example.js です
ステップ2:App.js
このステップでは、単純なコンテナを作成します。
App.js
import React, { Component } from 'react'
import TextExample from './text_example.js'
const App = () => {
return (
<TextExample/>
)
}
export default App
ステップ3:テキスト
このステップでは、継承パターンを使用します。 styles.text はすべての Text コンポーネントに適用されます。
また、テキストの一部に他のスタイリングプロパティを設定する方法にも注目してください。 すべての子要素には親スタイルが渡されることを知っておくことが重要です。
text_example.js
import React, { Component } from 'react';
import { View, Text, Image, StyleSheet } from 'react-native'
const TextExample = () => {
return (
<View style = {styles.container}>
<Text style = {styles.text}>
<Text style = {styles.capitalLetter}>
L
</Text>
<Text>
orem ipsum dolor sit amet, sed do eiusmod.
</Text>
<Text>
Ut enim ad <Text style = {styles.wordBold}>minim </Text> veniam,
quis aliquip ex ea commodo consequat.
</Text>
<Text style = {styles.italicText}>
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum.
</Text>
<Text style = {styles.textShadow}>
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
</Text>
</Text>
</View>
)
}
export default TextExample
const styles = StyleSheet.create ({
container: {
alignItems: 'center',
marginTop: 100,
padding: 20
},
text: {
color: '#41cdf4',
},
capitalLetter: {
color: 'red',
fontSize: 20
},
wordBold: {
fontWeight: 'bold',
color: 'black'
},
italicText: {
color: '#37859b',
fontStyle: 'italic'
},
textShadow: {
textShadowColor: 'red',
textShadowOffset: { width: 2, height: 2 },
textShadowRadius : 5
}
})
次の出力が表示されます-
React Native-アラート
この章では、カスタム*アラート*コンポーネントの作成方法を理解します。
ステップ1:App.js
import React from 'react'
import AlertExample from './alert_example.js'
const App = () => {
return (
<AlertExample/>
)
}
export default App
ステップ2:alert_example.js
*showAlert* 関数をトリガーするためのボタンを作成します。
import React from 'react'
import { Alert, Text, TouchableOpacity, StyleSheet } from 'react-native'
const AlertExample = () => {
const showAlert = () =>{
Alert.alert(
'You need to...'
)
}
return (
<TouchableOpacity onPress = {showAlert} style = {styles.button}>
<Text>Alert</Text>
</TouchableOpacity>
)
}
export default AlertExample
const styles = StyleSheet.create ({
button: {
backgroundColor: '#4ba37b',
width: 100,
borderRadius: 50,
alignItems: 'center',
marginTop: 100
}
})
出力
あなたがボタンをクリックすると、次が表示されます-
React Native-ジオロケーション
この章では、 Geolocation の使用方法を示します。
ステップ1:App.js
import React from 'react'
import GeolocationExample from './geolocation_example.js'
const App = () => {
return (
<GeolocationExample/>
)
}
export default App
ステップ2:ジオロケーション
最初と最後の位置を保持する初期状態を設定することから始めます。
次に、 navigator.geolocation.getCurrentPosition を使用してコンポーネントがマウントされたときに、デバイスの現在の位置を取得する必要があります。 状態を更新できるように、応答を文字列化します。
*navigator.geolocation.watchPosition* は、ユーザーの位置を追跡するために使用されます。 このステップでウォッチャーもクリアします。
AsyncStorageExample.js
import React, { Component } from 'react'
import { View, Text, Switch, StyleSheet} from 'react-native'
class SwichExample extends Component {
state = {
initialPosition: 'unknown',
lastPosition: 'unknown',
}
watchID: ?number = null;
componentDidMount = () => {
navigator.geolocation.getCurrentPosition(
(position) => {
const initialPosition = JSON.stringify(position);
this.setState({ initialPosition });
},
(error) => alert(error.message),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
this.watchID = navigator.geolocation.watchPosition((position) => {
const lastPosition = JSON.stringify(position);
this.setState({ lastPosition });
});
}
componentWillUnmount = () => {
navigator.geolocation.clearWatch(this.watchID);
}
render() {
return (
<View style = {styles.container}>
<Text style = {styles.boldText}>
Initial position:
</Text>
<Text>
{this.state.initialPosition}
</Text>
<Text style = {styles.boldText}>
Current position:
</Text>
<Text>
{this.state.lastPosition}
</Text>
</View>
)
}
}
export default SwichExample
const styles = StyleSheet.create ({
container: {
flex: 1,
alignItems: 'center',
marginTop: 50
},
boldText: {
fontSize: 30,
color: 'red',
}
})
React Native-AsyncStorage
この章では、 AsyncStorage を使用してデータを永続化する方法を示します。
ステップ1:プレゼンテーション
このステップでは、 App.js ファイルを作成します。
import React from 'react'
import AsyncStorageExample from './async_storage_example.js'
const App = () => {
return (
<AsyncStorageExample/>
)
}
export default App
ステップ2:ロジック
初期状態の*名前*は空の文字列です。 コンポーネントがマウントされたら、永続ストレージから更新します。
*setName* は入力フィールドからテキストを取得し、 *AsyncStorage* を使用して保存し、状態を更新します。
async_storage_example.js
import React, { Component } from 'react'
import { StatusBar } from 'react-native'
import { AsyncStorage, Text, View, TextInput, StyleSheet } from 'react-native'
class AsyncStorageExample extends Component {
state = {
'name': ''
}
componentDidMount = () => AsyncStorage.getItem('name').then((value) => this.setState({ 'name': value }))
setName = (value) => {
AsyncStorage.setItem('name', value);
this.setState({ 'name': value });
}
render() {
return (
<View style = {styles.container}>
<TextInput style = {styles.textInput} autoCapitalize = 'none'
onChangeText = {this.setName}/>
<Text>
{this.state.name}
</Text>
</View>
)
}
}
export default AsyncStorageExample
const styles = StyleSheet.create ({
container: {
flex: 1,
alignItems: 'center',
marginTop: 50
},
textInput: {
margin: 5,
height: 100,
borderWidth: 1,
backgroundColor: '#7685ed'
}
})
アプリを実行すると、入力フィールドに入力してテキストを更新できます。