Skip to content
← Back to rules

react/no-this-in-sfc 정확성

작동 방식

상태 없는 함수형 컴포넌트 내에서 this를 사용하는 것을 막습니다.

왜 문제가 되는가?

리액트에서 상태 없는 함수형 컴포넌트(SFC)는 this를 통해 프롭스와 컨텍스트를 받지 않습니다. 대신 함수 매개변수로 전달받습니다. 따라서 SFC 내부에서 this를 사용하는 것은 클래스 컴포넌트에서 변환할 때 실수를 범했거나, 두 가지 컴포넌트 스타일에 익숙하지 않기 때문입니다.

예시

이 규칙에 해당하는 잘못된 코드 예시:

jsx
function Foo(props) {
  return <div>{this.props.bar}</div>;
}

function Foo(props) {
  const { bar } = this.props;
  return <div>{bar}</div>;
}

const Foo = (props) => (this.props.foo ? <span>{props.bar}</span> : null);

이 규칙에 해당하는 올바른 코드 예시:

jsx
function Foo(props) {
  return <div>{props.bar}</div>;
}

function Foo({ bar }) {
  return <div>{bar}</div>;
}

class Foo extends React.Component {
  render() {
    return <div>{this.props.bar}</div>;
  }
}

사용 방법

이 규칙을 구성 파일 또는 명령줄 인터페이스를 통해 활성화하려면 다음을 사용할 수 있습니다:

json
{
  "plugins": ["react"],
  "rules": {
    "react/no-this-in-sfc": "error"
  }
}
bash
oxlint --deny react/no-this-in-sfc --react-plugin

참고 자료