1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React ,TypeScriptのprops分割代入 基礎

Posted at

分割代入でpropsを受け渡しするコードをよく見かけますが、毎回混乱するので基礎の確認です。

分割代入の基礎

// オブジェクトの分割代入
const person = {
  name: "田中",
  age: 25
};

// 分割代入を使わない場合
const name = person.name;
const age = person.age;

// 分割代入を使う場合
const { name, age } = person;

Propsを分割代入

type Props = {
  imageUrl: string;
  userName: string;
  fullName: string;
}

// 分割代入なし
export const Test: FC<Props> = (props) => {
  return (
    <>
      <img src={props.imageUrl} />
      <p>{props.userName}</p>
      <p>{props.fullName}</p>
    </>
  );
}

// 分割代入あり
export const Test: FC<Props> = ({ imageUrl, userName, fullName }) => {
  return (
    <>
      <img src={imageUrl} />
      <p>{userName}</p>
      <p>{fullName}</p>
    </>
  );
}

または、途中で分割代入する。

type Props = {
  imageUrl: string;
  userName: string;
  fullName: string;
}

export const Test: FC<Props> = (props) => {
  const { imageUrl, userName, fullName } = props;
  
  return (
    <div>
      <img src={imageUrl} />
      <p>{userName}</p>
      <p>{fullName}</p>
    </div>
  );
}

分割代入すると、
・コードが短くなる(props.を何度も書かなくて良い)
・使用するプロパティが明確になる
・デフォルト値の設定が簡単

といったメリットがあります。

終わり

propsの説明はたいてい「propsとは、親コンポーネントから子コンポーネントへ値を渡すための仕組み」から始まるので混乱し、整理しておきたかったです。

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?