본문 바로가기

프론트엔드/react

React (2) - React Event 동작 #2 (JSX)

JSX - JavaScript 확장 문법, React 활용 가능.

JSX & React를 사용하면 html 문법과 비슷하게 사용가능해서 유용!

단, JSX는 브라우저가 이해하지 못하기 때문에 babel을 불러와서 변환해줘야 한다.

 

* const h3 = React.createElement()를 jsx로 바꾸기

 
 
<!DOCTYPE html>
<html>

<body>
<div id="root"></div>
</body>

<script type="text/babel">
const root = document.querySelector("#root");

const Title = (
<h3 id="title" onMouseEnter={() => console.log("mouse enter")}>
hello, I'm span
</h3>
);

const Button = (
<button onClick={() => console.log("im clicked")}
style={{backgroundColor: "toamto"}}>
button
</button>
)
 
const container = React.createElement("div", null, [Title, Button]);

ReactDOM.render(container, root);
</script>

</html>
 
 
 

React

const h3 = React.createElement(
"h3",
{
id: "title",
onMouseEnter: () => console.log("mouse enter"),
}, 
"hello, I'm span"

);
JSX

const Title = (


<h3 id="title" onMouseEnter={() => console.log("mouse enter")}>
hello, I'm span
</h3>

);

 

html태그와 비슷해서 알아보기 편해서 JSX 사용!

 

* JSX는 브라우저가 이해하지 못해서 babel이라는 것을 통해 변환 후 인식이 가능하다.

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> 추가

본문 <script>   ----->    <script type="text/babel"> 변경

 

 

* const container = React.createElement()를 jsx로 바꾸기

<!DOCTYPE html>
<html>

<body>
<div id="root"></div>
</body>

<script type="text/babel">
const root = document.querySelector("#root");

function Title() {
return (
<h3 id="title" onMouseEnter={() => console.log("mouse enter")}>
hello, I'm span
</h3>
);
}

const Button = () => (
<button
style={{ backgroundColor: "tomato" }}
onClick={() => console.log("im clicked")}
>
click me!
</button>
);

const Container = () => (
<div>
<Title />
<Button />
</div>
);

ReactDOM.render(<Container />, root);
</script>

</html>
React

const container = 
React.createElement("div", null, [Title, Button]);
JSX

const Container = () => (
<div>
<Title />
<Button />
</div>
);

Title과 Button의 내용을 불러오기 위해서는 

1. const Title과 const Button 변수형태를 함수형태로 바꿔줘야 한다.

2. ReactDOM.render(<Container />, root);

  ㄴ Container를 불러오기 위해서 const Container역시 함수형태로 변경

 

 

* jsx 함수 형태로 변경하기

const Title = (

<h3 id="title" onMouseEnter={() => console.log("mouse enter")}>
hello, I'm span
</h3>

);
const Title = () => (
        <h3 id="title" onMouseEnter={() => console.log("mouse enter")}>
            hello, I'm span
        </h3>
    );
   function Title() {
        return (
       
<h3 id="title" onMouseEnter={() 
         => console.log("mouse enter")}>
            hello, I'm span
</h3>.   
);
    }

 const Title = () =>
function Title() {return()}

결과값이 같은 코드이다!

만든 컴포넌트의 첫 글자는 반드시 대문자! 소문자일 경우 html tag로 인식한다.

ex)   const Container = () => (
<div>

<title>  - html tag로 인식
<Title />  --- 만든 컴포넌트 Title로 인식
<Button />
</div>
);

반응형