2
0

More than 1 year has passed since last update.

Propsを使って画面表示を使い回す(React)

Last updated at Posted at 2022-07-09

Reactの基礎を書籍を読みながら勉強しています

ネット上の記事だとすでに非推奨となっている機能を使っているものが多いので書籍に沿って公式の資料を確認しながら進めています。

今回はPropsについて試してみますが、一言で表現すると引数を使って表示を切り替えることだと理解しました。

内容

・ユーザーによってボタンの表示を変える機能を作る
・ボタンの表示は共通化してProps経由で表示を切り替える機能にする

構成

index.tsx
button.tsx
proptest.tsx

画面の大枠

index.tsx
import { ButtonTest } from './button';
export default function Index() {
  return (
    <Container maxWidth="sm">
      <Box sx={{ margin: 3 }}>
        <ButtonTest />
      </Box>
    </Container>
  );
}

画面の表示とボタンの呼び出し元

button.tsx
import { Propstest } from "./propstest";

export const ButtonTest = () => {
  return (
    <>
      <h1>こんにちわ!</h1>
      <Propstest name='check' value='props test 2022/07/09' />
    </>
  )
}

ボタンの表示を引数を元に切り替える

propstest.tsx
export const Propstest = (props) => {
  const contStyle = {
    name: props.name
  }
  const onClickButton = () => {
    alert(props.value);
  }
  return <input type='button' value={contStyle.name} onClick={onClickButton} />
}

画面
image.png

実際に使ってみるとシンプルな仕組みですが、説明の文章を読むと動的に注入だとか無理矢理日本語に割り当てられているので、フロントエンドに触れて来ず理解力がすごく低い自分には難しい概念でした・・・。

他のフレームワークとの長所短所の比較だったり、Reactの仕組み上の疑問が色々ありましたが書籍をパラパラ流し読みすることで回答が得られて2022年7月時点ではすごく良い書籍でした。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0