꾸준히 성장하는 개발자

React - jsx , state, props 본문

React

React - jsx , state, props

ahleum 2022. 5. 6. 00:24

JSX 문법으로 작성된 코드는 순수한 JavaScript 로 컴파일 하여 사용한다.

컴파일을 누가해주냐 ?   babel 이다

babel 사이트에서 CDN받아서 먼저 사용해보기

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

 

<script type="text/babel">

 

 


JSX 문법

  • 최상위 요소가 하나여야 합니다.
  • 최상위 요소 리턴하는 경우, ( ) 로 감싸야 합니다.
  • 자식들을 바로 랜더링하고 싶으면, <>자식들</> 를 사용합니다. => Fragment
  • 자바스크립트 표현식을 사용하려면, {표현식} 를 이용합니다.
  • if 문은 사용할 수 없습니다.
    • 삼항 연산자 혹은 && (논리연산자)를 사용합니다.
  • style 을 이용해 인라인 스타일링이 가능합니다.
  • class 대신 className 을 사용해 class 를 적용할 수 있습니다.
  • 자식요소가 있으면, 꼭 닫아야 하고, 자식요소가 없으면 열면서 닫아야 합니다.
    • <p>어쩌구</p>
    • <br />

 

 

 ReactDOM.render(
      React.createElement(
        'div',
        null,
        React.createElement('div', null,
          React.createElement('h1', null, "주제"),
          React.createElement(
            'ul', 
            null,
            React.createElement('li', null, "React"),
            React.createElement('li', null, "vue")
          )
        )
      ),
      document.querySelector('#root')
    );

    ↓  jsx 문법으로 쓰게 되면 아래와 같이 사용할수 있다

<script type="text/babel">
ReactDOM.render(
    <div>
      <div>
        <h1>주제</h1>
        <ul>
          <li>react</li>
          <li>vue</li>
        </ul>
      </div>
    </div>,
      document.querySelector('#root')
    );
</script>

 


 

Props 와 State

Props 는 컴포넌트 외부에서 컴포넌트에게 주는 데이터입니다.

State 는 컴포넌트 내부에서 변경할 수 있는 데이터입니다.

둘 다 변경이 발생하면, 랜더가 다시 일어날 수 있습니다.

 

Render 함수

Props 와 State 를 바탕으로 컴포넌트를 그립니다.

그리고 Props 와 State 가 변경되면, 컴포넌트를 다시 그립니다.

컴포넌트를 그리는 방법을 기술하는 함수가 랜더 함수 입니다.

class 방식

 

function방식

class 방식

function 컴포넌트(props) { retutn JSX; }

class 컴포넌트 extends React.Component

<Component p="프롭스" />   -   props 설정
props.p 로 접근  -  props 사용
<Component p="프롭스" />  -  props 설정
this.props.p 로 접근  -  props 사용

 

 

// function 방식
// function Component(props){
//   return (
//     <div>
//       <h1>{props.message} 이것은 함수로 만든 컴포넌트 입니다.</h1>
//     </div>
//   );
// }


//class 방식
class Component extends React.Component{
  render(){
    return(
      <div>
        <h1>{this.props.message} 이것은 함수로 만든 컴포넌트 입니다.</h1>  
     </div>
    );
  }
  static defaultProps={
    message:"기본값2"
  }
}
// Component.defaultProps={
//   message:"기본값"
// }

ReactDOM.render(
  <Component message="안녕하세요!"/>, 
  document.querySelector('#root')
);

props를 이용하여 앞부분에 다른 문장을 추가 할 수 있다

 

defaultProps

만약 message가 빠져 있는 경우 기본값으로 주는 방법은 위 2가지

message가 있으면  message값이 들어가고 없으면 기본값이 들어간다

 

1.
static
 defaultProps={
    message:"기본값2"
  }   
를 render(){ }뒤에 붙여주기


클래스에서만 사용 가능
2.
Component
.defaultProps={
  message:"기본값"
}
class Component extends React.Component{}뒤에 붙여주기


 클래스, 함수 둘다 사용 가능

 

 

state는 객체형태로 사용 가능

 

state = {}; constructor    -   state 초기값 설정

this.state.s 로 접근   -   state 사용

class Component extends React.Component{
  // state={
  //   count:0
  // };
  constructor(props){
    super(props);

    //state 초기화
    this.state={count:0};
  }

  render(){
    return(
      <div>
        <h1>{this.props.message} 이것은 함수로 만든 컴포넌트 입니다.</h1>  
        <p>{this.state.count}</p>
        </div>
    );
  }

  componentDidMount(){
    setTimeout(()=>{
    // 
    // this.state.count=this.state.count+1;  -> 구현되지 않음
    
    // state를 변경해주는 함수 실행되면서 렌더링이 다시 구현된다.
    
    // 첫번째 방법  : 객체를 통채로 만들어서 넣는 방식
    // this.setState({
    //   count: this.state.count+1,
    // })
    // },1000);
    
    // 두번째 방법 : 앞의 값을 이용하여 할 수 있는 방식
    this.setState((previousState)=>{
      const newState ={count:previousState.count+1};
      return newState;
    })
    },1000);
  }
  static defaultProps={
    message:"기본값2"
  }
}

 

state 값을 넣는 방법 2가지

state={
    count:0
  };
constructor(props){
    super(props);

    //state 초기화
    this.state={count:0};
  }

state의 값을 변경하게 하는 방법

componentDidMount(){
    setTimeout(()=>{
    //
    // this.state.count=this.state.count+1;  -> 구현되지 않음
   
    // state를 변경해주는 함수 실행되면서 렌더링이 다시 구현된다.
    // 첫번째 방법  : 객체를 통채로 만들어서 넣는 방식
    this.setState({
      count: this.state.count+1,
    })
    },1000);
  }
  static defaultProps={
    message:"기본값2"
  }
}
componentDidMount(){
    setTimeout(()=>{
    
    // 두번째 방법 : 앞의 값을 이용하여 할 수 있는 방식
    this.setState((previousState)=>{
      const newState ={count:previousState.count+1};
      return newState;
    })
    },1000);
  }
  static defaultProps={
    message:"기본값2"
  }
}

 

 

state = {}; constructor

state 초기값 설정

class Component extends React.Component {
  state = {
    s: '스테이트'
  };
  render() {
    return (
      <div>{this.state.s}</div>
    );
  }
}

this.state.s 로 접근

state 사용

class Component extends React.Component {
  constructor(props) {
    super(props);
    this.state = {s: '스테이트'};
  }
  render() {
    return (
      <div>{this.state.s}</div>
    );
  }
}

 

this.setState({s: '새 스테이트'});

state 값 업데이트

class Component extends React.Component {
  state = {
    s: '스테이트'
  };
  render() {
    return (
      <div onClick={() => {
        this.setState({s: '새 스테이트'});
      }}>{this.state.s}</div>
    );
  }
}