Component 반환 함수 && OnClick 파라메터 넘겨주기

공부는 혼자하는 거·2021년 9월 7일
0

React Tip

목록 보기
21/24

JSX 문법에서 함수를 바인딩 시킬 때 () 넣어주면 바로 실행된다.. 이를 방지하면서 파라미터를 넘겨줄러면, 아래처럼 하면 된다..

function clickMe(parameter){
  //
}

<button onClick={() => clickMe(someparameter)}></button>

만약 이벤트까지 넘겨주고 싶다면..

function clickMe(event, someParameter){
     //do with event
}
<button 
   onClick={(e) => {
      clickMe(e, someParameter);
   }}
/>

이나

const clickMe = (parameter) => (event) => {
    // Do something
}
And use it:

<button onClick={clickMe(someParameter)} />

이나

function clickMe(parameter, event){
}

<button onClick={this.clickMe.bind(this, someParameter)}></button>

https://stackoverflow.com/questions/42597602/react-onclick-pass-event-with-parameter

이 점을 응용하여 컴포넌트를 리턴하는 메서드를 바인딩 시켜줄 수 있다.

const menu = (principalId) => {
    console.log(principalId);

    return (
      <Menu>
        <Menu.Item>
          {/* <Link to={`/${principal}`}>내 벨로그</Link> */}
          {/* <Link to="/1">내 벨로그</Link> */}
        </Menu.Item>
        <Menu.Item>
          <Link to="/write">새 글 작성</Link>
        </Menu.Item>
        <Menu.Item>
          <div onClick={logout}>로그아웃</div>
        </Menu.Item>
        <Menu.Item>
          <div onClick={tokenTest}>user Test</div>
        </Menu.Item>
        <Menu.Item>
          <div onClick={adminTeset}>admin Test</div>
        </Menu.Item>
        <Menu.Item>
          <Link to="/setting">설정</Link>
        </Menu.Item>
        <Menu.Item>
          <Link to="/1/1">게시글 상세보기</Link>
        </Menu.Item>
      </Menu>
    );
  };
{loginDone === false && principal == null ? (
              <div style={{ marginLeft: '1rem' }} className="loginButtonDiv">
                <Button onClick={showLoginModal}>로그인 </Button>
                {/* 모달 컨테이너 */}
                <AuthModal data={data} loginVisible={loginVisible} setLoginVisible={setLoginVisible} joinDone={joinDone} joinError={joinError} />
              </div>
            ) : (
              <>
                <StyledLoginSuccessDiv>
                  <StyledDropdown overlay={() => menu(principal.id)} trigger={['click']}>
                    <div className="ant-dropdown-link" onClick={(e) => e.preventDefault()} style={{ display: 'flex', marginTop: '0.3rem' }}>
                      <div>
                        <StyledUserImg />
                      </div>
                      <div style={{ marginTop: '3px', marginLeft: '3px' }}>
                        <CaretDownOutlined style={{ fontSize: '1rem', cursor: 'pointer' }} />
                      </div>
                    </div>
                  </StyledDropdown>
                </StyledLoginSuccessDiv>
              </>
            )}

https://www.w3schools.com/react/react_events.asp

https://ko.reactjs.org/docs/handling-events.html

https://ko.reactjs.org/docs/faq-functions.html

import React, { memo } from 'react';
import { Comment, Tooltip, Avatar } from 'antd';
import moment from 'moment';
import { DislikeOutlined, LikeOutlined, DislikeFilled, LikeFilled } from '@ant-design/icons';
import { useState } from 'react';
import { createElement } from 'react';
import { Link } from 'react-router-dom';

// const StyledRecommentFrom

const comment = () => {};

const CommentCard = memo((props) => {
  const { comment, userId, postId } = props;

  //const actions = [<span key="comment-basic-reply-to">Reply to</span>];  계층형 댓글은 시간날때
  <Comment
    actions={[<span key="comment-nested-reply-to">답글</span>]}
    author={<Link to={`/${userId}`}>{comment.user.username}</Link>}
    // avatar={<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" alt="Han Solo" />}
    content={<p dangerouslySetInnerHTML={{ __html: comment.content }} />}
    style={{ paddingBottom: '3rem' }}
    datetime={
      <Tooltip title={moment(comment.createDate).format('YYYY-MM-DD HH:mm:ss')}>
        <span>{moment().fromNow()}</span>
      </Tooltip>
    }
  />;
});

const RealComment = () => {
  return (
    <>
      <CommentCard />
    </>
  );
};

export default CommentCard;
profile
시간대비효율

0개의 댓글