희디 2023. 2. 17. 03:08

이벤트 발생시 함수를 호출해서 이벤트 발생하게 함. like onclick

유사 a태그. 

event 객체로 사용

a태그의 기본으로 링크이동을 막는 event.preventDefault();

event.target (이벤트를 동작하게 만든 요소)

 

import logo from './logo.svg';
import './App.css';



function 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=>{
      event.preventDefault();  // a태그가 작동되는것을 막음 
      props.onChangeMode(event.target.id);  // 이벤트가 유발되는 target을 통해 prop의 onChangeMode 실행?
    }}>{t.title}</a></li>);
  }

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

function Article(props) {
  
  return <article>
    <h2>{props.title}</h2>
    {props.body}
  </article>
}

function Header(props) {
  //console.log('props', props, props.title);
  return <header>
    <h1><a href = "/" onClick={function(event){
      event.preventDefault();
      props.onChangeMode(); // 함수 호출됨.
    }}>{props.title}</a></h1>
  </header>
}

function App(){

  const topics = [
    {id:1, title:'html', body:'html is ...'},
    {id:2, title:'css', body:'css is ...'},
    {id:3, title:'javascript', body:'javascript is ...'}
  ]

  return (
    <div>
      <Header title = "Web" onChangeMode={function(){
        alert('Header');
      }}></Header>
      <Nav topics={topics} onChangeMode={(id) =>{
        alert(id);
      }}></Nav>
      <Article title="Welcome" body="Hello, Web"></Article>
      <Article title="Hi" body="Hello, React"></Article>
    </div>
  );
}

export default App;