๐Ÿ” Archive/ReactJS

[ReactJS error] event๋กœ ํ˜ธ์ถœ๋˜๋Š” ํ•จ์ˆ˜ ๋‚ด์˜ ํ•จ์ˆ˜๊ฐ€ ์•ˆ๋ถˆ๋Ÿฌ์ง€๋Š” ์ด์œ ?

YoungRock 2020. 3. 11. 23:14

๋ฌธ์ œ

<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

 

Handling Events – React

A JavaScript library for building user interfaces

reactjs.org


๋‚ด์šฉ์„ ์‚ดํŽด๋ณด๋ฉด

์ด์™€๊ฐ™์ด ๋ฆฌ์•กํŠธ์—์„œ๋Š” ํ•จ์ˆ˜๋ฅผ ์œ„์™€ ๊ฐ™์ด ํ˜ธ์ถœํ•˜๋Š”๋ฐ

๋งŒ์•ฝ ์ € ํ•จ์ˆ˜ ์•ˆ์—์„œ ํ•ด๋‹น ํด๋ž˜์Šค์˜ 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);
    }

๋‚˜๋„ ์ด๋ฅผ ์ ์šฉํ•˜์˜€๋”๋‹ˆ ์˜ค๋ฅ˜๊ฐ€ ์—†์–ด์กŒ๊ณ ,

์ด๋ฒคํŠธ๋กœ ํ˜ธ์ถœํ•œ ํ•จ์ˆ˜ ๋‚ด์—์„œ ๋‚ด ํด๋ž˜์Šค์˜ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋˜์—ˆ๋‹คใ… ใ… ใ