๋ฌธ์
<select id="country" onChange={this.selectCountry}>
</select>
์ด ์ฝ๋๋ class component์ renderํจ์์ ๋ฆฌํด๊ฐ ์์ ์๋ค.
๋๋ ์ด๋ ๊ฒ selectํ๊ทธ๋ฅผ ๋ฐ๊พธ๋ฉด selectCountry๋ฅผ ํธ์ถํ๊ณ ์ ํ๋๋ฐ, selectCountry ์์์
selectCountry(){
var selectedCountry = document.getElementById("country").value;
document.getElementById("countrytxt").innerHTML = "country: " + selectedCountry;
this.makeCityList(selectedCountry);
}
์ด๋ ๊ฒ class์ ๋ฉ์๋ makeCityList๋ฅผ ํธ์ถํ๋ ค๊ณ ํ๋ฉด ์๋์ ๊ฐ์ด "TypeError: Cannot read property 'ํจ์์ด๋ฆ' of undefined"๋ผ๋ ์ค๋ฅ๊ฐ ๊ณ์ ๋ํ๋ฌ๋ค.
๊ทธ๋์ ๊ณ์ ์ธํฐ๋ท์ ๊ฒ์ํ ๊ฒฐ๊ณผ bind()๋ผ๋ ํจ์๊ฐ ๋์๋ค.
ํด๊ฒฐ
์ฐธ๊ณ : https://reactjs.org/docs/handling-events.html
๋ด์ฉ์ ์ดํด๋ณด๋ฉด
์ด์๊ฐ์ด ๋ฆฌ์กํธ์์๋ ํจ์๋ฅผ ์์ ๊ฐ์ด ํธ์ถํ๋๋ฐ
๋ง์ฝ ์ ํจ์ ์์์ ํด๋น ํด๋์ค์ state๋ฅผ ๋ณ๊ฒฝํ๊ฑฐ๋, ํจ์๋ฅผ ํธ์ถํ๋ฉด ๋์ ๊ฐ์ ์ค๋ฅ๊ฐ ๋ฌ๋คใ .
๊ทธ๋์ ์ด๋ฒคํธ๋ฅผ ์ค์ ํ ํจ์์ ๋ํด์๋ class์ constructor์ bind๋ก
๋ด ํจ์๋ฅผ ์ด component์ ์ฐ๊ฒฐ์์ผ์ฃผ์ด์ผ ํ๋ค.
class MainHome extends React.Component{
constructor(){
super(); // this is required
this.state = {
isDataLoading: true,
country: [],
city: []
}
this.getCity();
// This binding is necessary to make `this` work in the callback
this.selectCountry = this.selectCountry.bind(this);
}
๋๋ ์ด๋ฅผ ์ ์ฉํ์๋๋ ์ค๋ฅ๊ฐ ์์ด์ก๊ณ ,
์ด๋ฒคํธ๋ก ํธ์ถํ ํจ์ ๋ด์์ ๋ด ํด๋์ค์ ํจ์๋ฅผ ์ฌ์ฉํ ์ ์๊ฒ ๋์๋คใ ใ ใ