Created
August 7, 2020 11:30
-
-
Save kuredev/87d62034fbc14fe818a4cb7a53afb0d1 to your computer and use it in GitHub Desktop.
React Component(クラス)でStateを更新するサンプルコード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8" /> | |
<title>Fibonacci</title> | |
<script src="https://unpkg.com/react@16/umd/react.development.js"></script> | |
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> | |
<script src="https://unpkg.com/[email protected]/babel.js"></script> | |
</head> | |
<body> | |
<div id="root">wait...</div> | |
<script type="text/babel"> | |
// State をクリックで更新する | |
class Fibonacci extends React.Component { | |
constructor(props){ | |
super(props); | |
this.state = { | |
msg: "Fibonacci" | |
}; | |
this.calcNext = this.calcNext.bind(this); | |
} | |
// これでも動く | |
// calcNext(e){ | |
// this.setState({ | |
// msg: "hoge" | |
// }); | |
// } | |
//これでも動く | |
// updatedMsg = function(){ | |
// return { msg: "hoge" } | |
// } | |
// calcNext(e){ | |
// this.setState( | |
// this.updatedMsg | |
// ) | |
// } | |
// 動く (アロー関数Version) | |
// calcNext(e){ | |
// this.setState( | |
// () => { | |
// return { msg: "hoge" } | |
// } | |
// ) | |
// } | |
// 動く (アロー関数+引数にstateを取って前のやつを更新していく) | |
calcNext(e){ | |
this.setState( | |
(state) => { | |
return { msg: state.msg + "Fibonacci" } | |
} | |
) | |
} | |
render(){ | |
return <div> | |
<p>{this.state.msg}</p> | |
<button onClick={this.calcNext}>Calc</button> | |
</div>; | |
} | |
} | |
ReactDOM.render(<Fibonacci />, document.getElementById('root')); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
参考サイト
【JavaScript】アロー関数とか即時関数とかの書き方メモ https://gist.github.com/kuredev/86108045b1ca51f26ee5479ee4d739ab
React の setState() の引数が関数の場合とオブジェクトの場合の違いについて整理する - Qiita https://qiita.com/im36-123/items/857c96ff60024c0d8a1c