前回
今回はこのラーニングモジュールをやっていく
props
関数の引数に props を設定すると、呼び出し元のインスタンスを受け取ることができるみたい。props は特別な変数?なのかな。読み取り専用らしい。
import React from 'react'; function RecipeTitle(props) { return ( <section> <h2>{ props.title} </h2> </section> ) }; export default RecipeTitle;
App.jsx にて、レシピのオブジェクトを定義する。
import './index.css' import React from 'react'; import RecipeTitle from './RecipeTitle'; function App() { const recipe = { title: 'Mashed potatoes', feedback: { rating: 4.8, reviews: 20 }, ingredients: [ { name: '3potatoes, cut into 1/2 pieces', prepared: false}, { name: '4 Tbsp butter', prepared: false}, { name: '1/8 cup heavy cream', prepared: false}, { name: 'salt', prepared: true}, { name: 'Pepper', prepared: true}, ], }; return ( <article> <h1>Recipe Manager</h1> <RecipeTitle title={ recipe.title }/> </article> ) } export default App;
これで実行するとタイトルが表示される。
RecipeTitle 関数に引数を設定すると、App.jsx からコンポーネントを呼び出すときに、パラメータを与えることができるみたい。ここに、recipe オブジェクトを入れることで、レシピに関する情報を表示できる。
三項演算子
三項演算子については C# も同じなので、大丈夫そう。Web の場合は条件によって、例えばフォントの色を変更したりできるみたい。まずは RecipeTitle.css を src に追加する。
.red { color: red; } .green { color: green; }
次に、RecipeTitle.jsx にスタイルを import して、三項演算子を記述。
<h3 className={ props.feedback.rating <= 3.5 ? 'red' : 'green'}> { props.feedback.rating } from { props.feedback.reviews } reviews </h3>
あとは、パラメータをもう一つ渡すために、App.jsx のコンポーネントにもう一つパラメータを記述。
<RecipeTitle title={ recipe.title } feedback={ recipe.feedback }/>
これで feedback に関するパラメータを recipe オブジェクトから持ってきて、RecipeTitle の props で受け取ることができるわけだ。
配列データ
JavaScript では配列を map 関数で使うらしい。配列は C# にもあるので宣言については問題ないが、それを使うときがちょっと難しさを感じる。とりあえず、IngredientList.jsx と IngredientList.css を src ディレクトリの中につくる。
import './IngredientList.css' import React from 'react'; function IngredientList(props) { const ingredientListItems = props.ingredients.map((ingredient, index) => { return ( <li key={index} className={ ingredient.prepared ? 'prepared' : '' }> { ingredient.name } </li> ); }); return ( <ul> { ingredientListItems } </ul> ); } export default IngredientList;
.prepared { text-decoration: line-through; }
map 関数は C# でいうところの foreach ステートメントに似ていて、すべての要素にアクセスできるが、map 関数は処理した要素を返すことができる。JS にも foreach はあるが、コンポーネント要素を戻したいときには map を使うほうが適切ということなのかも?
で、return が2つあるのでちょっと混乱したが、map 用の return と、IngredientList 用の return があってちょっとややこしいかな。これは括弧の問題な気もするが...。
あとはこのコンポーネントを App.jsx から呼び出すだけ。
import IngredientList from './IngredientList'; <IngredientList ingredients={recipe.ingredients}/>
実行したら、レシビが表示された。
なんとなくコンポーネントの使い方とか、配列の使いかたとかがわかってきたかも。
イベントのお知らせ
2022年4月24日(日)に MS Tech Camp #14 を開催します。今回は私「たくのろじぃ」主催で、Blazor を使ったポートフォリオサイト製作と Azure Static Web Apps へのデプロイをやります。 興味がある方は(社会人、学生問わず)ぜひご参加ください! Youtube での配信ですので、休日はごろごろしながらご覧いただければと思います。もちろん、一緒にやっていただいても結構です!