TIL | React 04 / 컴포넌트 상태 states / props

김윤희·2022년 9월 13일
0
  • MainHeader.js
/*eslint-disable*/

import React, {useState} from "react";

function MainHeader(){
  	//[상태데이터, 상태를 위한 setter 함수]
	const [text, setClick] = useState("Hello world!");
  
	return (
    	<h1 onClick=(()=>{setClick("Bye world")})>{text}</h1>
    )
}

export default MainHeader
  • 예를들어 위에 코드를 props를 전달해서 MainHeader를 이곳저곳에서 쓰고 싶은데 text를 받아서 사용하고 싶다면 아래와 같이 해주면 된다

  • App.js

import MainHeader from "./components/MainHeader";
import "./App.css";

function App(){
  // HTML에서는 class를 class로 작성하지만 jsx에서 class는 예약어이기 때문에 
  //class는 className으로 작성한다
	return <div className="App"> 
    			<MainHeader text="Hello"></MainHeader>
                <MainHeader text="word"></MainHeader>
                <MainHeader text="Hello word"></MainHeader>
    		</div>
}

export default App;
  • MainHeader.js
import React, {useState} from "react";

//props
function MainHeader({text}){ //text = props
	return <h1>{text}</h1>
}

export default MainHeader

props란? - HTML attribute(속성)으로 정해주면 컴포넌트로 가져와서 사용할 수 있다 / props 객체로 받아온다 ex) {text, href, ...}

✔ state 와 props
= props는 부모 요소에서 데이터를 보내줄때 사용한다(수동적), 각각의 state를 갖고 있는 컴포넌트의 경우 독립적으로 움직인다

0개의 댓글