はじめに
ReactNativeを使っている方の多くは、NativeBaseに触れたことがあると思います。
その中でもとりわけ重宝するのがIconですが、そこにちょっとアレンジを加えたいなと思う今日この頃。
例えば、アイコンを丸く表示してみたり…
やってみた
RoundIcon.tsx
import React, {Component} from 'react';
import {StyleSheet, TouchableOpacity} from 'react-native';
import {Icon, View} from 'native-base';
/**
* Props
*/
export interface RoundIconProps{
type?: "AntDesign" | "Entypo" | "EvilIcons" | "Feather" | "FontAwesome" | "FontAwesome5" | "Foundation" | "Ionicons" | "MaterialCommunityIcons" | "MaterialIcons" | "Octicons" | "SimpleLineIcons" | "Zocial";
name: string;
key?: string;
onPressIcon?: () => void;
color?: string;
bgColor?: string;
small?: boolean;
large?: boolean;
}
/**
* 丸アイコン
*/
class RoundIcon extends React.Component<RoundIconProps, {}> {
/**
* コンストラクタ
* @param props
*/
constructor(props: RoundIconProps){
super(props);
}
/**
* コンポーネント描画処理
*/
render(){
let icon: JSX.Element;
const type: "AntDesign" | "Entypo" | "EvilIcons" | "Feather" | "FontAwesome" | "FontAwesome5" | "Foundation" | "Ionicons" | "MaterialCommunityIcons" | "MaterialIcons" | "Octicons" | "SimpleLineIcons" | "Zocial" = this.props.type? this.props.type : "FontAwesome";
const name: string = this.props.name;
const color: string = this.props.color? this.props.color: "#FFFFFF";
const bgColor: string = this.props.bgColor? this.props.bgColor : "#A1A1A1";
// Iconサイズ
let wh : number = 42;
let radius: number = 21;
let iconSize: number = 20;
// small表示
if(this.props.small){
wh = 36;
radius = 18;
iconSize = 16;
}
// large表示
if(this.props.large){
wh = 48;
radius = 24;
iconSize = 27;
}
// onPressが指定されていたらTouchableOpacity
if(this.props.onPressIcon){
icon = (
<TouchableOpacity style={[styles.iconWrap, {backgroundColor: bgColor, width: wh, height: wh, borderRadius: radius}]} onPress={this.props.onPressIcon}>
<Icon type={type} name={name} style={{color: color, fontSize: iconSize}}/>
</TouchableOpacity>
)
}
else {
icon = (
<View style={[styles.iconWrap, {backgroundColor: bgColor, width: wh, height: wh, borderRadius: radius}]}>
<Icon type={type} name={name} style={{color: color, fontSize: iconSize}} />
</View>
)
}
// key設定
if(this.props.key){
icon.key = this.props.key;
}
return icon;
}
}
/**
* スタイル定義
*/
const styles: StyleSheet.NamedStyles<any> = StyleSheet.create({
iconWrap: {
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
}
});
export default RoundIcon;
作り自体はIconをラップしただけの簡素なものになっています。
呼び出す時は以下のように記述します。
<RoundIcon type="FontAwesome5" name="amazon" bgColor="#FFAD46" color="#FFFFFF" />
感想
同じようなことをされている方は既にいると思うので、何番煎じかもわからないような内容ではあります。
ただ、オリジナルのコンポーネントを自作するのはなかなか楽しいですね。