KIC/React

[React] Props, State

octopengj 2020. 11. 4. 15:12

Props

 

- 컴포넌트에서 사용 할 데이터 중 변동되지 않는 데이터를 다룰 때 사용

-  parent 컴포넌트에서 child 컴포넌트로 데이터를 전할 때, props 가 사용

 

- 컴포넌트에서 immutable (변하지 않는)  데이터가 필요 할 땐,

  render() 메소드의 내부에 안에  { this.props.propsName } 형식으로 넣는다.


- 컴포넌트를 사용 할 때, < > 괄호 안에 propsName="value를 넣어 값을 설정


index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
   
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <hr>
    <div id="root2"></div>  //추가
   
  </body>
</html>

 

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
//App부모 컴포넌트만 새로 불러올 경로를 지정
import App from './components/App';
import App2 from './components/App2';

import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App headerTitle="전달연습1" />
  </React.StrictMode>,
  document.getElementById('root')
);
//새로 추가
//부모(<자식태그명 전달할 매개변수(=속성명)=전달할값>)
const rootElement2=document.getElementById('root2')
//<App2 />
/* before 
  ReactDOM.render(<App2 contentTitle="전달연습2" 
                       contentBody="부모로부터 자식에게 전달함"/>,rootElement2);
*/
//after
ReactDOM.render(<App2 />,rootElement2);
reportWebVitals();

 

Contents.js

import React, { Component } from 'react';
//추가
import propTypes from 'prop-types';

class Content extends Component {
    render() {
        return (
            <div>
                <h1>Content</h1>
                <h1>본문내용 추가 변경</h1>
                <hr />
                <h1>{this.props.title}</h1>
                <h2>{this.props.body}</h2>
            </div>
        );
    }
}
/*
 유효성검사규칙(validate)
 형식) 자식클래스명.propTypes={
     매개변수명:PropTypes.자료형(string, number, double,,,,)
     매개변수명:PropTypes.자료형.isRequired(반드시 필수로 입력을 받는표시)
 }
*/
Content.propTypes = {
    title:propTypes.string,
    body:propTypes.string.isRequired
}


export default Content;

 

Header.js

 

import React, { Component } from 'react';

class Header extends Component {
    render() {
        return (
            <div>
                <h1>Header</h1>
                <h1>Design 연습중</h1>
            </div>
        );
    }
}

export default Header;

 

App2.js

import React, { Component } from 'react';
// 하나의 파일에 반드시 하나의 클래스만 작성x -> 여러개 작성이 가능하다.
// 컴포넌트 갯수 3개 -> App2, Header, Content
// 불러올 자식컴포넌트 및 스타일시트파일을 import하면 메이페이지 작성
import Header from './Header'; // 자기 파일내부에 존재하지 않은 경우
import Content from './Content';
class App2 extends Component {
    //데이터를 저장
    constructor(props){
        super(props)// 자식->부모클래스의 값을 먼저 초기화 작업
        //초기 설정 -> json 표기법 형태로 값을 초기화
        this.state={
            value:Math.round(Math.random()*100) // 키명: 저장할 값
        }
    }
    //this.state.value=5 (x)=>this.setState()를 이용해서 저장하라
    //state 값을 변경시켜주는 함수작성
    //매개변수가 있는 경우
    updateValue(randomValue){
        //this.state.value=randomValue
        this.setState({value:randomValue})
    }
    //매개변수가 없는 경우
    test(){
        alert('매개변수가 없는 경우 부모함수 호출됨!')
    }
    render() {
        return (
            <div>
                <h1>데이터전달 출력예제</h1>
                <h1>{this.props.contentTitle}</h1>
                <h1>{this.props.contentBody}</h1>
               <Header /> 
               {/* <Content title="연습2" body="본문내용전달"/> */}
               <Content title={this.props.contentTitle}
                        body={this.props.contentBody} />
            </div>
        );
    }
}
/*
 형식) 자식입장에서 만약에 props값을 못받았다면
        자식클래스명.defaultProps={매개변수명:기본값,,}
 */
App2.defaultProps={
    contentTitle:'기본값 contentTitle',
    contentBody:'기본값 contentBody'
}


/*
// 1.Header
class Header extends Component {
    render() {
        return (
        <div>
            <h1>Header</h1>
            <h1>Design 연습중</h1>
        </div>
        );
    }
}

// 2.Content
class Content extends Component {
    render() {
        return (
        <div>
            <h1>Content</h1>
            <h1>본문내용 추가 변경</h1>
        </div>
        );
    }
}
*/

export default App2;