ラベル

2017年1月25日水曜日

[React Native] いろいろなButtonライブラリを試してみる

公式のButtonコンポーネントが残念だったので、いろいろなライブラリを試してみようと思います。

react-native-button


ide/react-native-button
https://github.com/ide/react-native-button

さっそく

npm install react-native-button --save

READMEを参考にコードを書くとこんな感じ

enter image description here

Container Styleはシンプルで使えそう!

コードはこんな感じ

<Button
  style={{fontSize: 20, color: 'gray'}}
  styleDisabled={{color: 'black'}}
  onPress={() => this._handlePress()}>
  Usage
</Button>

<Button
  containerStyle={{padding:10, height:45, overflow:'hidden', borderRadius:4, backgroundColor: '#99AAFF'}}
  style={{fontSize: 20, color: 'gray'}}>
  Container Style
</Button>

APSL/react-native-button


APSL/react-native-button
https://github.com/APSL/react-native-button

enter image description here

このライブラリはオプションがたくさんあって幅は広そう
個人的にisLoadingが良かったです。

enter image description here

ここら辺でボタンのコンポーネントは自作したほうが良いことに察したので、
次回はボタンを自作してみようと思います。

[ReactNative] Buttonコンポーネントを使ってみる

今回はReact Native公式のButtonコンポーネントを使ってみましょう

http://facebook.github.io/react-native/releases/next/docs/button.html#button


アプリをビルド


もちろん既存のアプリで全然大丈夫です。
react-native init AwesomeProject
cd AwesomeProject
react-native run-ios
完全に公式Getting Startedのコピペ
おなじみの下の画面になるはず

enter image description here

Buttonコンポーネント使ってみる


公式に載ってるExample usage


<Button
  onPress={onPressLearnMore}
  title="Learn More"
  color="#841584"
  accessibilityLabel="Learn more about this purple button"
/>
Example usageを参考にindex.ios.jsを編集します。
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Button
} from 'react-native';

export default class AwesomeProject extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Button
          onPress={() => console.log('test')}
          title="Learn More"
          color="#841584"
          accessibilityLabel="Learn more about this purple button"
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
});

AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
無事ボタンが作成できました!
ボタンてよりかはほぼほぼリンクw

ボタンを無効にする


disabledを追加するとボタンが灰色がかって、押せなくなります。
これはちょっと便利

<Button
  onPress={() => console.log('test')}
  title="押せないボタン"
  disabled
/>
enter image description here


Alertと組み合わせる


ボタンを押すとウインドウが出現する機能をつけてみましょう。
Alertを追加します。

import {
  //省略
  Alert
} from 'react-native';
あとはこんな感じ
export default class AwesomeProject extends Component {
  render() {
    return (
      <View style={styles.container}>
      <Button
        onPress={this.alertMessage}
        title="ボタン"
      />
      </View>
    );
  }
  alertMessage() {
    Alert.alert('Button has been pressed!');
 }
}
alertMessage関数を作ってButtonのonPressに渡してあげるだけです。

enter image description here

最後に

うーん。ちゃんとstyleを当ててあげないとボタンぽくならないのが残念ですね。

公式ではTouchableOpacity や TouchableNativeFeedbackを使って独自のボタンを作れるとのこと、次回試してみたいと思います。