1
2

Reactで覚えとくべきポイント

Posted at

コンポーネントの定義

コンポーネントはjavaScriptの関数として定義する

function Hello(){
  return <h1>hello</h1>;
  // コンポーネントはJSXを返す
}

コンポーネントの実行

<Hello />

アロー関数でも定義できる

const Hello = () => {
  return <h1>hello</h1>;
}
// const Hello = () => <h1>hello</h1>; も可

複数行になるときは丸括弧で囲む

const Hello = () => {
  return (
    <div>
      <h1>hello</h1>
    </div>
  );
}
const Hello = () => (
  <div>
    <h1>hello</h1>
  </div>
);

JSX内のJSの書き方

{ }を使用する

function Hello(){
  const name = "taro"
  return <h1>hello {name}</h1>;
}
// {}の中にJavaScirptのコードを埋め込むことができる ※式のみ(文はNG)

配列を渡した場合は自動的に中身が展開される

function Hello(){
  const names = ["taro", "jiro"]
  return <h1>hello {names}</h1>;
}
// => hello tarajiro

HTMLもJavaScriptのオブジェクトとみなせる

function Hello(){
  const name = <h1>taro</h1>;
  return name
}

propsで効率よくオブジェクトを渡す(スプレット演算子を使用する)

function Example(){
  const taro = {
    age: 10,
    height: 150
  };

  return (
    <>
      <Child {...taro}/>
    </>
  )
}

props.cheildrenの使い方

const Example = () => {
  return (
    <div>
      <Container name="人名">
        {"taro"}
      </Container>
    </div>
  );
};

コンポーネントの開始タグと終了タグで囲んだ中身がchildrenに入る

const Container = (props) => {
  console.log(props);
  // => {name: '人名', children: 'taro'}
  return (
    <div className="container">
      <p></p>
    </div>
  );
};

そのため、分割代入で使用できる

const Container = ({ name, children }) => {
  return (
    <div className="container">
      <p>{name}:{children}</p>
    </div>
  );
};

配列にすることもできる

const Example = () => {
  return (
    <div>
      <Container name="人名" children={["taro"]} />
    </div>
  );
};
1
2
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
2