propsの引き渡し
コンポーネントと画面ができたので、それを更新して、ハードコードされた情報を表示するのではなく、渡されたデータをレンダリングできるようにする必要があります。React Nativeのコンポーネント間でデータを受け渡す方法の1つにpropsがあります。
props(properties(プロパティ)の略)はReactコンポーネントに渡される引数です。関数にpropsを追加し、props変数を参照すると、次のようなパラメーターにアクセスできます。
const MyComponent = props => {
console.log(props.arg1);
};
データにアクセスするもう1つの方法は、propsから必要な引数を分割する方法です。
const MyComponent = ({arg1}) => {
console.log(arg1);
};
このガイドでは、両方の方法を使用します。
VideoCardへのpropsの追加
VideoCardにpropsを追加しましょう。まず、TypeScriptでpropsのデータ型を定義します。TypeScriptでは、インターフェイスがこれらの型の命名や定義を行う役割を担っています。インターフェイスは、コード内のコントラクトや、プロジェクト外のコードとのコントラクトを定義する強力な手段です。
propsのインターフェイスを定義しましょう。
VideoCard.tsxを開き、importステートメントの下に、propsの型を宣言するインターフェイスを挿入します。
interface IProps {
title: string;
imgURL: string;
description: string;
}
- VideoCardのアロー関数で、インターフェイスの各フィールドを分割します。
:IPropsを追加して、オブジェクトの各フィールドの型を適用します。
const VideoCard = ({title, imgURL, description}: IProps) => {};
- ハードコードされた値を該当する値に置き換えます。
<View style={styles.videoCardContainer}>
<Image style={styles.videoImage} source={{uri: imgURL}} />
<View style={styles.videoTextContainer}>
<Text style={styles.videoTitle}>{title}</Text>
<Text style={styles.videoDescription}>{description}</Text>
</View>
</View>
更新されたVideoCard.tsxは次のようになります。
import * as React from 'react';
import {StyleSheet, Text, View, Image} from 'react-native';
interface IProps {
title: string;
imgURL: string;
description: string;
}
const VideoCard = ({title, imgURL, description}: IProps) => {
return (
<View style={styles.videoCardContainer}>
<Image style={styles.videoImage} source={{uri: imgURL}} />
<View style={styles.videoTextContainer}>
<Text style={styles.videoTitle}>{title}</Text>
<Text style={styles.videoDescription}>{description}</Text>
</View>
</View>
);
};
const styles = StyleSheet.create({
videoCardContainer: {
height: 400,
width: 550,
borderWidth: 1,
borderColor: 'white',
borderRadius: 5,
},
videoTextContainer: {
height: '25%',
display: 'flex',
justifyContent: 'space-around',
padding: 10,
},
videoImage: {
height: '75%',
},
videoTitle: {
fontSize: 20,
fontWeight: 'bold',
color: 'white',
},
videoDescription: {
color: 'white',
},
});
export default VideoCard;
VideoCardへのpropsの引き渡し
次に、ランディング画面を更新して値をVideoCardに渡す必要があります。
LandingScreen.tsxを開きます。title、description、imgURLをVideoCardコンポーネントに渡します。propsを渡していることを確認しやすいように、titleを「マイビデオ」に、descriptionを「マイビデオの説明」に変更します。
更新されたLandingScreen.tsxは次のようになります。
import * as React from 'react';
import Header from '../components/Header';
import VideoCard from '../components/VideoCard';
const LandingScreen = () => {
return (
<>
<Header />
<VideoCard
title="マイビデオ"
description="マイビデオの説明"
imgURL="https://le1.cdn01.net/videos/0000169/0169322/thumbs/0169322__002f.jpg"
/>
</>
);
};
export default LandingScreen;
- 必要に応じて [play] をクリックするか「R」キーを押してアプリを再読み込みすると、値が更新されたビデオカードが表示されます。


