Skip to content
← Back to rules

react/no-this-in-sfc 正しさ

何を実行するか

ステートレスな関数型コンポーネント内での this の使用を防止します。

なぜ悪いのか

React では、ステートレスな関数型コンポーネント(SFC)はプロパティやコンテキストを関数の引数として受け取るため、this を通じて取得しません。SFC 内で this を使用することは、クラスコンポーネントから変換する際の誤り、または2つのコンポーネントスタイルに対する理解不足を示していることが多いです。

このルールに対して不正なコードの例:

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>;
  }
}

使い方

このルールを設定ファイルまたは CLI で有効化するには、以下の方法を使用できます:

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

参照