랜더링하는 방법
설명하기엔 조금 복잡하기때문에 일단 실습을 통해서 어떻게 랜더링이 되는지부터 알아보았다.
일단 화면에서 tag를 랜더링하려면 아래와 같이 tagname과 property(속성)을 작성해준다.
tagName은 무조건 대문자로 시작해야한다. (-> MyTag)
property인 name = "홍길동"은 함수에서 인자값으로 넘어가서 사용된다.
ReactDOM.render(<MyTag name="홍길동" />, document.getElementById('root'));
function MyTag(props) {
//console.log(props.name); 출력값 : "홍길동"
return <h1>Hello {props.name}</h1>;
};
콘솔창에 홍길동이 찍히는것을 확인할 수 있다.
JSX에 속성값을 {} 괄호안에 넣어서 출력할 수 있다.
함수와 클래스의 차이
클래스가 덩치가 커서 클래스안에 함수를 여러가지 가지고 다닐 수 있다.
나만의 태그 만들기
나만의 태그를 만들때는 아래 코드를 작성한다. 왠만하면 extends React.Component { render() { return ...} 는 외워두자.
1. 만든 함수를 사용할때는 맨 아래의 render함수에 tagName을 지정해주면 된다.
2. render함수의 속성값은 {this.props.name}으로 사용할 수 있다.
3. 나만의 태그를 만들때에는 좀 더 복잡한 태그를 만들때 사용한다.
class NewH3 extends React.Component {
render() {
return <h3>Hello, {props.name}!</h3>;
}
}
ReactDOM.render(<NewH3 name="gomigomi" />, document.getElementById('root'));
출력값 : Hello, gomigomi
▷ 간략한 순서
1.함수를 만든다.
function MyTag(props) {return <h1>{this.props.name}</h1>; }
2. element 변수에 만든 함수태그를 지정한다.
const element = <MyTag name = "gomimi" />;
3. element를 render한다.
ReactDOM.render(element, document.getElementById( 'root');
나만의 태그를 이용하여 버튼만들기
function RoundButton(props) {
const buttonStyle = {
"padding" : "10px",
"border-radius" : "20px"
}
return (
<button style={buttonStyle}>
/* 최종랜더링시 사용 */
{props.children}
</button>
);
}
ReactDOM.render(
<div>
<RoundButton>새로운 버튼</RoundButton>
<RoundButton>새로운 버튼</RoundButton>
<RoundButton>새로운 버튼</RoundButton>
<RoundButton>새로운 버튼</RoundButton>
<RoundButton>새로운 버튼</RoundButton>
<RoundButton>새로운 버튼</RoundButton>
<RoundButton>새로운 버튼</RoundButton>
</div>,
document.getElementById('root')
);
출력값 :
버튼 사이 간격 주기
간단하다. {' ' }만 주면 끝
<div>
<RoundButton>새로운 버튼</RoundButton>
{' '}
<RoundButton>새로운 버튼</RoundButton>
{' '}
<RoundButton>새로운 버튼</RoundButton>
{' '}
<RoundButton>새로운 버튼</RoundButton>
{' '}
<RoundButton>새로운 버튼</RoundButton>
{' '}
<RoundButton>새로운 버튼</RoundButton>
{' '}
<RoundButton>새로운 버튼</RoundButton>
</div>,
출력값 :
아직까지는 react가 어떤점이 좋은건지 잘 모르겠지만 계속해서 배워보자!
'공부 기록노트 > React' 카테고리의 다른 글
리액트 공부 day1 - 상속 (0) | 2024.09.20 |
---|---|
리액트 공부 day1 - JSX (0) | 2024.09.20 |