javascript

function과 function()의 차이, onclikc=function과 onclick=function()의 차이

우주유령 2021. 8. 19. 16:37
728x90
반응형

https://stackoverflow.com/questions/42178136/when-to-call-function-vs-function-in-react-onclick

 

When to call function vs function() in react onClick?

I'm having questions about when to call a function inside a react component. Sometimes my code breaks when I don't add the brackets to a function call, but not always. Is there some sort of rule i'm

stackoverflow.com

 

()가 없으면 함수를 참조하는 것,

()가 붙으면 참조한 함수를 호출하는 것. 지금 당장 호출해야 할 때 사용한다.

const printHello = () => {
	return "hello!";
}

console.log(printHello);
//() => {
//	return "hello!";
//}

console.log(printHello());
// "hello!"

 

onclick이벤트에서는 click할 때 printHello()해야한다.

따라서 onclick이벤트에서는 onclick="printHello"라고 작성해야 한다.

 

onclick="printHello()"라고 하면 페이지가 렌더링 될 때 "즉시" 실행되어버린다.

 

 

728x90
반응형