LoginSignup
2

More than 3 years have passed since last update.

React本 覚え書き

Last updated at Posted at 2019-04-16

React.DOMは予め用意されているHTML要素の集合。
ReactDOMは、ReactDOM.render()のようなブラウザ上で描画するための手段が提供されている。

this.propsは読み取り専用だと思え。
this.stateは直接書き換えてはいけない。this.setState()を使え。

this.propsとはコンポーネントのユーザからコンポーネントの設定を行うための仕組み
this.stateは、内部のデータ構造
オブジェクト指向でいうとthis.propsはコンストラクタに渡す引数、this.stateはプライベート変数

JSXでの空白

<h1> {1} plus {2} is {3}

の場合の結果

<h1>
1 plus 2 is 3
</h1>
<h1>
    {1}
    plus
    {2}
    is
    {3}
</h1>

の場合の結果

<h1>
1plus2is3
</h1>

コメントは

{/* コメント */}

を推奨

class と for を属性の名前として使いたいときは、className と htmlFor としなければならない。

JSXは全てのタグに閉じタグが必要

参考図書:

Reactビギナーズガイド――コンポーネントベースのフロントエンド開発入門

空要素は必ず閉じる

<br> ではなく<br />

Functional Component と Class Component
Functional Component

//Functional Component
const Hello = (props) => {
 return <div>こんにちは、{props.name}さん </div>
}
//Class Component
class Hello extends React.Component{
 render(
  return <div>こんにちは{this.props.name}</div>
 )
}

Functional Component と Class Component
Class Component にはコンポーネントの状態を記憶するstateがある

Reactコンポーネント

const Hello = () => {
 return <div>こんにちは</div>
}
Reactコンポーネントはクラスに近い
<Hello />
Reactエレメントはインスタンスに相当するもの

Fragmentコンポーネント

エラーのコード
const Hello = () => {
 return (
  <div>こんにちは</div>
  <div>こんばんは</div>
 )
}

Reactでは単一の親からなる要素しか表現できない、なので

const Hello = () => {
 return (
 <div>
   <div>こんにちは</div>
   <div>こんばんは</div>
 </div>
 )
}

こうするか

const Hello = () => {
 return (
 <React.Fragment>
   <div>こんにちは</div>
   <div>こんばんは</div>
 </React.Fragment>
 )
}

こうする
を<>と書くこともできるが、多くのツールで対応されていない場合がある。

props.children

const Hello = (props) => {
 return (
  <div>{props.children}さん</div>
 )
}

const Greeting = (props) => {
 return(
  <div>
   <div>ご挨拶</div>
  {props.children}
  </div>
 )
}

ReactDOM.render(
 <Greeting>
 <Hello>鈴木</Hello>
 <Hello>田中</Hello>
 </Greeting >
 document.getElementById('root')
)
表示結果
ご挨拶
鈴木さん
田中さん

用語

トランスパイル 処理結果を変えずすべてのブラウザ上で実行できる形式へとソースコードを書き換える

参考図書
React入門 React・Reduxの導入からサーバサイドレンダリングによるUXの向上まで

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