LoginSignup
40
29

More than 5 years have passed since last update.

React の Class Component と Functional Component の書き方

Last updated at Posted at 2018-07-05

Class Component and Stateless Functional Component

React Componentでの基本的なコンポーネントの書き方をまとめます

ReactDOM.render() {
  <Greeting name="Ronaldo" age=33 />,
  document.getElementById('root')
}

ReactDOM.render()で描画を行う
描画内容である、Greetingコンポーネントにnameagepropsとして渡します

Class Component

class Greeting extends React.Component {
  constructor(props) {
    super(props)
  }
  render() {
    return <h1>My name is {this.props.name}{this.props.age} years old.</h1>
  }
}

classにReact.ComponetというReactの基本的なコンポーネントを基底クラスとして継承します
render()メソッドを定義して、その戻り値でコンポーネントの表示内容を返します
propsをそのまま渡すだけなら、constructorを定義しなくとも問題ない

Stateless Functional Component

基本的なjsの書き方で実装すると、

function Greeting (props) {
  return <h1>My name is {this.props.name}{this.props.age} years old.</h1>
}

ES6のアロー関数を用いると、

const Greeting = (props) => (
  <h1>My name is {this.props.name}{this.props.age} years old.</h1>
)

のように、returnを省略できる

Stateless とは?

処理結果が変わるようなデータを内部に持たない状態を持たないコンポーネントのこと
コードライクではthis.state.がない
このようなコンポーネントは上記の2つの書き方の内、functional componentで実装することが推奨されている

40
29
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
40
29