ํฐ์คํ ๋ฆฌ ๋ทฐ
๋ฌธ์
Route๋ฅผ ์ฌ์ฉํ์ฌ ๋ก๊ทธ์ธ ํ์ด์ง์์ ๋ฉ์ธ ํ์ด์ง๋ฅผ ์ด๋ํ๋ ๊ตฌํ ๊ณผ์ ์์, ๋ค์๊ณผ ๊ฐ์ด withRouter๋ฅผ ์ฌ์ฉํ์ง ์๊ณ ๋ฉ์๋ ํจ์ ๊ฐ์ฒด๋ฅผ props๋ก ๋๊ฒจ ์ฃผ๋ ๋ฐฉ์์ผ๋ก ์ ๊ทผํ์๋ค.
goMain() ๋ฉ์๋์์๋ ์ธ์ ๊ฐ์ผ๋ก ๋ฐ์ ๊ฒฝ๋ก๋ก ์ด๋ํ ์ ์๋๋ก history ๊ฐ์ฒด props๋ฅผ ์ฌ์ฉํ์๋ค.
import React, {Component} from 'react';
import Login from '../Login/Login';
import {withRouter} from 'react-router-dom';
class LoginPage extends Component {
goMain(path) {
this.props.history.push(path);
}
render() {
return (
<>
<Login goMain={this.goMain}/>
</>
)
}
}
export default withRouter(LoginPage);
๋ก๊ทธ์ธ ํ๋ฉด์์ ์ผ์ ์กฐ๊ฑด์ ๋ง์กฑํ ๊ฒฝ์ฐ์ ์์ ์ปดํฌ๋ํธ์์๋ props๋ก ์ ๋ฌ ๋ฐ์ ๋ฉ์๋์ธ goMain()์ path ๊ฐ์ ์ ๋ฌํ๋๋ก ํ๋ ๊ฒ์ด ์๋ํ ๋ฐ ์์ง๋ง, ๋ค์๊ณผ ๊ฐ์ ์๋ฌ๊ฐ ๋ฐ์ํ์๋ค.
goMain()์์๋ this.props๋ฅผ ํตํด history ๊ฐ์ฒด์ ์ ๊ทผํ๊ณ ์๋๋ฐ, goMain()์ด ํธ์ถ๋ ์์น๋ ํด๋น ์ปดํฌ๋ํธ๊ฐ ์๋, goMain์ props๋ก ์ ๋ฌ ๋ฐ์ ์์ ์ปดํฌ๋ํธ์ด๊ธฐ ๋๋ฌธ์ this ๋ฐ์ธ๋ฉ ๋ฌธ์ ๊ฐ ๋ฐ์ํ์ฌ ํด๋น ๊ฐ์ฒด์ ์ ๋๋ก ์ ๊ทผํ์ง ๋ชปํ ๋ฌธ์ ์ธ ๊ฒ์ ํ์ธํ ์ ์์๋ค.
ํด๊ฒฐ
๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด goMain() ๋ฉ์๋ ๋ด์ this๋ฅผ ํ์คํ๊ฒ ๋ถ๋ชจ ์ปดํฌ๋ํธ์ ๊ท์์ํฌ ํ์๊ฐ ์์๋ค.
์ด๋ฅผ ์ํด Funtion.prototpye.bind() ๋ฉ์๋๋ฅผ ์ฌ์ฉํ๊ธฐ๋ก ํ์๋ค.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
Function.prototype.bind() - JavaScript | MDN
bind() ๋ฉ์๋๊ฐ ํธ์ถ๋๋ฉด ์๋ก์ด ํจ์๋ฅผ ์์ฑํฉ๋๋ค. ๋ฐ๊ฒ๋๋ ์ฒซ ์ธ์์ value๋ก๋ this ํค์๋๋ฅผ ์ค์ ํ๊ณ , ์ด์ด์ง๋ ์ธ์๋ค์ ๋ฐ์ธ๋๋ ํจ์์ ์ธ์์ ์ ๊ณต๋ฉ๋๋ค.
developer.mozilla.org
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
์์ฑ์ ํจ์์ธ constructor() ๋ด์์ goMain() ๋ฉ์๋๋ฅผ ํด๋น ์ปดํฌ๋ํธ this์ ๋ฐ์ธ๋ฉ๋๋๋ก ์ด๊ธฐํํด์ฃผ์๊ณ , ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์๋ค.
ํด๋น ๋ฐฉ์ ์ธ์๋ ๊ตฌ๊ธ๋งํด๋ณด๋, ์ด๋ฒคํธ props๋ฅผ ์ ๋ฌํ๋ ๊ณผ์ ์์๋ ํด๋น ํจ์๋ฅผ ํ์ดํ ํจ์๋ก ๊ฐ์ธ์ฃผ์ด ๋ณด๋ด์ฃผ๋ฉด ์์ ์ ์ผ๋ก this ๋ฐ์ธ๋ฉ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์์ ํ์ธํ์๋ค.
import React, {Component} from 'react';
import Login from '../Login/Login';
import {withRouter} from 'react-router-dom';
class LoginPage extends Component {
constructor(props) {
super(props);
this.goMain = this.goMain.bind(this);
}
goMain(path) {
this.props.history.push(path);
}
render() {
return (
<>
<Login goMain={this.goMain}/>
</>
)
}
}
export default withRouter(LoginPage);
๊ด๋ จ ํฌ์คํ
https://choi95.tistory.com/107
์ด๋ฒคํธ ํธ๋ค๋ฌ this ๋ฐ์ธ๋ฉ ๋ฌธ์
๋ฌธ์ li.addEventListener('click', () => { const obj = { image: this.dataset.image, ...JSON.parse(this.dataset.user) } modal.classList.add('active'); thumbnail.src = obj.image; profileImg.src = obj.m..
choi95.tistory.com
'React' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Type ๊ฐ์ ๋ฐ๋ผ ์กฐ๊ฑด๋ถ ๋๋๋ง_getDerivedStateFromProps (0) | 2021.11.07 |
---|---|
Carousel Slide ๊ธฐ๋ฅ Component๋ก ๋ถ๋ฆฝ (0) | 2021.11.07 |
๋ช ๋ นํ ํ๋ก๊ทธ๋๋ฐ๊ณผ ์ ์ธํ ํ๋ก๊ทธ๋๋ฐ(how / what) (0) | 2021.10.28 |
๊ด์ฌ์ฌ์ ๋ถ๋ฆฌ_JSX ์์์ Inline-style์ ๋ํด (0) | 2021.10.28 |
๋ฆฌ์กํธ ํ๋ก์ ํธ์ ์น ํฐํธ ์ ์ฉํ ๋ GlobalStyles์ ๋ฌธ์ ์ (0) | 2021.10.24 |