IT이야기

동일한 컴포넌트를 동적으로 반응

cyworld 2022. 3. 13. 11:01
반응형

동일한 컴포넌트를 동적으로 반응

나는 동적으로 같은 컴포넌트 내의 컴포넌트를 호출하고 싶다.

        commentdata = [
  {
    "_id": "5dbc479babc1c22683b73cf3",
    "comment": "wow .. this is awsome",
    "children": [
      {
        "_id": "5dbc481ec3bb512780ebda22",
        "comment": "second child",
        "children": [
          {
            "_id": "5dbc481ec3bb512780ebda22",
            "comment": "hi darling",
            "children": [],
            "user": {
              "_id": "5dbb81c8c597533bf4c38e75",
              "username": "arunkavale",
              "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/johnsmithagency/128.jpg"
            },
            "updatedDate": "2019-11-01T14:58:38.188Z",
            "createdDate": "2019-11-01T14:58:38.188Z"
          }
        ],
        "user": {
          "_id": "5dbb81c8c597533bf4c38e75",
          "username": "arunkavale",
          "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/johnsmithagency/128.jpg"
        },
        "updatedDate": "2019-11-01T14:58:38.188Z",
        "createdDate": "2019-11-01T14:58:38.188Z"
      },
      {
        "_id": "5dbc481ec3bb512780ebda22",
        "comment": "yep",
        "children": [],
        "user": {
          "_id": "5dbb81c8c597533bf4c38e75",
          "username": "arunkavale",
          "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/johnsmithagency/128.jpg"
        },
        "updatedDate": "2019-11-01T14:58:38.188Z",
        "createdDate": "2019-11-01T14:58:38.188Z"
      }
    ],
    "user": {
      "_id": "5dbb9683b44bfa2a3dce55bd",
      "username": "mayank",
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/alxndrustinov/128.jpg"
    },
    "createdDate": "2019-11-01T14:56:27.580Z",
    "updatedDate": "2019-11-01T14:58:38.188Z",
    "__v": 0
  }
]

위는 내가 bcakend로부터 얻은 comment list 데이터 입니다.

import React from 'react';
import CommentDetail from './commentDetails';

class CommentList extends React.Component {
    constructor(props){
        super(props);
    }
    render(){
        const comments = this.props.comments.map((comment)=>{
            return <CommentDetail comment={comment.comment} key={comment._id}  author = {comment.user} timeAgo={comment.createdDate}></CommentDetail>
        })
        return (
            <div >
               {comments}
            </div >
        )
    }
}

export default CommentList;

.

import React from 'react';
import CommentAction from './commentAction';

const CommentDetail = (props) =>{
    console.log(props);

    return (
        <div className="comment">
            <a href="/" className="avatar">
            <img alt="avatar" src={props.author.avatar} />
            </a>
            <div className="content">
                <a href="/" className="author">
                    {props.author.username}
                </a>
                <div className="metadata">
                    <span className="date">
                    {props.timeAgo}
                    </span>
                </div>
                <div className="text">{props.comment}</div>
                <CommentAction user={props.author}></CommentAction>
            </div>
        </div>
    )
}

export default CommentDetail;

위의 모든 코드는 잘 작동하지만 나는 다음과 같은 것을 원한다.

    import React from 'react';
import CommentDetail from './commentDetails';

class CommentList extends React.Component {
    constructor(props){
        super(props);
    }
    render(){
        const comments = this.props.comments.map((comment)=>{
            if(comment.children.length>0){
                let children=[];
                for (let i = 0; i < comment.children.length; i++) {
                    let commentComp = <CommentDetail comment={comment.comment} key={comment._id}  author = {comment.user} timeAgo={comment.createdDate}>

                            <CommentDetail comment={comment.children[i].comment} key={comment.children[i]._id}  author = {comment.children[i].user} timeAgo={comment.children[i].createdDate}>
                            </CommentDetail>
                    </CommentDetail>

                    children.push(commentComp)
                }
                return children
            }
            return <CommentDetail comment={comment.comment} key={comment._id}  author = {comment.user} timeAgo={comment.createdDate}></CommentDetail>
        })
        return (
            <div >
               {comments}
            </div >
        )
    }
}

export default CommentList;

여기서 함수는 CommentDetail 구성 요소에서처럼 CommentDetail에 모든 자녀가 중첩되어 있는지 확인해야 한다.나는 재귀적 기능을 시도해 보았지만...이것을 도와줘.그리고 미리 고마워.

당신이 원하는 결과가 무엇이었으면CommentDetail어떤 방법으로도 아이들을 다루지 않는다. 그래서 둥지를 틀고.commentDetaila 이내에commentDetail이 경우 어레이의 최상위 수준만 표시됨

먼저 만들기renderComments렌더 밖의 방법(대부분의 경우 렌더링만 하는 것이어야 함)

함수를 렌더링하는 다음 랩<ul>그리고 돌아오다<li>지도 함수에서.

그 안에<li>아이가 있는지 없는지, 또 다른 아이를 보금자리를 찾아보다.<ul>그리고renderComments…과 함께comment.children재귀적으로

실행 가능한 코드 조각:

class CommentList extends React.Component {
  renderComments = (comments) => (
      comments.map(comment=>(
        <li key={comment._id}>
          <CommentDetail comment={comment} />
          {comment.children.length && <ul>{this.renderComments(comment.children)}</ul>}
        </li>
      ))
  )

  render(){
      return <ul>{this.renderComments(this.props.commentdata)}</ul>
  }
}






















const CommentDetail = ({comment}) =>{

  return (
    <div className="comment">
      <a href="/" className="avatar">
        <img alt="avatar" src={comment.user.avatar} />
      </a>
      <div className="content">
        <a href="/" className="author">
          {comment.user.username}
        </a>
        <div className="metadata">
          <span className="date">
            {comment.createdDate}
          </span>
        </div>
        <div className="text">
          {comment.comment}
        </div>
      </div>
    </div>
  )
}






const commentdata = [
  {
    "_id": "5dbc479babc1c22683b73cf3",
    "comment": "wow .. this is awsome",
    "children": [
      {
        "_id": "5dbc481ec3bb512780ebda25",
        "comment": "second child",
        "children": [
          {
            "_id": "5dbc481ec3bb512780ebda23",
            "comment": "hi darling",
            "children": [],
            "user": {
              "_id": "5dbb81c8c597533bf4c38e73",
              "username": "arunkavale",
              "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/johnsmithagency/128.jpg"
            },
            "updatedDate": "2019-11-01T14:58:38.188Z",
            "createdDate": "2019-11-01T14:58:38.188Z"
          }
        ],
        "user": {
          "_id": "5dbb81c8c597533bf4c38e72",
          "username": "arunkavale",
          "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/johnsmithagency/128.jpg"
        },
        "updatedDate": "2019-11-01T14:58:38.188Z",
        "createdDate": "2019-11-01T14:58:38.188Z"
      },
      {
        "_id": "5dbc481ec3bb512780ebda24",
        "comment": "yep",
        "children": [],
        "user": {
          "_id": "5dbb81c8c597533bf4c38e71",
          "username": "arunkavale",
          "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/johnsmithagency/128.jpg"
        },
        "updatedDate": "2019-11-01T14:58:38.188Z",
        "createdDate": "2019-11-01T14:58:38.188Z"
      }
    ],
    "user": {
      "_id": "5dbb9683b44bfa2a3dce55bd",
      "username": "mayank",
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/alxndrustinov/128.jpg"
    },
    "createdDate": "2019-11-01T14:56:27.580Z",
    "updatedDate": "2019-11-01T14:58:38.188Z",
    "__v": 0
  }
]


ReactDOM.render(
  <CommentList commentdata={commentdata}/>,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

<div id="root"></div>

참조URL: https://stackoverflow.com/questions/58666651/nesting-react-same-compoennt-dynamically

반응형