[react] 코드분석

오미희·2021년 7월 6일
0
기본적으로 <head>에 넣어야 할 부분
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
// 마지막은 babel에 관한 부분으로 아래의 코드에서는 사용하지 않았음 => 즉  babel 사용을 위해서는 마지막 세번째 코드를 head에 넣어주어야 한다.

<div id="root"></div>
<script type="text/javascript">

class App extends React.Component{
	render(){
    	return(
        	console.log('hello')
            // 여기는 반환값으로 줄 내용
        )
    }
}
ReactDOM.render(
	<App/>,
    document.querySelecrot('#root')
)
</script>

<!-- 기본적으로 react사용시에는 아래와 같이 div id="root" 이렇게 만들어주고  -->
<div id="root"></div>


<script type="text/javascript">
//LoginBtn만 내가 지정하는 class명 나머지는 외워야함
    class LoginBtn extends React.Component{
        constructor(props){
            super(props)
            	//props 함수형 컴포넌트에서 부모와 자식사이에 데이터를 전달하는 방법
    		//props사이의 데이터 흐름이 양방향이 아니다. => 즉 업데이트를 컴포넌트 사이에 전달하기 어려움
    		/*  // props 값 전달 참고 
    			function Welcome(props){
        			return <h1>hello, {props.name}</h1>
    				} 
                    	//welcome함수에는 props를 통해 name을 전달하여 출력
    			const element = <Welcome name="algml"/>
   			ReactDOM.render(
        			element,
        			document.getElementById('root')
    			)
     			===> hello algml 를 출력
    		*/                 
            
            
            this.state = {
                isLogin:false,

            }
        }
        // 위는 기본 세팅값 => 즉 기본적으로 그냥 외워야 함
        // 아래는 내가 어떤 식으로 출력할 것인지
        render(){
            return(
                //React.createElement('button',null,'로그인')  //<button
                //React.createElement(생성하려는 element,해당 element에 적용할 style or event,'입력내용')
                ** 스타일 적용시 {className:'box';style:'color':'blue'} 이와 같이 객체 식으로 적용
                ** 특별히 스타일을 적용하지 않을 경우 값을 null로 준다.
                // React.createElement('button',{onClick:()=>{alert('로그인버튼입니다.')}},'로그인')
                // 이벤트 넣을 때 반드시 카멜 형식 즉 처음에는 소문자 나중에 대문자 반드시 지켜야함
                React.createElement('button',{onClick:()=>{this.setState({isLogin:!this.state.isLogin})}},this.state.isLogin ? '로그아웃' : '로그인')
                // this.setState => 해당 값을 변경하기 위해 사용
                // this.setState의 첫번째 인자값은 무조건 객체로 들어간다.
                // 즉 setState({isLogin:!this.state.isLogin})은 위에서 false로 값을 준 상태이므로 onClick이 발생하면 false의 반대인 true가 isLogin의 설정값이 된다. 
            );
        }
    }
    // document.querySelector('#root').innerHTML('hello world') => 아래와 같은 부분
    // ReactDom사용시에는 2가지 인자값을 갖는다. 
    // 첫번째 인자값 => 내가 넣을 내용
    // 두번째 인자값 => 내가 넣을 위치
    ReactDOM.render(   // 가장 중요한 부분 화면에 출력을 가능하게 하는 것
        //React.createElement('button',null,'버튼'),            
            // 첫번째 인자값=> 만들 elememt
            // 두번째 인자값=> 해당 요소의 이벤트
            // 세번째 인자값-> 그 안에 넣을 내용
        React.createElement(LoginBtn),
        // 위에 주석처리된 부분과 같은 결과를 출력
        // 안에 생성한 class명을 넣어준다. 
        document.querySelector('#root')
        // 위의 내용을 넣을 위치
    )

    //리엑트는 기본적으로 html을 사용하지 않고 자바스크립트 만으로 화면을 만들 수 있도록 한 것
</script>
//babel을 이용하여 코드를 짠 경우
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>


</head>
<body>
    <!-- 기본적으로 react사용시에는 아래와 같이 div id="root" 이렇게 만들어준다. 이 안에 내용이 들어옴  -->
    <div id="root"></div>


    <script type="text/babel">
    //바벨사용시에는 위의 script type을 "text/babel"로 해야한다!! 중요!!
    //LoginBtn만 내가 지정하는 class명 나머지는 기본적으로 외워야하는 구문!!
        class LoginBtn extends React.Component{
            constructor(props){
                super(props)               
                this.state = {
                    isLogin:false,
                }
            }           
            render(){
                return(  // 자바스크립트 영역 => 즉 "" 가 아닌 대괄호로 표시해야함
                // 아래(jsx)와 같이 코드를 작성하기 위해 바벨을 설치           
                    <button onClick={()=>{ this.setState({isLogin:!this.state.isLogin}) }}>  
                        {this.state.isLogin?'로그아웃':'로그인'}    
                    </button> 
                    // 아래는 위에와 같은 코드 => 바벨을 사용하지 않는 경우
                    // React.createElement('button',{onClick:()=>{this.setState({isLogin:!this.state.isLogin})}},this.state.isLogin ? '로그아웃' : '로그인')           
                );
            }
        }
        
        ReactDOM.render(           
            React.createElement(LoginBtn),            
            document.querySelector('#root')            
        )


        //리엑트는 기본적으로 html을 사용하지 않고 자바스크립트 만으로 화면을 만들 수 있도록 한 것
    </script>
    
</body>
</html>
profile
안녕하세요

0개의 댓글