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の混乱する書き方のおさらい(stateの取り扱い、アロー関数の書き方)

Posted at

頭の中が混乱するから整理しておきたい。
紐解きまではしない。

stateの取り扱い

やりたいこと 書き方
stateの定義 this.state = {name: "きつねうどん"};
stateの更新 this.setState({name: "たぬきそば"});
stateの表示 {this.state.name}

なんでこんなにややこいのよ!

アロー関数の書き方

関数の宣言・使用方法の基礎

let addNumber = function(numA, numB) {
  return numA + numB;
}

console.log("3 足す 4 は " + addNumber(3, 4) + " です");
// 3 足す 4 は 7 です

JavaScriptにおいて関数の宣言は「addNumberという関数を作ります。引数は2つです」をaddNumber = function(a, b)と書く。

こういうのを「関数リテラル」というらしい。
リテラル = ベタ書き。マジックナンバー的なやつ。

アロー関数

アロー関数は「関数リテラル」を省略して書く方法。

let addNumber = (numA, numB) => {
  return numA + numB;
}
console.log("3 足す 4 は " + addNumber(3, 4) + " です");
// 3 足す 4 は 7 です

function=>になって、さらに書く場所が(){}の間になった。

renderのなかでメソッドをリテラル的に呼び出すやつ

handleClick(name) {
  this.setState({name:name});
}

render() {
  return (
    <div>
      <button onClick={() => {this.handleClick("hoge")} }>ほげ</button>
    </div>
  );
}

もうココがわからんよ!

onClick={() => {xxx}}

感覚的にはこうなんだけど違う。

onClick=this.handleClick("hoge")

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?