#5 【React.jsで、BlackJackを作る】:カードを重ねて表示する
これまで
前回は、プレイヤーが HIT したときの処理を実装しました。
BlackJack アプリの sandbox
BlackJack アプリの sandbox は以下です。
この sandbox は、連載が進むのと同時に更新されていきます。
「私も作りたい!」という方は、フォークして一緒に作り始めることができます。
カードを重ねて表示する
HIT ボタンを何回かポチポチすると、やはり画面が崩れてしまいました。
なので、カードを重ねて表示するようにします。
src/components/PlayArea.js
やはり修正することになりましたね。
元のコードは以下です。
export default function PlayArea(props) {
const classes = useStyles();
return (
<Box className={classes.playArea}>
<Grid
container
direction="column"
spacing={5}
alignItems="center"
justify="center"
>
<Grid item>
<Grid container direction="row" spacing={1}>
{props.dealersHand.map((card, index) => {
return (
<Grid item key={index}>
<Card card={card} />
</Grid>
);
})}
</Grid>
</Grid>
<Grid item>
<Grid container direction="row" spacing={1}>
{props.playersHand.map((card, index) => {
return (
<Grid item key={index}>
<Card card={card} />
</Grid>
);
})}
</Grid>
</Grid>
</Grid>
</Box>
);
}
修正をするにあたり、以下の二つの案が浮かびました。
案1:Card.js で margin設定をする
Card.js のフック useCardStyles() で margin 設定をする案です。
以下、該当部分を抜粋します。
PlayArea.js
<Grid item>
// Box に変更
<Box display="flex" flexDirection="row">
{props.playersHand.map((card, index) => {
// props で marginLeft の値を渡す
let marginLeft = index === 0 ? "0px" : "-45px"
return (
<Card card={card} marginLeft={marginLeft}/>
);
})}
</Box>
</Grid>
Card.js
const useCardStyles = makeStyles({
root: {
width: "105px",
height: "150px",
color: 省略
marginLeft: props => props.marginLeft
},
案2::PlayArea.js で margin設定をする
PlayArea.js の Grid に margin 設定をする案です。
以下、該当部分を抜粋します。
<Grid item>
<Grid container direction="row" spacing={1}>
{props.dealersHand.map((card, index) => {
let marginLeft = index === 0 ? "0px" : "-45px"
return (
<Grid item key={index} style={{marginLeft: marginLeft}}>
<Card card={card} />
</Grid>
);
})}
</Grid>
</Grid>
案2にしました
Card.js にスタイル設定のためのフック useCardStyles() があったので、margin の設定もそこで行うべきかなと最初は思いました。
ただ、フック useCardStyles() はあくまでカード自体のスタイルを設定するものです。
カードがどのように並べられるかは Card.js には関係のないことだと思うので、PlayArea.js で行うことにしました。
現在の画面
今回の修正で画面は以下のようになりました。
重ねたことでカードの境目がわかりにくくなったので、border の設定を追加しています。
詳しい変更はこちら
Codesandbox は GitHub連携ができます。
以下は今回のコミットによる差分です。
次回
これで見栄えがだいぶ良くなってきましたね!
次回は、プレイヤーが STAND したときの処理を実装します。
この記事があなたのお役に立ちましたら、よろしければサポートをお願いいたします! より良い記事をお届けできるよう、活動費に充てさせていただきます。