React 이벤트

박서현·2023년 8월 16일
0
post-thumbnail

생활코딩 - React 이벤트

Header 컴포넌트에 이벤트 기능 넣기

onChangeMode

<div>
	<Header title="REACT" onChangeMode={function(){

      }}></Header>
    <Nav topics={topics}></Nav>
    <Article title="Welcom" body="Hello, WEB"></Article>
</div>  

🌼Header의 a 링크를 클릭하면 onChangeMode 함수를 호출하여 이벤트가 발생하게 된다.


Header 이벤트 등록

function Header(props) {
    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="REACT" onChangeMode={function(){
                alert('header')
            }}></Header>
            <Nav topics={topics}></Nav>
            <Article title="Welcom" body="Hello, WEB"></Article>
        </div>
    );
}


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()
                    props.onChangeMode(event.target.id)
                }}>{t.title}</a>
            </li>)
    }
    return  <nav>
                <ol>
                    {lis}
                </ol>
            </nav>
}

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="REACT" onChangeMode={function(){
                alert('header')
            }}></Header>
            <Nav topics={topics} onChangeMode={(id) =>
                alert(id)}></Nav>
            <Article title="Welcom" body="Hello, WEB"></Article>
        </div>
    );
}


🌼event.target.id target : event를 유발하는 태그를 가리킨다.
🌼html과 문법이 다르다. React만의 문법이 있음!!

0개의 댓글