vue를 사용했을 때에 조건에 따라 다른 내용을 화면에 출력하고자했을 땐 state 의 값에 따라 삼항연산자나 다른 조건식을 이용해서 하였었는데, 이번에 react에서도 state 상태값을 이용해 동일하게 방법을 수행하였지만 화살표함수를 이용한 방식도 알게되었다.
function handleSelect(selectButton) {
console.log(selectButton);
}
<TabButton onSelect={() => handleSelect('components')}>
component
</TabButton>
{}안에 화살표함수를 이용하는 식의 방법인데, handleSelect함수에 매개변수를 전달하는 방식이다.
이벤트를 핸들링하는 함수의 실행을 다른 함수로 감싸면, 그 다른 함수가 이벤트 핸들링의 prop(속성)의 값으로 전달된다. 그러므로 메인 함수 (handleSelect)는 너무 빨리 실행되지 않는다. 대신, 이벤트가 발생할 때만 실행된다!!
그리고 중간에 handleSelect()와 handleSelect 의 차이를 적어보자면,
{handleSelect()}
는 이벤트가 발생할 때가 아니라 이 prop이 추가된 요소가 처음으로 평가/렌더링될 때 handleClick() 함수를 실제로 실행한다. 따라서 함수가 너무 일찍 실행되고 그 함수 실행의 결과가 onClick prop의 값으로 설정된다(따라서 실제 이벤트가 발생할 때는 아무 일도 하지 않는다).
{handleSelect}
라고 작성해야 이벤트가 발생했을 때 리액트는 handleClick()을 호출한다.
다음으로 삼항연산자를 이용해서 상태값에 따라 화면에 출력하는 내용을 상이하게 해보겠다.
react에서는 useState hook을 이용할 수 있다.
const [selectedTopic, setSelectedTopic] = useState();
보통 초기값은 null이나 빈값으로 설정한다.
function App() {
const [selectedTopic, setSelectedTopic] = useState(); //내부함수에 중첩되면안되며, 컴포넌트 함수의 최상위에서 호출해야한다.
function handleSelect(selectButton) {
setSelectedTopic(selectButton);
}
return (
<div>
<main>
<section id="examples">
<menu>
<TabButton onSelect={() => handleSelect('components')}>
component
</TabButton>
<TabButton onSelect={() => handleSelect('jsx')}>JSX</TabButton>
<TabButton onSelect={() => handleSelect('props')}>Props</TabButton>
<TabButton onSelect={() => handleSelect('state')}>State</TabButton>
</menu>
{!selectedTopic ? (
<p>주제를 선택해주세요.</p>
) : (
<div id="tab-content">
<h3>{EXAMPLES[selectedTopic].title}</h3>
<p>{EXAMPLES[selectedTopic].description}</p>
<pre>
<code>{EXAMPLES[selectedTopic].code}</code>
</pre>
</div>
)}
</section>
</main>
</div>
);
}
여기에서 &&을 이용해서 조건문을 작성할 수도 있다.
{!selectedTopic && <p>주제를 선택해주세요.</p>}
{selectedTopic && (
<div id="tab-content">
<h3>{EXAMPLES[selectedTopic].title}</h3>
<p>{EXAMPLES[selectedTopic].description}</p>
<pre>
<code>{EXAMPLES[selectedTopic].code}</code>
</pre>
</div>
)}
3번째 방법으로는 jsx코드가 반환되기전에, 변수를 설정하는 방법이 있다.
let tabContent = <p>주제를 선택해주세요.</p>;
if (selectedTopic) {
tabContent = (
<div id="tab-content">
<h3>{EXAMPLES[selectedTopic].title}</h3>
<p>{EXAMPLES[selectedTopic].description}</p>
<pre>
<code>{EXAMPLES[selectedTopic].code}</code>
</pre>
</div>
);
return 문에서 {tabContent}
내가 지금까지 가장 잘써왔던 방식으로 변수를 설정해서 하는 방법이다.