Web/React

React - 스파르타강의 2주차 숙제

또롱또 2022. 5. 20. 13:03
728x90

뭔가 Layout만 하기에는 심심할거 같아서

useRef()를 통해서 input 값을 동적으로 name에 줘봤다.

다만 input창을 초기화 시키는 방법을 실패했다.

막장의 소스코드는 아래있다

app.js and start.jsx

더보기

// app. js

import React, {useState, useRef} from "react";


import styled from "styled-components"; // styled component


// components
import Start from './Start.jsx'
import img from "./scc_img01.png";


function App() {
  const [name, setName] = useState('르탄이'); // name에 기본값 르탄이를 넣어두고 setName에 바뀌는 이름마다 갈아치운다
  const inputRef = useRef(); // input Dom에 접근하기 위한


  // 버튼이 눌릴때의 이벤트
  const onChange = (event) => {
    event.preventDefault(); // 새로고침 방지
    setName((value)=> value = inputRef.current.value) // setName에는 input에 입력된 값을 추가해줌
  };


  return (
    <AppWrap>
      <Container>
          <img src={img} alt="img"style={{width: "100px",margin: "16px"}}/>
          {/* props로 name에 들어오는 걸 컴포넌트에 넘겨줌 */}
          <Start name={name}/>
          <form style={{display:"flex", flexDirection:"column", justifyContent:"center", alignItems:"center"}} onSubmit={onChange}>
            {/* ref를 이용해서 DOM에 접근 */}
            <Input ref={inputRef} type="text" placeholder="이름을 적으세요"/>
            <Button type="submit">시작하기</Button>
            <Button type="reset">초기화</Button>
          </form>
      </Container>
    </AppWrap>
  );
}


// STYLED COMPONENTS
const AppWrap = styled.div`
  background-color: #eee;
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
`;


const Container = styled.div`
  background-color: #fff;
  width: 50vw;
  max-width: 350px;
  margin: auto;
  height: 80vh;
  padding: 16px;
  border: 1px solid #ddd;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
`;


const Input = styled.input`
  border: 1px solid #dadafc;
  border-radius: 30px;
  padding: 10px;
  width: 100%;
`;


const Button = styled.button`
  padding: 10px 36px;
  background-color: #dadafc;
  border: #dadafc;
  border-radius: 30px;
  margin: 10px 0;
`;


export default App;
 
 

// start.js

import styled from "styled-components";

const Start = ({name}) =>{
    return(
        <>
            <Title>나는 <TextWrap>{name}</TextWrap> 에 대해서</Title>
            <Title>얼마나 알고 있을까?</Title>
        </>
    )
}

const TextWrap = styled.span`
    background-color: #f6e58d;
    padding: 10px;
    border-radius: 30%;
`;

const Title = styled.h2`
`;

export default Start;

 

728x90

'Web > React' 카테고리의 다른 글

React - Github IO  (0) 2022.05.22
React - Route 5 --> 6  (0) 2022.05.20
React - Styled Components 02  (0) 2022.05.17
React - Styled Components 01  (0) 2022.05.16
React Hook 03 - useRef()  (0) 2022.05.16