korean IT student

React - Components and Props 본문

front-end/React

React - Components and Props

현창이 2022. 7. 27. 00:17

1. Component

  • 리액트로 만들어진 앱을 이루는 최소한의 단위
  • 화면을 구성하게 되면, 사용자가 볼 수 있는 여러 가지 컴포넌트로 구성되어 있습니다. 사용자에게 보여지는 UI 요소를 컴포넌트 단위로 구분하여 구현할 수 있습니다.
  • 컴포넌트 이름은 항상 대문자로 시작 (소문자로 시작하는 컴포넌트를 DOM 태그로 취급한다. )
  • "props"라고 하는 임의의 입력을 받은 후, 화면에 어떻게 표시되는지를 기술하는 React 엘리먼트를 반환

 

2. 함수 컴포넌트와 클래스 컴포넌트

  • 함수형 컴포넌트 : function 으로 정의하고 return 문에 jsx 코드를 반환합니다.
  • 화살표 함수로 정의 가능합니다.
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const Welcome = () => {
  return <h1>Hello, {props.name}</h1>;
}

 

  • 클래스형 컴포넌트 : class로 정의하고 render() 함수에서 jsx 코드를 반환
  • React.Compent를 상속받아서 만들어야 한다.
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

 

3. 컴포넌트 렌더링 활용

  • 아래와 같이 함수형 컴포넌트를 통해서 컴포넌트 렌더링, 합성, 추출
  • 리액트 18에서는 ReactDOM.render가 아니라, createRoot를 사용해야 한다
<div id="root"></div>

--- 컴포넌트 렌더링
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const root = ReactDOM.createRoot(document.getElementById('root'));
const element = <Welcome name="Sara" />;
root.render(element);



// 18 이전 버전
ReactDOM.render(
  element,
  document.getElementById('root')
);

-- 컴포넌트 합성

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);


-- 컴포넌트 추출

function formatDate(date) {
  return date.toLocaleDateString();
}

function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <img className="Avatar"
             src={props.author.avatarUrl}
             alt={props.author.name} />
        <div className="UserInfo-name">
          {props.author.name}
        </div>
      </div>
      <div className="Comment-text">
        {props.text}
      </div>
      <div className="Comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}

const comment = {
  date: new Date(),
  text: 'I hope you enjoy learning React!',
  author: {
    name: 'Hello world',
    avatarUrl: 'http://reactStudy.com'
  }
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <Comment
    date={comment.date}
    text={comment.text}
    author={comment.author} />
);

 

4. Props 

  • 프로퍼티, props(properties의 줄임말) 
  • 상위 컴포넌트가 하위 컴포넌트에 값을 전달할때 사용한다. (단방향)
  • 프로퍼티는 수정할 수 없다 (자식입장에선 읽기 전용인 데이터)
  • 문자열을 전달할 때는 "" , 문자열 외의 값을 전달할 때는 중괄호 {} 사용
import MyComponent from './MyComponent';

const App=()=>{
	return <MyComponent name="React"/>;
};

export default App;


--- props 기본값 설정 : defaultProps

const App=()=>{
	return <MyComponent/>;
};

const MyComponent = props => {
 return 이름은 {props.name};
};

MyComponent.defaultProps = {
	name: '홍길동'
};

-- 태그 사이의 내용을 보여주는 children

const App=()=>{
	return <MyComponent> 리엑트 </MyComponent>;
};


const MyComponent = props => {
 return 이름은 {props.children}; // 이름은 리엑트
};

-- ES6의 비구조화 할당 문법 사용하여 내부 값을 바로 추출

 const MyComponent = props => {
  const { children } = props;
  return 이름은 {children}; // 이름은 리엑트
};

 const MyComponent = ({ children }) => {
  return 이름은 {children}; // 이름은 리엑트
};

-- propTypes를 통한 props 검증

import PropTypes from 'prop-types';

const MyComponent = props => {
 return 이름은 {props.name};
};

MyComponent.defaultProps = {
	name: '홍길동'
};

MyComponent.propTypes = {
 name: PropTypes.string.isRequired
};

 

 

 

[참고]

https://goddaehee.tistory.com/299

Comments