2021-05-25 코드리뷰

노성호·2021년 5월 25일
0

react

목록 보기
4/12

코드 가독성

기존 코드

<RadioGroup
    id="creater"
    aria-label="generator"
    name="generator"
    row
    onChange={(e) => {
    const value = e.target.value === 'teacher' ? 'teacher' : 'org';
    const form = { ...props.formData, creater: value };
    setOrgDescDisabled(props.formData.creater === 'org');
    props.handler(form);
    console.log(form);
  }}
  value={props.formData.creater}
>

<TextField
  id="title"
  className={classes.textField}
  variant="outlined"
  label="클래스 제목을 입력해주세요."
  onChange={(e) => {
    const value = e.target.value;
    const form = { ...props.formData, title: value };
    props.handler(form);
  }}
  value={props.formData.title}
/>

onChange=>{} 내부에 이벤트를 각각 구현하고 있었다. 코드 길이도 길어지고, 가독성도 좋지 않은 상태였음.

코드 리뷰 후 코드

function handleChangeForm(propertyName: keyof FormData, value: unknown) {
  props.handler({ ...props.formData, [propertyName]: value });
}

<TextField
  id="title"
  className={classes.textField}
  variant="outlined"
  label="클래스 제목을 입력해주세요."
  onChange={(e) => handleChangeForm('title', e.target.value)}
  value={props.formData.title}
/>

handleChangeForm(...) 이라는 핸들러를 만들고, onChange={} 이벤트 내부에 핸들러 함수 하나만을 이용해서 이벤트를 컨트롤 하게 만든다. 단 한 줄로 코드가 정리되었으며 다른 이벤트에도 동일하게 적용할 수 있다.

children & onClick event

interface CreateProjectCardProps {
  onclick?: () => void;
  children: React.ReactNode;
}

function CreateProjectCard(props: CreateProjectCardProps) {
  return (
    <Paper>
      <Typography>프로젝트</Typography>
      <img src="statics/imgs/poision.png" />
    </Paper>
  );
}

<CreateProjectCard
  onclick={() => {
    history.push('/class/project/create/select');
  }}     
>
  <CardContent>
    <Typography variant="h5">프로젝트 생성</Typography>
  </CardContent>
</CreateProjectCard>

children

children을 선언하지 않고 리액트 컴포넌트 내부에 children를 선언할수 있는 방법은 없다. 심지어 위의 CreateProjectCardchildren을 렌더링 하고 있지도 않았음. children을 인터페이스 파라메터로 넣지 않고 사용하려면, styled-components를 이용해서 컴포넌트를 만들고 const CardWrapper = styled(Paper) 처럼 컴포넌트를 만들어 사용해야 한다.

onClick

CreateProjectCard에는 onclick이라는 프로퍼티가 있다. 나는 당연히 onClick 이벤트에 onclick 구현을 넣어주면 이벤트가 발생할거라 생각하고 있었다. 하지만 안됨ㅋ
일단 위 구현에서의 문제는 <Paper>에서 onclick={function}을 전달하고 있지도 않고있다. CreateProjectCard에서 onclick파라메터에 그냥 익명함수를 넣어주고 있다.

refactoring

function CreateProjectCard(props: CreateProjectCardProps) {
  return (
    <Paper onClick={() => props.onclick}>
      <Typography>비즈니스모델 캔버스</Typography>
      <img src="statics/imgs/poision.png" />
      {props.children}
    </Paper>
  );
}

<CreateProjectCard
  onclick={() => {
    history.push('/class/project/create/select');
  }}
 >
    <CardContent>
    <Typography variant="h5">+ 프로젝트 생성</Typography>
  </CardContent>
</CreateProjectCard>

children{props.children}으로 렌더링 해주고 있고(styled-components를 쓸 수도 있다), <Paper>에는 onClick={() => props.onclick}와 같이 <Paper>onClickonclick 함수 구현을 넣어주도록 해주었다.

0개의 댓글