-
-
Save yuheiy/09ec31858f2a5d2a829df596090c83f7 to your computer and use it in GitHub Desktop.
React Componentのライフサイクル。DOMをアップデートするケース
This file contains 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
/* | |
React Componentのライフサイクル | |
- setState - componentWillReceiveProps | |
- かならずimmutableなsetStateにする | |
- 複数回の更新時は間引かれるので、++のようなインクリメントな処理はしない | |
- DOMから情報取得 - componentWillUpdate | |
- DOMの位置を変更 - componentDidUpdate | |
をそれぞれ書く場所が決まってる | |
https://facebook.github.io/react/docs/component-specs.html | |
https://facebook.github.io/react/blog/2016/01/08/A-implies-B-does-not-imply-B-implies-A.html | |
http://javascript.tutorialhorizon.com/2014/09/13/execution-sequence-of-a-react-components-lifecycle-methods/ | |
http://blog.vjeux.com/2013/javascript/scroll-position-with-react.html | |
*/ | |
// setStateはcomponentWillReceivePropsで行う | |
componentWillReceiveProps(nextProps) { | |
const leftMargin = nextProps.leftMargin; | |
this.setState({leftMargin}); | |
} | |
// willでDOMの現在地を取得 | |
componentWillUpdate(nextProps, nextState) { | |
this.clientLeft = this._element.clientLeft; | |
} | |
// didでDOMを新しい位置へ移動 | |
componentDidUpdate(prevProps, prevState) { | |
// 必要なら this.clientLeftを使う | |
const leftMargin = this.clientLeft + this.state.leftMargin; | |
this._element.setAttribute('style', `position:relative; display:block; left:-${leftMargin}px;`); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment