React props, event (생활코딩 2022 개정판 )

FE 개발자 신상오·2022년 6월 15일
0

React

목록 보기
3/10
post-thumbnail

📚 component

여러 함수들을 모아 하나의 특정한 기능을 수행할 수 있도록 구성한 작은 단위

// 컴포넌트 Headers 작성
const Headers = () => {
  return (
  <headers>
  <h1><a href="/">{props.title}</a></h1>
  </headers>
);}


// 컴포넌트 모음
const App = () => {
  return (
    <div>
      <Headers />
    </div>
  );}


// 컴포넌트 외부에서 사용할 수 있도록 내보내는 명령어
export default App;

📚 Props

컴포넌트의 입력값, 부모 컴포넌트로부터 자식 컴포넌트로 전달된 데이터
(위에서 아래로 내려가는 개념)

⚠️ Props읽기 전용이므로 어떤 방식으로든 수정 x


const Headers = (props) => {
  
  console.log('props' , props, props.title)
  return (
  <headers>
  <h1><a href="/">{props.title}</a></h1>
</headers>
);}

➡️
props는 객체
지금 Header 컴포넌트의 props에는
key 값으로 title, value 값으로 REACT인 속성이 들어있음
props.title === 'React'

const App () => {
  <Headers title="REACT"/>
}

➡️
Headers 컴포넌트에 title="REACT"

📚 이벤트

사용자의 여러 행동 - 키보드 입력, 마우스 클릭, 화면 터치 등등

const Headers = (props) => {
  return (
  <headers>
  <h1><a href="/" onClick = {(event) => {
    event.preventDefault(); // 기본동작 방지 클릭해도 변화 x
    props.onChangeMode(); // 클릭마다 실행
  }}>{props.title}</a></h1>
</headers>
);}

➡️
OnClick 클릭 -> event가 매개변수로 들어옴 -> 함수 실행

const App = () => {
  return (
    <div>
      <Headers title="REACT" onChangeMode={() => {
        alert('Header');
      }} />
    </div>
  );}

➡️
Headers 컴포넌트의 props 객체
{
title : "REACT",
onChangeMode = {() => alert('Header')}
}


다른예제

const Nav = (props) => {
  const lis = []

  for(let i = 0; i < props.topics.length; i++){
    let t = props.topics[i];
    lis.push(<li key={t.id}>
      <a id = {t.id} href={'/read/' + t.id} onClick={(event) =>{
        props.onChangeMode(event.target.id);
      }}>{t.title}</a>
      </li>)
  }

  return (
  <nav>
  <ol>
   {lis}
  </ol>
</nav>
);}

➡️
event.target => 현재 이벤트를 발생시키는 <a> 태그
즉, OnClick이 실행되는 태그를 말함

event.tartget.id => <a> 태그 객체에 있는 속성의 id 값

const App = () => {
  const topics = [
    {id:1, title:'html', body:'html is ...'},
    {id:2, title:'css', body:'css is ...'},
    {id:3, title:'js', body:'js is ...'}
  ]
  return (
    <div>
      <Nav topics={topics} onChangeMode={(id) =>{
        alert(id);
      }}/>
    </div>
  );}
profile
주간 회고용 블로그입니다 (개발일지와 정보글은 티스토리에 작성합니다.)

0개의 댓글