본문 바로가기
react

[React] 기본정리

by dyyoo 2019. 11. 4.

React 공부 시작.

 

* 모든 React 컴포넌트는 render 메소드가 있다.

  -> 컴포넌트가 어떻게 생길지 정의해준다.

 

* JSX

  -> js코드에서 html형식을 그대로 작성할 수 있다. 

  -> xml같은 문법을 native javascript로 변환

  -> 괄호를 안해도 오류나진 않지만, 가독성을 위해 사용하는게 좋음

//0.기본 구조.

//--------------------------------------------------------------
class Codelab extends React.Component {
  render() {
    return ( <div>Codelab</div>);
}
)

class App extend React.Component {
 render () {
   return (
     <Codelab/>
   );
 }
}
ReactDOM.render(<App/>, document.getElementById('root'));
//--------------------------------------------------------------
//index.html

<div id="root"></div>

 

1. 컴포넌트에서 여러 Element를 렌더링할때 꼭 모든 jsx코드는 container element안에 포함해야한다.

 

2. jsx안에서 js를 표현하는 방법

//{}로 wrapping하면 된다.

render () {
  let text = "hihi";
  return (
    <div> {text} </div>
  );
}

 

3. jsx안에서 style을 설정 할때는 string형식을 사용하지 않고 key가 camelCase인 객체가 사용된다.

render () {
   let text = "hihi";
   let styleVal = {
     backgroundColor:'aqua'
   }
   return (
     <div style={styleVal}> {text} </div>
   );
}

 

4. jsx안에서 주석을 작성 할때는 { /* ...  */} 형식으로 작성

 

5. Props
  -> 컴포넌트 내부의 immutable data를 처리할때 사용.
  -> jsx 내부에 {this.props.propsName}
  -> 컴포넌트를 사용할 때 <> 괄호안에 propsName="value"작성
  -> this.props.children은 기본적으로 갖고있는 props로써, 여기에 있는 값이 들어간다.
  -> Hello 다음 Codelab의 name이 나오고. children에 Codelab태그 사이에있는게출력

class Codelab extends React.Component {
 render () {
   return (
     <div> 
       <h1> Hello {this.props.name} {this.props.tmp} </h1>
       <div>
         {this.props.children}
       </div>
     </div>
   );
 }
);

class App extend React.Component {
 render () {
   return (
     <Codelab name={this.props.name} tmp="tmp attr">{this.props.children}</Codelab>
   );
 }
};
ReactDOM.render(<App name="name print">출력 children</App>, document.getElementById('root'));

 

6. 기본 값 설정

class App extend React.Component {
 render () {
   return (
     <div> {this.props.value} </div>
   );
 }
};

App.defaultProps = {
  value:0
};

 

7. Type 검증

class App extend React.Component {
 render () {
   return (
     <div> 
       {this.props.value} 
       {this.props.secondValue} 
       {this.props.thirdValue} 
     </div>
   );
 }
};

App.propTypes = {
 value:React.PropTypes.string,
 secondValue: React.PropType.number,
 thirdValue:React.PropTypes.any.isRequired
}


참고: https://facebook.github.io/react/docs/reusable-components.html

 

 

8. State
 -> 컴포넌트에서 유동적인 데이터를 사용할때 
 -> jsx 내부에 {this.state.stateName}
 -> 초기값 설정이 필수, constructor에서 this.state={} 으로 설정
 -> 값을 수정할 때는 this.setState({}), 렌더링이 된 다음엔 this.state= 는 사용하지 말아야함 
    -> 바뀐부분만 업데이트하는 부분을 무시하는 것. 성능에 악영향

class Counter extends React.Component {
  constructor(props) {
    //컨스트럭트를 사용해 초기화 해준다. super(props)를 통해 상속받은 React.Component의 메소드를 실행하고.
    //this.state를 통해 할 작업을 실행
    super(props):
    this.state={
      value:0
    }
  }
  render() {
    return (
      <div>  
        <h2> {this.state.value} </h2>
        <button>Press Me </button>
      </div>
    );
  }
}


class App extends React.Component {
  render() {
    return (
      <Counter />
    );
  }
};

ReactDOM.render(
  <App></App>,
  document.getElementById("root")
);

 

9. Component mapping

class ContactInfo extends React.Component {
  render() {
    return (
      <div>
        {this.props.contact.name}
        {this.props.contact.phone}
      </div>
    );
  }
};

class Contact extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      contactData: [
        {name:'Abet', phone:'010-1234-0000'},
        {name:'Beta', phone:'010-1234-2222'},
        {name:'Charlie', phone:'010-1234-3333'},
        {name:'David', phone:'010-1234-4444'}
      ]
    }
  }
  render() {
    
    const mapToComponent = (data) => {
      return data.map((contact, i) => {
        return (<ContactInfo contact={contact} key={i}/>);  
      });
    };
    return (
      <div>{mapToComponent(this.state.contactData)}</div>
    );
  }
};

class App extends React.Component {
  render() {
    return (
      <Contact/>
    );
  }
};

ReactDOM.render(
  <App></App>,
  document.getElementById("root")
);

'react' 카테고리의 다른 글

node.js Express - react 서버 세팅  (0) 2019.10.11

댓글