ReactNative-スイッチ

この章では、 Switch いくつかのステップでコンポーネント。

ステップ1:ファイルを作成する

を使用します HomeContainer ロジックのコンポーネントですが、プレゼンテーションコンポーネントを作成する必要があります。

新しいファイルを作成しましょう。 SwitchExample.js

ステップ2:ロジック

から値を渡します state とスイッチアイテムを切り替えるための機能 SwitchExample成分。状態の更新にはトグル機能が使用されます。

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 小道具はの状態にバインドされています 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
   }
})

スイッチを押すと状態が更新されます。コンソールで値を確認できます。

出力