programing

리액트의 차이점은 무엇입니까?Function Component와 플레인 JS 함수 컴포넌트

css3 2023. 3. 1. 11:23

리액트의 차이점은 무엇입니까?Function Component와 플레인 JS 함수 컴포넌트

이 두 가지 예는 같은 것을 실현합니다.하지만 후드 아래에는 어떤 차이가 있을까?기능 컴포넌트와React.컴포넌트 및 리액트PureComponent. 하지만 관련 문서를 찾을 수 없습니다.React.FunctionComponent.

React.Function Component(기능 컴포넌트)

const MyComponentA: React.FunctionComponent = (props) => {
  return (
    <p>I am a React.FunctionComponent</p>
  );
};

일반 JS 함수 구성 요소:

const MyComponentB = (props) => {
  return (
    <p>I am a plain JS function component</p>
  );
};

후드 밑에는 아무런 차이가 없습니다.첫 번째는 TypeScript 구문을 사용하여 TypeScript의 유형을 나타냅니다.React.FunctionComponent그러나 둘 다 플레인 JS 함수 구성요소입니다.

몇 가지 사소한 차이가 있습니다. 플레인 함수 컴포넌트는 다음과 같은 문자열을 반환할 수 있습니다.

const FooString = () => "foo";

하지만 당신은 그 끈을 돌려받을 수 없었다.FunctionComponent.

const BarString: React.FC<{}> = () => "string";

따라서 반환 유형은 다음과 같아야 합니다.ReactElement|null

다른 점은 말이다.FunctionComponent에는 기본적으로 다음 1개의 속성이 포함되어 있습니다.children


// Note, no children defined
type Props = {
  name: string
}

const MyComponentA: React.FunctionComponent<Props> = (props) => {
  return (
    <p>I am a React.FunctionComponent and my name is {props.name}</p>
    <p>And I have {props.children}</p>
  );
};

const MyComponentB = (props: Props) => {
  return (
    <p>I am a plain JS function component</p>
    <p>But my {props.children} are undefined</p>
  );
};

위해서MyComponentBTS 컴파일러는 다음과 같이 불평합니다.children정의되어 있지 않습니다.

물론 두 구성 요소 모두 어린이를 통과시키고 TS 경고를 무시할 수 있습니다.

언급URL : https://stackoverflow.com/questions/53935996/whats-the-difference-between-a-react-functioncomponent-and-a-plain-js-function