はじめに
Reactの関数型コンポーネントについて備忘録です。
✅ゴール
・Reactの理解を深める
✅環境
Windows
✅参考教材
📚React.js&Next.js超入門
Reactの関数型コンポーネントについて
React.js&Next.js超入門で作るカウンターアプリのコンポーネントを関数型に書き直してみました。
Appコンポーネントでの比較
クラス型
class App extends Component { constructor(props){ super(props); } render() { return ( <div> <h1>Redux</h1> <Message /> <Button /> </div> ); } }
関数型
function App() { return ( <div> <h1>Redux</h1> <Message /> <Button /> </div> ); }
🙄propsとrenderメソッドの記載がない。超スッキリしていて読みやすい。
Messageコンポーネントでの比較
クラス型
class Message extends Component { render(){ return ( <p> {this.props.message}: {this.props.counter} </p> ); } }
関数型
function Message(props) { return ( <p> {props.message}: {props.counter} </p> ); }
🙄コンポーネント名の引数にpropsを記載。thisを付ける必要がない。
Buttonコンポーネントでの比較
クラス型
class Button extends Component { constructor(props){ super(props); this.doAction = this.doAction.bind(this); } doAction(e){ if (e.shiftKey){ this.props.dispatch({ type:'DECREMENT' }); } else { this.props.dispatch({ type:'INCREMENT' }); } } render(){ return ( <button onClick={this.doAction}> click </button> ); } }
関数型
function Button(props) { function doAction(e){ if (e.shiftKey){ props.dispatch({ type:'DECREMENT' }); } else { props.dispatch({ type:'INCREMENT' }); } } return ( <button onClick={doAction}> click </button> ); }
🙄こちらもpropsを引数に。メソッドは関数として記載。
簡単なスタイル適用
function App() { const style = { color: "blue" } return ( <div> <h1 style={{color: "blue"}}>Redux</h1> <h1 style={style}>Redux</h1> <Message /> <Button /> </div> ); }

🙄書き方によって{}の数が変わる点が注意。
アロー関数をふんだんに使ってみる
※6/3追記
🙄教材によって書き方が様々なので、理解を深めるためにためしにアロー関数で書いてみました。
コネクト時にコンポーネントの変数を使うのでconstは使わずに、letで代入できるようにするのがポイントかなと思いました。
おわりに
function型の方が記述が楽な印象。
素のJSに近い感覚で書けて好みです。教材であまり扱わないのが残念なところ。
そろそろHooksを本格的に学習したい。
コメントを残す