ReactNaitiveボタンを作成する
ボタンを押すと、テキストが表示される仕組みを作成します。
まずはテキストを変更した元コードです。
import { Text, View } from "react-native";
export default function Index() {
return (
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center",
}}
>
<Text>Hello! こんにちは</Text>
</View>
);
}
まず必要なButton
とuseState
をインポートします。
import React, { useState } from "react";
import { Text, View, Button } from "react-native";
useState
を使って、ボタンが押されたかどうかの状態を管理します。
export default function Index() {
const [showText, setShowText] = useState(false);
return (
constは定数で、一度代入すると後からその変数に別の値を代入できません。
useStateにはまずfalse
を入れておきます。
Buttonを追加し、押された時にsetShowText(true)を呼び出します。
<Text>Hello! こんにちは</Text>
<Button title="テキストを表示" onPress={() => setShowText(true)} />
showTextがtrueのときのみテキストを表示します。
<Text>Hello! こんにちは</Text>
<Button title="テキストを表示" onPress={() => setShowText(true)} />
{showText && <Text>ボタンが押されました!</Text>}
</View>
全体のコード以下の通りです。
import React, { useState } from "react";
import { Text, View, Button } from "react-native";
export default function Index() {
const [showText, setShowText] = useState(false);
return (
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center",
}}
>
<Text>Hello! こんにちは</Text>
<Button title="テキストを表示" onPress={() => setShowText(true)} />
{showText && <Text>ボタンが押されました!</Text>}
</View>
);
}
これからボタンのデザインを変更していきます。
Button
Buttonの部分にcolorを指定してあげます。
<Button title="テキストを表示" color="#FFA500" onPress={() => setShowText(true)} />
これによりボタンがオレンジ色になります。
さらに、ボタンのデザインを細かく調整できるようにします。
import { Text, View, TouchableOpacity, StyleSheet } from "react-native";
Buttonの代わりにTouchableOpacity(タッチャブル・オパシティ)とStyleSheetを使います。
Viewの下に、
const buttonStyles = StyleSheet.create({
button: {
backgroundColor: '#FFA500',
padding: 10,
borderRadius: 20,
shadowColor: '#000',
},
});
と追加します。
その後にButtonの部分をTouchableOpacityに変更します。
<TouchableOpacity style={buttonStyles.button} onPress={() => setShowText(true)} >
<Text style={{ color: "#fff" }}>テキストを表示</Text>
</TouchableOpacity>
Buttonとは違い、TouchableOpacityを使用すると、余白、角丸、影など細かくデザインを調整することが可能です。
全体のコード
import React, { useState } from "react";
import { Text, View, TouchableOpacity, StyleSheet } from "react-native";
export default function Index() {
const [showText, setShowText] = useState(false);
return (
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center",
}}
>
<Text>Hello! こんにちは</Text>
<TouchableOpacity style={buttonStyles.button} onPress={() => setShowText(true)} >
<Text style={{ color: "#fff" }}>テキストを表示</Text>
</TouchableOpacity>
{showText && <Text>ボタンが押されました!</Text>}
</View>
);
}
const buttonStyles = StyleSheet.create({
button: {
backgroundColor: '#FFA500',
padding: 10,
borderRadius: 20,
shadowColor: '#000',
},
});
出力結果
TouchableOpacityとButtonの違い
TouchableOpacity
ボタンのデザインをカスタマイズしたい
テキストだけでなく、アイコンや画像を含めたい
ボタン以外の要素(例えばカスタムカードやリストアイテム)でタッチ可能な領域を作りたい
Button
シンプルなボタンで十分な時
カスタマイズが不要で、すぐに使えるボタンが欲しい
まとめ
- 状態管理には
useState
を使う - ボタンをカスタマイズしたい場合は
TouchableOpacity
が便利
参考URL