티스토리 뷰

React

[React]JSX와 Prop종류들

Xion 2020. 11. 8. 15:39

1.JSX

-모든 JSX코드는 컨테이너 Element안에 포함시켜줘야한다.

무언가로 감싸줘야지만 제대로 코드가 작동한다.

 

 

2.javaScript

JSX안에서 자바스크립트를 표현할때는 브라켓 " { }  " 으로 감싸주면 됩니다.

ex) render(){

   let text = "Hello React";

  return(

     <div>{text}</div>

   );

}

 

render(){

  return ( <p>{1==1 ? 'True' : ' False'}</p> );

}

 

3.Inline Style

- JSX안에서 style을 설정 할때는 , string형식을 사용하지 않고

key가 camelCase인 객체가 사용이됩니다.

rener(){
	let Style = {
    	color:'aquq'
        ,backgroundColor : 'black'	//원래는 back-ground-color지만 카멜케이스 적용한다.
    };
    
    return(
    	<div style={style}>React CodeLab</div>
    };
}

/* JSX 안에서 class를 설정 할 때는 class= 가 아닌 className=을 사용하세요 */
render(){
	return(
    	<div className="box">React CodeLab</div>
   );
}

4.JSX안에서 주석 사용 시

문법 : { /*...*/ }

주석이 container element안에 작성되어야한다.

render(){
	return(
    	<div>
        	{/* This is How You Comment */}
            {/*Multi-line Testing */}
            ReactCodeLab
        </div>
    );
}

<div>위나 아래에서 사용 X

 

props

-component안에서 props 변경은 절대 불가능하다.( component에서 props는 read only이기 때문 )

- 컴포넌트 내부의 Immutable Data

- JSX 내부에 {this.props.propsName}

- 컴포넌트를 사용 할 때, <>괄호 안에 propsName="value"

- this.props.children은 기본적으로 갖고 있는 props로서, <Cpnt>여기에 있는 값이 들어간다.</Cpnt>

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


class App extends React.Component{
  render(){
    return(
      <Codelab name="This is Name">zz</Codelab> // name과 사이에 text값 전달
    );
  }
}

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

 

Props의 기본 값 설정

Component의 선언이 끝난 후 defaultProps를 선언하면 된다.

class App extends React.Component{
	render(){
    	return(
        	<div>{this.props.value}</div>
          );
        }
 };  
 //컴포넌트 선언이 끝난 후
 
 
 //defaultProps 설정
 App.defaultProps  = {
 	value : 0
 };

 

Type 검증

Components.propTypes = { ... }

class App extends React.Component{

	render(){
    	return(
        	<div>
            	{this.props.value}
                {this.props.secondValue}
                {this.props.thirdValue}
            </div>
         );
     }
  };
  
  App.propTypes = {
  	value : React.PropTypes.string
    ,secondValue : React.PropTypes.number
    ,thirdValue : React.PropTypes.any.isRequired
  };
       
              

->최신버전 리액트는 propTypes를 따로 분리하여 사용하기 때문에 따로 추가시켜 사용해야합니다 !!

 

 

'React' 카테고리의 다른 글

[React]React & Node & Mongoose & git연동  (0) 2020.11.13
[React] package.json이란?  (0) 2020.11.13
[React]Component문법  (0) 2020.11.11
[React]리액트 state 마음대로 변경하기  (0) 2020.11.11
[React]JSX에서 리액트 style  (0) 2020.11.11