React

React STEP 5 - 컴포넌트 스타일 2

IT의 큰손 2025. 2. 6. 16:10
728x90

⭐ 컴포넌트

  • 컴포넌트는 화면을 구성하는 구성 요소를 의미합니다.

1. 컴포넌트는 개별적인 속성을 정의할 수 있다.

  • ReactDOM에서 호출된 컴포넌트에서 전달한 속성은 {this.props.propsValue} 방식으로 전달 받습니다. 
    props는 속성인 Properties의 약어입니다.
  • this는 HelloReact 컴포넌트를 의미합니다. 이를 바인딩(binding)이라 합니다.
  • 전달받은 속성은 중괄호를 사용해서 렌더링하며, 이런 방식을 JSX의 표현식이라 합니다.
class StudyReact extends React.Component {
    render() {
        return (
            <h5>Study React {this.props.type} </h5>
        )
    }
}

root.render(
  <div>
      <StudyReact type="type1" />
      <StudyReact type="type2" />
      <StudyReact type="type3" />
      <StudyReact type="type4" />
      <StudyReact type="type5" />
  </div>
);
  • props는 여러 개를 추가할 수도 있습니다.
class StudyReact extends React.Component {
    render() {
        return (
            <h5>Study React {this.props.type} {this.props.user} </h5>
        )
    }
}

root.render(
  <div>
      <StudyReact type="type1" user="kim" />
      <StudyReact type="type2" />
      <StudyReact type="type3" />
      <StudyReact type="type4" />
      <StudyReact type="type5" />
  </div>
);
  • ReactDOM에서 추가된 HTML 구조는 {this.props.children} 방식으로 전달 받습니다.
class Button extends React.Component {
  render() {
    return (
      <button type={this.props.attr}>{this.props.children}</button>
    )
  }
}

root.render (
  <div>
    <Button attr="button">Button</Button>
    <Button attr="reset">Reset</Button>
    <Button attr="submit">Submit</Button>
  </div>
)
  • 추가적인 컴포넌트
class Korean extends React.Component {
  render() {
    return (
      <div className="korean">
        {this.props.children}
      </div>
    );
  }
}

root.render (
  <div>
    <Korean>가</Korean>
    <Korean>나</Korean>
    <Korean>다</Korean>
    <Korean>라</Korean>
  </div>
)

 

2. CSS 방식

  • Inline 방식을 선호합니다.
  • 기존에 쓰던 방식과 차이가 존재합니다.
display: inline-block; -> display: "inline-block",
margin: 10px; -> margin: 10,
margin: 0 auto; -> margin: "0px auto";
padding: 10px; -> padding: 10,
background-color: #fff; -> backgroundColor: "#fff"
  • 사용 예시
class Korean2 extends React.Component {
  render() {
    let koreanStyle = {
      display: "inline-block",
      margin: 10,
      padding: 10,
      backgroundColor: this.props.bgColor
    };

    return (
      <div style={koreanStyle}>
        {this.props.children}
      </div>
    )
  }
}

root.render(
  <div>
    <Korean2 bgColor="#eaeaea">가</Korean2>
    <Korean2 bgColor="#ccc">나</Korean2>
    <Korean2 bgColor="#999">다</Korean2>
  </div>
)

 

728x90