onClick
좋아요 기능을 구현해봅시다.
좋아요 이모티콘을 만들고, 이모티콘을 누르면 숫자가 1씩 증가하는 기능이 목표입니다.
function App(){
let [따봉] = useState(0);
return (
<h4> { 글제목[0] } <span>👍</span> { 따봉 }</h4>
)
}
우선 클릭했을 때, 이벤트를 주는 방법은 js에서는 이벤트리스너를 사용했지만, 리액트에서는 onClick을 사용합니다.
<div onClick={실행할 함수}>
onClick은 위와같은 형식으로 사용하면 되고, Click을 대문자로 쓰며, {} 중괄호 안에 함수를 넣어야 동작합니다.
state 변경
function App(){
let [ 따봉 ] = useState(0);
return (
<h4> { 글제목[0] } <span onClick={ ()=>{ 따봉 = 따봉 + 1 } } >👍</span> { 따봉 }</h4>
)
}
클릭했을 때 따봉을 변경하는 함수를 만들고, 이제는 state를 변경해야 합니다.
여기서 중요한 점이, state를 변경할 때는 state 변경 함수를 써야 하는 것입니다.
let [ 따봉, 따봉변경 ] = useState(0);
위의 코드를 보면 useState를 만들 때 우리는 2개까지 작명을 할 수 있었습니다.
2번째 작명한 '따봉변경'이 바로 state의 변경을 도와주는 함수입니다.
함수 사용법은 따봉변경(새로운 state) 방식으로, 괄호( ) 안에 넣은 것으로 새로운 state를 변경시켜줍니다.
그리고 이렇게 따봉변경 함수를 써서, 기능을 구현하면 아래와 같은 코드를 작성할 수 있습니다.
function App(){
let [ 따봉, 따봉변경 ] = useState(0);
return (
<h4> { 글제목[0] } <span onClick={ ()=>{ 따봉변경(따봉 + 1) } } >👍</span> { 따봉 }</h4>
)
}
array 와 object state 변경하기
우선, 버튼을 하나 만들어보겠습니다.
그리고 이 버튼을 누르면 글이 가나다 순으로 정렬되는 기능을 구현해봅시다.
function App(){
let [글제목, 글제목변경] = useState( ['남자코트 추천', '강남 우동맛집', '파이썬 독학'] );
return (
<button onClick={ ()=>{
let copy = [...글제목];
copy.sort();
글제목변경(copy)
} }> 정렬버튼 </button>
)
}
위의 코드를 실행하면, 우리가 원하는 기능이 구현이 됩니다.
코드에서 우리가 알아야 할 점이 총 2개가 있습니다.
첫 번째, array, objcet 자료를 다룰 때는 원본 데이터를 직접 건드리는 것보다는 기존값을 보존하는 것이 좋은 관습니다.
그렇기 때문에 let copy 와 같이 기존 데이터가 들어간 새로운 변수를 만들어서 코드를 만든 것입니다.
두 번째, state 변경함수의 동작원리입니다.
array/object 와 같은 refefenct data type은 메모리에 저장된 객체의 위치를 참조합니다.
우리는 글제목 state의 copy 를 만들고 싶습니다.
let copy = [글제목]
그런데, 위와 같은 식으로 만들면 메모리에 저장된 같은 객체의 위치를 참조하기 때문에 전혀 새로운 변수가 만들어지지 않습니다.
그래서 우리는 spread operator 라는 문법을 활용해 새로운 배열을 만들어줍니다.
let copy = [...글제목]
참고)
2023.06.09 - [JavaScript] - JavaScript(Reference Data Type, constructor 함수)
2023.06.01 - [JavaScript] - JavaScript(Spread Operator)
마지막으로 sort 함수를 사용해 정렬기능을 구현하면 가나다 순으로 글 순서를 바꿀 수가 있습니다.
'React' 카테고리의 다른 글
React 블로그(동적 UI 만들기) (0) | 2023.07.03 |
---|---|
React 블로그(component) (0) | 2023.07.03 |
React 블로그(state) (0) | 2023.07.03 |
React 블로그(className, 데이터바인딩, style 넣기) (0) | 2023.07.03 |
React(시작하기) (0) | 2023.06.29 |