
function App() {
return (
<h1> 👋 Hi, there!</h1>
<h2> JSX 식에는 부모 요소가 하나 있어야 함.</h2>
);
}
export default App;
다음과 같이 <div> 태그로 감쌀 수 있지만 불필요한 태그가 추가된다는 단점이 있음!
<div>
<h1> 👋 Hi, there!</h1>
<h2> JSX 식에는 부모 요소가 하나 있어야 함.</h2>
</div>
Fragment 컴포넌트 를 이용하면 불필요한 태그 추가를 방지할 수 있다
import { Fragment } from "react";
<Fragment>
<h1> 👋 Hi, there!</h1>
<h2> JSX 식에는 부모 요소가 하나 있어야 함.</h2>
</Fragment>
보통은 축약식을 많이 사용한다
function App() {
return (
<>
<h1> 짜잔 </h1>
<h2> Fragment 태그의 축약식이에요 😺 </h2>
</>
);
}
export default App;
function App() {
const name = "CNS";
const age = 23;
return (
<>
<h1>{`안녕, ${name}`}</h1> ➡️ 문자열 데이터를 표현식으로 출력
<h1>안녕, {name}</h1> ➡️ 이름 변수값 출력
<h2>{age + 2}</h2>
</>
);
}
export default App;
<h2>{name === "CNS" ? "환영합니다" : "환영하지 않습니다"}</h2>
이름이 "CNS" 이면 환영합니다 출력, 그렇지 않으면 환영하지 않습니다 출력
<h2>{name === "CNS" ? "환영합니다." : null}</h2>
조건을 만족하면 내용을 출력하고 그렇지 않으면 null 반환함
<h2>{name === "CNS" && "환영합니다."}</h2>
(1>2) & (2>3) 은 조건식 앞과 뒤를 모두 확인하지만
&& 은 앞이 false면 뒤는 확인하지 않음
뒤의 연산이 생략(단락)되었다 ➡️ 단락 연산자
태그 내에서 style 속성을 이용해서 스타일을 지정하는 방법
- 스타일은 객체 형태로 지정
- 스타일 이름은 카멜 표현식을 사용
- 숫자 타입의 경우 단위를 생략하면 기본값 px (단위를 포함할 때는 문자열로 표현)
<h1 style={ { backgroundColor: "black", color: "yellow", fontSize: 28, padding: '16px' } }>{`안녕, ${name}`}</h1>
function App() {
const name = "CNS";
const age = 23;
const myStyle = { backgroundColor: "black", color: "yellow", fontSize: 28, padding: '16px' };
return (
<>
<h1 style={myStyle}>{`안녕, ${name}`}</h1>
function App() {
const name = "CNS";
const age = 23;
const myStyle = {
h1Style: { backgroundColor: "black", color: "yellow", fontSize: 28, padding: '16px' },
h2Style: { color: "red" }
};
return (
<>
<h1 style={myStyle.h1Style}>{`안녕, ${name}`}</h1>
<h2 style={myStyle.h2Style}>{name === "CNS" && "환영합니다."}</h2>
</>
변수에 값이 할당되지 않으면 undefined 리턴함.
이를 방지하기 위해 기본값 설정
function Name() {
let name;
return name || "아무개";
}
class는 자바스크립트의 예약어이기 때문에 className를 사용함
function App() {
return (
<div className="react">홍길동</div>
);
}
.react {
background-color: black;
color: yellow;
font-size: 40px;
padding: 10px;
}
최근 대부분의 코드가 함수형 컴포넌트이지만 오랜 기간동안 쓰여온 클래스형 컴포넌트의 구조도 알고 있어야 한다
import { Component } from "react";
class MyApp extends Component {
render() {
return (
<> </>
);
}
}
export default MyApp;
function MyApp() {
return (
<> </>
);
}
export default MyApp;
const MyApp = function() {
return (
<> </>
);
}
export default MyApp;
가장 익숙한 구조
const MyApp = () => {
return (
<> </>
);
}
export default MyApp;