Web Dev/React :: 리액트
[React] HTML과 JSX에서 다른점(Inline style부분)
HJPlumtree
2020. 7. 20. 22:59

HTML과 React의 구문은 조금씩 다르다.
헷깔리지 않도록 정리해보자
div에 class 주기
HTML에서 <div>에 클래스를 주려면 class를 사용한다.
JSX에서는 className을 사용한다.
HTML
<div class="color"></div>
React
class Colorextends React.Component {
render() {
return (
<div className="color">Big Red</div>
);
}
};
Inline style, HTML에서 style 속성을 사용할 때 다른점
1.
HTML은 kebab-case (예: font-size)
React는 camelCase를 사용한다 (예: fontSize)
2.
React에서 style 속성을 사용할 때
object처럼 사용한다.
3.
React에서 width, height, fontSize 같은 크기를 지정할 때
픽셀(px)이 기본값이라 생략가능.
필요하면 다른 걸로 대체하면 된다.(em, rem, % 등_
HTML
<div style="color: yellow; font-size: 16px">Mellow Yellow</div>
React
class Colorful extends React.Component {
render() {
return (
<div style={{color: "yellow", fontSize: "72px"}}>Mellow Yellow</div>
);
}
};
style{{ 블라 블라 블라 }}
이렇게 중괄호 2개 안해주면 에러가 뜬다.
그 이유를 찾아보자.
길어지는 Inline style을 위해 변수로 빼주자
위의 예처럼 짧은 style이면 괜찮지만 길어지면 보기 힘들 수 있다.
변수를 이용해 빼주자
오브젝트에 스타일을 저장하고 JSX에서 불러와주면 된다.
const styles = {
color: "purple",
fontSize: 40,
"border": "2px solid purple"
}
class Colorful extends React.Component {
render() {
return (
<div style={styles}>Style Me!</div>
);
}
};