2swan

React Practice(3) 본문

Programming/React

React Practice(3)

2swan 2023. 9. 6. 13:37

App.js

import logo from './logo.svg';
import {Component} from "react";
import './App.css';
import CommentList from './CommentList';
import TodoListTemplate from './component/TodoListTemplate';
import Form from './component/Form';
import TodoItemList from './component/TodoItemList';
import NotificationList from './NotificationList';

class App extends Component {
    state = {
    id : 4,
    input : '',
    todos : [
      {id: 0, text: '치킨먹기1', checked:false},
      {id: 1, text: '치킨먹기2', checked:true},
      {id: 2, text: '치킨먹기3', checked:false},
      {id: 3, text: '치킨먹기4', checked:true}
    ]
  }

  handleChange = e => {
    this.setState({
     input : e.target.value
    })
  }
  //추가
  handleCreate = ()=>{
    const {input, todos} = this.state
    this.setState({
    input : '',
    todos : todos.concat({
      id: this.id++,
      text: input,
      checked: false
    })
   })
  }

  //삭제
  handleRemove = id =>{
    // console.log("handleRemove id: "+id)
    const {todos} = this.state
    const nextTodos = todos.filter(todo => todo.id !==id)

    this.setState({
    todos : nextTodos
    })
}
  //토글
    handleToggle = (id)=>{
    // console.log("handleToggle id : "+id)
    const {todos} = this.state
    
    const index = todos.findIndex(todo => todo.id === id)
    const selected = todos[index]   //선택된 객체{id: 1, text:'치킨먹기', checked:true}

    const nextTodos = [...todos]
    nextTodos[index] ={
      ...selected,
      checked : !selected.checked
    }
    this.setState({
      todos : nextTodos
    })
  }
  //입력하고 엔터키
  handleKeyPress = e=>{
    if(e.key === 'Enter'){
      this.handleCreate()
    }
  }
  
  render(){
  return (
    <div>
          {/* <CommentList/> */}
          {/* <TodoListTemplate
            form={
              <Form value={this.state.input}
              onKeyPress = {this.handleKeyPress}
              onChange = {this.handleChange}
              onCreate = {this.handleCreate}
              />
            }
          >

          <TodoItemList
          todos={this.state.todos}
          onRemove={this.handleRemove}
          onToggle={this.handleToggle}
          />

          </TodoListTemplate>    */}
          <NotificationList/>
    </div>
    );
  }
}

export default App;

 

Comment.js

const styles = {
    wrapper: {
        margin: 8,
        padding: 8,
        display: "flex",
        flexDirection: "row",
        border: "1px solid grey",
        borderRadius: 16,
    },
    imageContainer: {},
    image: {
        width: 50,
        height: 50,
        borderRadius: 25,
    },
    contentContainer: {
        marginLeft: 8,
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
    },
    nameText: {
        color: "black",
        fontSize: 16,
        fontWeight: "bold",
    },
    commentText: {
        color: "black",
        fontSize: 16,
    },
};

function Comment(props){
  return(
    <div style={styles.wrapper}>
    <div style={styles.imageContainer}>
      <img 
      style={styles.image}
      />
    </div>
    
    <div style={styles.contentContainer}>
      <span style={styles.nameText}>{props.name}</span>
      <span style={styles.commentText}>{props.comment}</span>
    </div>
    </div>
  )
}
export default Comment;

 

CommentList.js

import Comment from "./Comment";

const comments = [
  {
    name : "이인제",
    comment : "안녕하세요, 소플입니다."
  },
  {
    name : "유재석",
    comment : "리액트 재미있어요."
  },
  {
    name : "강민경",
    comment : "저도 리액트 배워보고 싶어요!!."
   }
]
function CommentList(){
  return(
    <div>
      <h1>CommentList</h1>
      {
        comments.map((comment,i)=>{
          return(
            <div key={i}>
             {/* {comment.name} // {comment.comment} <br/> */}
            <Comment name={comment.name} comment={comment.comment}/>
            </div>
          )
        })
      }
    </div>
  )
}
export default CommentList;

 

Notification.js

import { Component } from "react";

const styles = {
    wrapper: {
        margin : 8,
        padding : 8,
        display : "flex",
        flexDirection : "row",
        border : "1px solid grey",
        borderRadius : 16,
    },
    messageText: {
        color : "black",
        fontSize: 16,
    },
};

class Notification extends Component{
    constructor(props){
        super(props)
        this.state ={}
    }
    componentDidMount(){
        console.log(`${this.props.id}componentDidMount() called.`)
    }
    componentDidUpate(){
        console.log(this.props.id+"componentDidUpate() called.")
    }
    componentWillUnmount(){
        console.log(this.props.id+"componentWillUnmount() called.")
    }
    render(){
        return(
            <div style={styles.wrapper}>
                <span style={styles.messageText}>{this.props.message}</span>
            </div>
        )
    }
}

export default Notification;

 

NotificationList.js

import { Component } from "react";
import Notification from "./Notification";

const reservedNotifications=[
    {
        id : 1,
        message : "안녕하세요, 오늘 일정을 알려드립니다."
    },
    {
        id : 2,
        message : "점심식사 시간입니다."
    },
    {
        id : 3,
        message : "이제 곧 미팅이 시작됩니다."
    },
];

var timer;

class NotificationList extends Component{
    constructor(props){
        super(props)
        this.state={
            notifications : []
        }
    }

    componentDidMount(){
        const {notifications} = this.state
        timer = setInterval(()=>{
            if(notifications.length < reservedNotifications.length){
                const index = notifications.length;
                notifications.push(reservedNotifications[index]);
                this.setState({
                    notifications : notifications
                })
            }else{
                this.setState({
                    notifications : []
                })
                clearInterval(timer)
            }

        },1000)
    }
    componentWillUnmount(){
        if(timer){
            clearInterval(timer)
        }
    }
    render(){
        return(
            <div>
                {
                    this.state.notifications.map((notification)=>{
                        return(
                            <Notification
                            key={notification.id}
                            id={notification.id}
                            message={notification.message}/>
                        )
                    })
                }
            </div>
        )
    }
}

export default NotificationList;

 

 

 

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

React DB 연결(JPA)  (0) 2023.09.11
React 추가, 삭제(JPA)  (0) 2023.09.11
React Practice(2)  (0) 2023.09.06
React Practice(1)  (0) 2023.09.06
React Practice(4-3)  (0) 2023.09.04