TIL/JavaScript
TIL 34: [React] ๋ฐ์ดํฐ ํ๋ฆ์ ์ดํด์ ๋น๋๊ธฐ ์์ฒญ ์ฒ๋ฆฌ
Deviloper๐
2021. 9. 7. 21:11
์ค๋์ ์ด์ ์ ์ด์ด์ StateAirlines๋ฅผ ๋ง์ ํ์ต๋๋ค. ์๋ก ๋ฐฐ์ด ๋ด์ฉ์ ์์ด ์ฒ์ ํ์์ ๋ ํค๋งธ๋ ์์ฃผ๋ก ์ ๋ฆฌํด๋ณด๋ ค๊ณ ํฉ๋๋ค!
Lifting State Up
๋ถ๋ชจ์ปดํฌ๋ํธ์ ์๋์ ๊ฐ์ด search ํจ์๋ฅผ onSearch๋ฅผ ํตํด ์ ๋ฌํด์ฃผ๋ฉด,
<Search onSearch={search} />
์์ ์ปดํฌ๋ํธ์์ ํจ์(Search)๊ฐ ์คํ๋๋ฉด onSearch์ ์ํด ๋ถ๋ชจ ์ปดํฌ๋ํธ๊ฐ ๋ณ๊ฒฝ๋ฉ๋๋ค.
import { useState } from 'react'
function Search({onSearch}) { //onSearch ๋ฃ์ด์ฃผ๊ธฐ, Main์์๋ <Search onSearch={search} />ํด์ฃผ๊ธฐ
const [textDestination, setTextDestination] = useState('')
const handleChange = (e) => {
setTextDestination(e.target.value.toUpperCase())
}
const handleKeyPress = (e) => {
if (e.type === 'keypress' && e.code === 'Enter') {
handleSearchClick()
}
}
const handleSearchClick = () => {
const departure = 'ICN' //๋งค๊ฐ๋ณ์ ์์ผ๋ departure destination ๋ฐ๋ก ์ค์ ํด์ฃผ๊ธฐ
const destination = textDestination === '' ? null : textDestination
onSearch({departure,destination})
}
return <fieldset>
<input id="input-destination" type="text" value={textDestination} onChange={handleChange} placeholder="CJU, BKK, PUS ์ค ํ๋๋ฅผ ์
๋ ฅํ์ธ์" onKeyPress={handleKeyPress} />
<button id="search-btn" onClick={handleSearchClick}>๊ฒ์</button>
</fieldset>
}
export default Search