bestsource

TypeScript로 대응 - 상태 비저장 함수에서 defaultProps 정의

bestsource 2023. 6. 23. 22:19
반응형

TypeScript로 대응 - 상태 비저장 함수에서 defaultProps 정의

나는 타입스크립트로 리액트를 사용하고 있으며 상태 비저장 기능을 만들었습니다.가독성을 위해 예제에서 쓸모없는 코드를 제거했습니다.

interface CenterBoxProps extends React.Props<CenterBoxProps> {
    minHeight?: number;
}

export const CenterBox = (props: CenterBoxProps) => {
    const minHeight = props.minHeight || 250;
    const style = {
        minHeight: minHeight
    };
    return <div style={style}>Example div</div>;
};

모든 것이 훌륭하고 이 코드는 올바르게 작동합니다.하지만 제 질문이 있습니다: 어떻게 정의할 수 있을까요?defaultProps위해서CenterBox구성요소?

대응 문서에 언급된 바와 같이:

(...) 그들은 보일러 플레이트가 없는 입력의 순수한 기능 변환입니다.그러나 .propTypes 및 .defaultProps를 ES6 클래스에 설정하는 것처럼 함수에 속성으로 설정하여 지정할 수 있습니다. (...)

다음과 같이 쉬워야 합니다.

CenterBox.defaultProps = {
    minHeight: 250
}

그러나 이 코드는 TSLint 오류를 생성합니다.error TS2339: Property 'defaultProps' does not exist on type '(props: CenterBoxProps) => Element'.

다시 한 번 말하지만, 어떻게 하면 정확하게 정의할 수 있습니까?defaultProps위 스택(React + TypeScript)에서?

2시간 동안 해결책을 찾다가...효과가 있습니다.

정의하려는 경우defaultProps화살표 기능은 다음과 같아야 합니다.

export const CenterBox: React.SFC<CenterBoxProps> = props => {
    (...)
};

그런 다음 다음과 같은 소품을 정의할 수 있습니다.

CenterBox.defaultProps = { someProp: true }

참고:React.SFC의 별칭입니다.React.StatelessComponent.

저는 이 질문(그리고 대답)이 누군가에게 도움이 되기를 바랍니다.최신 React 유형을 설치했는지 확인합니다.

React 문서에 설명된 것보다 더 나은 방법은 단순히 Javascript / Typescript default 인수를 사용하는 것이라고 생각합니다.

여기에 답이 있습니다: https://stackoverflow.com/a/54569933/484190 . 하지만 편의를 위해 다음과 같은 예가 있습니다.

import React, { FC } from "react";

interface CompProps {
  x?: number;
  y?: number;
}

const Comp: FC<CompProps> = ({ x = 10, y = 20 }) => {
  return <div>{x}, {y}</div>;
}

export default Comp;

이를 통해 Typescript는 사용자가 소품을 제공할 필요가 없으며 구성 요소 내부에서 "정의되지 않음"이 발생하지 않음을 알 수 있습니다.

그리고 이것은 다른 사람들이 이것을 발견할 경우를 대비하여 상태 저장 기능에 어떻게 작동하는지 보여줍니다.핵심은 defaultProps를 정적 변수로 선언하는 것입니다.

interface IBoxProps extends React.Props<IBoxProps> {
    x?: number;
    y?: number;
    height?: number;
    width?: number;
}

interface IBoxState {
    visible?: boolean;
}

export default class DrawBox extends React.Component<IBoxProps, IBoxState> {
    static defaultProps: IBoxProps;

    constructor(props: IBoxProps) {
        super(props);
    }
    ...
}

DrawBox.defaultProps = {
    x=0;
    y=0;
    height=10;
    weight=10;
};

React 16.7.0 기준 기능 구성 요소의 경우 'React'.SFC' 유형은 '로 인해 더 이상 사용되지 않습니다.React.FC'.

type TFuncComp = React.FC<{ text: string }>

const FuncComp: TFuncComp = props => <strong>{props.text}</strong>

FuncComp.defaultProps = { text: 'Empty Text' }

소스에서 사용되지 않는 경고

FC(기능 구성 요소)원본 입력

React를 사용하여 함수 구성 요소에 기본 특성을 입력합니다.FC에서 false 유형 오류가 발생할 수 있습니다.

   type Props = {
     required: string,
   } & typeof defaultProps;

   const defaultProps = {
     optDefault: 'optDefault'
   };

   const MyComponent: React.FC<Props> = (props: Props) => (
     <ul>
       <li>required: {props.required}</li>
       <li>optDefault: {props.optDefault}</li>
     </ul>
   )
   MyComponent.defaultProps = defaultProps;


   ReactDOM.render(
     <div>
       <MyComponent
         required='required'
         optDefault='over written'
       />
       <MyComponent   /* type error  <---- false type error */
         required='required'
       />
     </div>,
     document.getElementById('app')
   );

오류:

[tsserver 2741] Property 'optDefault' is missing in type '{ required: string; }' but required in type '{ optDefault: string; }'. [E]

제안된 또 다른 솔루션은 Javascript 자체의 기본 함수 매개 변수를 사용하는 것입니다.

type Props = {
  required: string,
  optDefault?: string
}

const MyComponent:  React.FC<Props> = ({
  required,
  optDefault='default'
}: Props) => (
  <ul>
    <li>required: {required}</li>
    <li>optDefault: {optDefault}</li>
  </ul>
)

ReactDOM.render(
  <div>
    <MyComponent
      required='required'
      optDefault='over written'
    />
    <MyComponent
      required='required'
    />
  </div>,
  document.getElementById('app')
);

그러나 이 솔루션의 문제는 기본값을 제공하는 것을 잊어버린 경우 런타임 버그가 발생한다는 것입니다.

const MyComponent: React.FC<Props> = ({
  required,
  optDefault //='optDefault' //<--- if you forgot to provide default
}: Props) => (
  <ul>
    <li>required: {required}</li>
    <li>optDefault: {optDefault}</li> {/* <-- result in bug */}
  </ul>
)

더 나은 해결책은 React를 사용하지 않는 것입니다.FC는 단순히 유형 스크립트 유형 추론에 의존합니다.

type Props = {
  required: string,
} & typeof defaultProps;

const defaultProps = {
  optDefault: 'optDefault'
};

const MyComponent = (props: Props) => (
  <ul>
    <li>required: {props.required}</li>
    <li>optDefault: {props.optDefault}</li>
  </ul>
)
MyComponent.defaultProps = defaultProps


ReactDOM.render(
  <div>
    <MyComponent
      required='required'
      optDefault='over written'
    />
    <MyComponent
      required='required'
    />
  </div>,
  document.getElementById('app')
);

당신은 이것을 당신의 구성요소 안에 넣을 수 있습니다.

static defaultProps: any;

나에게 가장 간단한 것은 defaultProps에서 (부분적인) 기본값을 직접 정의하는 것입니다.

export default class TSError extends React.Component<ITSErrorProps, {}> {
  private static defaultProps: Partial<ITSErrorProps> = {
    fullPage: true,
    controlClick: true,
    doubleClick: true
  };

...

}

언급URL : https://stackoverflow.com/questions/37262047/react-with-typescript-define-defaultprops-in-stateless-function

반응형