programing

상태 비저장, 기능성 React 컴포넌트용 TypeScript 기본 소품(옵션)을 지정하는 방법

fastcode 2023. 4. 5. 22:20
반응형

상태 비저장, 기능성 React 컴포넌트용 TypeScript 기본 소품(옵션)을 지정하는 방법

(React Native 프로젝트의 경우) Typescript에 옵션 소품 및 defaultProps를 사용하여 상태 비저장 React 구성 요소를 생성하려고 합니다.이것은 바닐라 JS에서는 사소한 일이지만, TypeScript에서는 어떻게 해야 할지 막막합니다.

다음 코드 포함:

import React, { Component } from 'react';
import { Text } from 'react-native';

interface TestProps {
    title?: string,
    name?: string
}

const defaultProps: TestProps = {
    title: 'Mr',
    name: 'McGee'
}

const Test = (props = defaultProps) => (
    <Text>
        {props.title} {props.name}
    </Text>
);

export default Test;

부르기<Test title="Sir" name="Lancelot" />예상대로 랜슬롯 경을 표현하지만<Test />"Mr McGee"를 출력할 때 아무 결과도 나오지 않습니다.

어떤 도움이라도 대단히 감사합니다.

다음은 TypeScript로 대응 - 스테이트리스 함수로 defaultProps를 정의하는 것과 같은 질문입니다.

import React, { Component } from 'react';
import { Text } from 'react-native';

interface TestProps {
    title?: string,
    name?: string
}

const defaultProps: TestProps = {
    title: 'Mr',
    name: 'McGee'
}

const Test: React.SFC<TestProps> = (props) => (
    <Text>
        {props.title} {props.name}
    </Text>
);

Test.defaultProps = defaultProps;

export default Test;

가장 쉬운 방법은 선택적 인수를 사용하는 것입니다.default Props는 기능 컴포넌트에서는 사용되지 않습니다.

예:

interface TestProps {
    title?: string;
    name?: string;
}

const Test = ({title = 'Mr', name = 'McGee'}: TestProps) => {
    return (
        <p>
            {title} {name}
        </p>
    );
}

제가 좋아하는 방법은 다음과 같습니다.

type TestProps = { foo: Foo } & DefaultProps
type DefaultProps = Partial<typeof defaultProps>
const defaultProps = {
  title: 'Mr',
  name: 'McGee'
}

const Test = (props: Props) => {
  props = {...defaultProps, ...props}
  return (
    <Text>
      {props.title} {props.name}
    </Text>
  )
}

export default Test

업데이트 2022

기능 컴포넌트의 경우 실제로 다음과 같은 기능이 저하될 수 있습니다.defaultProps필드입니다. 이미 작성된 코드의 양으로 인해 이렇게 빨리 발생하지는 않을 것입니다. 하지만 콘솔에 경고가 표시될 가능성이 매우 높습니다.

올바른 동작과 적절한 TypeScript 검증을 제공하는 다음 솔루션을 사용하고 있습니다.정의된 속성과 정의되지 않은 속성이 혼재된 경우 및 기본값을 사용하거나 사용하지 않는 속성과 함께 작동합니다. 즉, 다음과 같은 모든 경우를 다룹니다.

interface Props {
  name: string;
  surname?: string;
  age?: number;
}

const defaultProps = {
  surname: 'Doe',
};

function MyComponent(propsIn: Props) {
  const props = {...defaultProps, ...propsIn};

  return <div>{props.surname}</div>;
}

VSCode 자동 완성 기능은 다음과 같습니다.

VSCode 자동 완성

TypeScript 4.7에서 테스트되었습니다.

냄비에 제 솔루션을 추가하면 기존 솔루션에 가독성과 우아함이 더해진다고 생각합니다.

컴포넌트가 있다고 칩시다.MyComponent필수 소품과 옵션 소품을 혼합하여 제공합니다.이러한 필수 소품 및 옵션 소품을 2개의 인터페이스로 분리하여 컴포넌트의 완전한 프로펠러 인터페이스를 위해 조합할 수 있습니다.단, 옵션 소품만을 사용하여 기본 소품을 설정할 수 있습니다.

import * as React from "react";

// Required props
interface IMyComponentRequiredProps {
  title: string;
}

// Optional props
interface IMyComponentOptionalProps {
  color: string;
  fontSize: number;
}

// Combine required and optional props to build the full prop interface
interface IMyComponentProps
  extends IMyComponentRequiredProps,
    IMyComponentOptionalProps {}

// Use the optional prop interface to define the default props
const defaultProps: IMyComponentOptionalProps = {
  color: "red",
  fontSize: 40,
};

// Use the full props within the actual component
const MyComponent = (props: IMyComponentProps) => {
  const { title, color, fontSize } = props;
  return <h1 style={{ color, fontSize }}>{title}</h1>;
};

// Be sure to set the default props
MyComponent.defaultProps = defaultProps;

export default MyComponent;

제가 틀릴 수도 있지만, 두 번째 투표 응답에 따라 함수에 기본 프로펠러 값을 전달하면 미묘한 버그나 use Effects가 발생할 수 있습니다(응답할 수 있는 담당자가 부족하기 때문에 여기 재현 가능한 codesanbox가 있습니다).

비록 이것이 정말 의도적인 예이고, 아마도 대부분의 경우 단지 나쁜 컴포넌트 설계일지라도, 저는 이것을 한 번 이상 본 적이 있습니다. 심지어 페이지 전체를 부수기도 합니다.

제가 보기엔 이건 활자 문제처럼 보이지 않습니다.

면책사항: 나는 이것을 타자기로만 시도했다.

하지만, 문제는 소품들이 항상 존재한다는 것입니다(아무것도 전달되지 않은 빈 물체라도).단, 여기에는 2가지 회피책이 있습니다.

번째 클린 되지만 이 명령어는 defaultProps★★★★★★★★★★★★★★★★★★.

interface TestProps {
    title?: string;
    name?: string;
}

const defaultProps: TestProps = {
    title: 'Mr',
    name: 'McGee'
}

const Test = (passedIn: TestProps) => {
    const props = Object.assign({}, defaultProps, passedIn);
    return (
        <p>
            {props.title} {props.name}
        </p>
    );
}

많은 소품을 가지고 있으면 조금 복잡해질 수 있지만, 원래의 구문을 유지할 수 있는 또 다른 방법은 다음과 같습니다.

const Test = (props: TestProps) => (
    <Text>
        {props.title || 'Mr'} {props.name || 'McGee'}
    </Text>
);

이게 도움이 됐으면 좋겠네요!

언급URL : https://stackoverflow.com/questions/40209352/how-to-specify-optional-default-props-with-typescript-for-stateless-functiona

반응형