React statr 2

๋ฐ•์„œํ˜„ยท2023๋…„ 8์›” 18์ผ
0
post-thumbnail
post-custom-banner

์ƒํ™œ์ฝ”๋”ฉ- React 7. state

๐Ÿ”ธ๊ธฐ๋ณธ ์ฝ”๋“œ

๐Ÿ“ src > App.js

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


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

function Header(props) {
    return  <header>
                <h1><a href="/" onClick={function(event){
                    event.preventDefault();
                    props.onChangeMode()
                }}>{props.title}</a></h1>
            </header>
}

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>
    );
}

export default App;
  • prop : componunt๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์™ธ๋ถ€์ž๋ฅผ ์œ„ํ•œ ๋ฐ์ดํ„ฐ
  • state : componunt๋ฅผ ๋งŒ๋“œ๋Š” ๋‚ด๋ถ€์ž๋ฅผ ์œ„ํ•œ ๋ฐ์ดํ„ฐ

1. mode ์‹๋ณ„์ž ์ƒ์„ฑ

๐Ÿ“ src > App.js
1. const mode = 'WELCOM'; ์ถ”๊ฐ€
mode์˜ ๊ฐ’์ด ๋ฌด์—‡์ด๋ƒ์— ๋”ฐ๋ผ์„œ ๋ณธ๋ฌธ์˜ ๋‚ด์šฉ์ด ๋‹ฌ๋ผ์ง€๊ฒŒ ํ•˜๊ณ  ์‹ถ๋‹ค.

function App() {
    const mode = 'WELCOM';
    const topics = [
        {id:1, title:'html', body:'html is ...'},
        {id:2, title:'css', body:'css is ...'},
        {id:3, title:'javascript', body:'javascript is ...'}
    ]
    let content = null;
    if(mode === 'WELCOME') {
        content = <Article title="Welcom" body="Hello, WEB"></Article>
    } else if (mode === 'READ') {
        content = <Article title="READ" body="Hello, READ"></Article>
    }
    return (
        <div>
            <Header title="REACT" onChangeMode={function(){
                alert('header')
            }}></Header>
            <Nav topics={topics} onChangeMode={(id) =>
                alert(id)}></Nav>
            {content}
        </div>
    );
}

mode ๊ฐ’์„ event๊ฐ€ ๋ฐœ์ƒํ–ˆ์„ ๋•Œ ๋ณ€๊ฒฝํ•ด์ฃผ๋„๋ก ์ˆ˜์ •ํ•œ ๊ฒƒ

post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€