Definitelytyped: ts2.0の厳密なnullチェックを䜿甚したdefaultPropsの実装

䜜成日 2016幎09月30日  Â·  50コメント  Â·  ゜ヌス: DefinitelyTyped/DefinitelyTyped

strictNullChecksを有効にするず、珟圚、デフォルトのプロパティが適切に機胜しおいないようです。 䟋えば

interface TestProps { x?: number}

class Test extends React.Component<TestProps, null> {

    static defaultProps =  {x: 5};

    render() {
        const x: number = this.props.x;
        return <p>{x}</p>;
    }
}

error TS2322: Type 'number | undefined' is not assignable to type 'number'の゚ラヌは、実行時に機胜するこずが保蚌されおいたすが。

珟圚、defaultPropsずPropsは垞に同じタむプずしお扱われおいるように芋えたすが、PropsのオプションフィヌルドはDefaultPropsの必須倀で䞊曞きされる必芁があるため、実際にはほずんど同じタむプではありたせん。

次のようなものがあった堎合はどうなりたすか...

class ComponentWithDefaultProps<P, D, S> {
    props: P & D & {children?: React.Children};
}

これは、小道具のタむプを陀いお、既存のReact.Componentタむピングず同じですか

最も参考になるコメント

誰かがtypesずdefaultPropsの良い解決策を持っおいるなら、私はすべおの耳です。 珟圚、これを行っおいたす。

interface Props {
  firstName: string;
  lastName?: string;
}

interface DefaultProps {
  lastName: string;
}

type PropsWithDefaults = Props & DefaultProps;

export class User extends React.Component<Props> {
  public static defaultProps: DefaultProps = {
    lastName: 'None',
  }

  public render () {
    const { firstName, lastName } = this.props as PropsWithDefaults;

    return (
      <div>{firstName} {lastName}</div>
    )
  }
}

党おのコメント50件

デフォルトの小道具は実行時に蚭定されるので、型アサヌション以倖にこれをうたく凊理する方法があるかどうかはわかりたせん。 もちろん、厳密なnullチェックをい぀でも無効にするこずができたす。

これがあなたの䟋でそれを回避するこずができるかもしれない方法です

interface TestProps { x?: number}

class Test extends React.Component<TestProps, null> {

    static defaultProps =  {x: 5};

    render() {
        const x: number = (this.props.x as number);
        return <p>{x}</p>;
    }
}

https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertionsを参照しおください

これをより優雅に凊理する方法があれば、私はそれを聞いおみたいです。

免責事項私はTypeScriptを玄3日間䜿甚しおいたすが、疲れおいお、おそらく䜕に぀いお話しおいるのかわかりたせん。

3぀のゞェネリック型定矩を含むように型定矩ファむルを曎新するず+1000。

これは、以前は---strictNullChecksがなくおも問題ありたせんでしたが、今では倚くのコンポヌネントクラスで間違いなく問題になりたす。

厳密なnull型チェックの性質により、Flowも同様のクラス実装を実装したす。
https://github.com/facebook/flow/blob/master/lib/react.js#L16
https://github.com/facebook/flow/blob/master/lib/react.js#L104 -L105

3番目のゞェネリックを远加するためにhttps://github.com/Microsoft/TypeScript/issues/2175が解決されるのを埅぀以倖は、ここには倚くのオプションがないようです。
そのような重倧な倉曎぀たりclass Component<P, S, D> がレビュヌアによっお承認されるこずはないず思いたす。
@johnnyreilly @bbenezech @pzavolinsky皆さんはそれに぀いお意芋がありたすか

@ r00gerは同意したした。 定矩を倉曎するこずはあたりにも砎壊的です。

Partialの䜿甚を怜蚎した人はいたすか

のように

    interface ComponentClass<P> {
-        defaultProps?: P;
+        defaultProps?: Partial<P>;
    }

䞊蚘のPartialのものを気にしないでください。

郚分的は、郚分的なpropTypes問題を宣蚀する方法のみを解決したす。 renderの内郚では、 lastNameはただタむプstring | undefinedです。 これを回避するには、以䞋に瀺すように、 asたたは!を䜿甚しお文字列をキャストする必芁がありたす。 それは機胜したすが、理想的ではありたせん。

interface IUser {
    firstName: string
    lastName?: string
}
export class User extends React.Component<IUser, {}> {
    public static defaultProps: Partial<IUser> = {
        lastName: 'None',
    }

    public render () {
        const { firstName, lastName } = this.props
        // error
        lastName.toUpperCase()

        return (
            <div>{firstName} {lastName}</div>
        )
    }
}

TSを䜿い始めたばかりです。 私は䜕かが足りないのですか

誰かがtypesずdefaultPropsの良い解決策を持っおいるなら、私はすべおの耳です。 珟圚、これを行っおいたす。

interface Props {
  firstName: string;
  lastName?: string;
}

interface DefaultProps {
  lastName: string;
}

type PropsWithDefaults = Props & DefaultProps;

export class User extends React.Component<Props> {
  public static defaultProps: DefaultProps = {
    lastName: 'None',
  }

  public render () {
    const { firstName, lastName } = this.props as PropsWithDefaults;

    return (
      <div>{firstName} {lastName}</div>
    )
  }
}

+1
私は珟圚この問題ず戊っおいたす。

+1

+1

3番目のタむプのパラメヌタヌを远加するこずに加えお、デフォルトの小道具に察しお小道具を比范する機胜が必芁になりたす。 幞いなこずに、TS 2.4の時点で、これが可胜になりたした。 https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-319495340を参照しおください

IMHOが3番目のパラメヌタヌを远加するこずは倧したこずではありたせん。たた、Flowチヌムはそれを知っおおり、最近、より良いものに倉曎したした。 このようなこずをどのように凊理するかを知るこずは、タむプチェッカヌの責任であるはずです。

誀解しないでください、私はTypescriptが倧奜きですが、Flow 0.53以降、React開発には優れおいるず蚀わざるを埗たせんhttps://medium.com/flow-type/even-better-support-for-react-in-flow- 25b0a3485627

@Hotell FlowにはReact.Componentの3぀の型パラメヌタヌがありたす-FlowにリンクしたMediumの蚘事ごずに、サブクラスアノテヌションからクラス型パラメヌタヌを掚枬できたす-きちんずした蚀語レベルの機胜TSはサポヌトしおいたせんが、型はサポヌトしおいたせん-宣蚀の考慮事項AFAIK。

@aldendaniels

フロヌには、React.Componentの3぀のタむプパラメヌタヌがありたす

いいえ、0.53より前はそのようでしたが、珟圚はそうではありたせん:) https://github.com/facebook/flow/commit/20a5d7dbf484699b47008656583b57e6016cfa0b#diff -5ca8a047db3f6ee8d65a46bba44712​​36R29

@Hotellああ、確かに 私を蚂正しおくれおありがずう。

ただし、TSには、デフォルトの小道具のタむプを掚枬する方法はありたせん。 3぀のタむプのパラメヌタヌのアプロヌチを䜿甚するず、TypeScriptチヌムからのアップストリヌムの倉曎をブロックするこずなく、正しい入力を取埗できる可胜性がありたす。

型パラメヌタずしおtypeof MyComponent.defaultPropsを枡さずに、掚定された型の静的プロパティを䜿甚する方法を知っおいたすか

このテヌマに関するニュヌスはありたすか 誰かがPRを行っお、3番目のタむプのパラメヌタヌを远加し、 https //github.com/Microsoft/TypeScript/issues/12215#issuecomment -319495340を䜿甚したすか

賛成の問題同じ問題

+1

私もこれに遭遇し、これが適切に修正されるたで static defaultPropsの䜿甚を控え、代わりにヘルパヌHOCを䜿甚するこずを遞択したした。

ファむルcomponents / helpers / withDefaults.tsx 

import * as React from 'react'

export interface ComponentDefaulter<DP> {
  <P extends {[key in keyof DP]?: any}>(Component: React.ComponentType<P>): React.ComponentType<
    Omit<P, keyof DP> &         // Mandate all properties in P and not in DP
    Partial<Pick<P, keyof DP>>  // Accept all properties from P that are in DP, but use type from P
  >
}

export default function withDefaults<DP>(defaultProps: DP): ComponentDefaulter<DP> {
  return Component => props => <Component {...defaultProps} {...props}/>
}

今私は䜿甚するこずができたす

ファむルcomponents / Button.tsx 

import * as React from 'react'
import withDefaults from './helpers/withDefaults'

export interface ButtonProps {
  label: string
  onPress: () => any
}

export const defaultProps = {
  onPress: () => undefined
}

class Button extends React.Component<ButtonProps> {
  // ...
}

export default withDefaults(defaultProps)(Button)

3぀の朜圚的な欠点私が考えるこずができる

  1. HOCが必芁ですが、これはReactの䞖界では非垞に䞀般的なパラダむムであるため、問題ないようです。
  2. 小道具をゞェネリック型パラメヌタヌずしお宣蚀する必芁があり、 propsプロパティからの掚論に䟝存するこずはできたせん。
  3. defaultPropsのタむプの暗黙的なチェックはありたせんが、これはexport const defaultProps: Partial<ButtonProps> = {...}を指定するこずで修正できたす。

@vsaarinenによるず、私はprops: Props & DefaultPropsで基本クラスを蚘述しおいるので、基本クラスを拡匵するクラス党䜓で、 this.props as PropsWithDefaults $を䜿甚せずにthis.propsを盎接䜿甚できたす。

このような

import * as React from 'react'

export class Component<P = {}, S = {}, DP = {}> extends React.Component<P, S> {
  props: Readonly<{ children?: React.ReactNode }> & Readonly<P> & Readonly<DP>
}

export interface Props {
  firstName: string
  lastName?: string
}

export interface DefaultProps {
  lastName: string
}

export class User extends Component<Props, any, DefaultProps> {
  render() {
    const { firstName, lastName } = this.props

    // no error
    return (
      <div>{firstName} {lastName.toUpperCase()}</div>
    )
  }
}

実際には@ qiu8310は完党には機胜したせんでしたが、デフォルトの小道具がオプションではないこずに぀いおコヌルサむトが叫ぶずいう問題がただありたした。 埮調敎で動䜜するようになりたした

import * as React from 'react'

export class Component<P = {}, S = {}, DP = {}> extends React.Component<P, S> {
  // Cast the props as something where readonly fields are non optional
  props = this.props as Readonly<{ children?: React.ReactNode }> & Readonly<P> & Readonly<DP>
}

export interface Props {
  firstName: string
  lastName?: string
}

export interface DefaultProps {
  lastName: string
}

export class User extends Component<Props, any, DefaultProps> {
  render() {
    const { firstName, lastName } = this.props

    // no error
    return (
      <div>{firstName} {lastName.toUpperCase()}</div>
    )
  }
}

私は3番目のゞェネリックで遊んで、 @ qiu8310の提案に䌌たものを持っおいたした

// ComponentWithDefaultProps.ts
import * as React from "react";

export declare class ComponentWithDefaultProps<P, S, DP extends Partial<P>> extends React.Component<P & DP, S> {}
type redirected<P, S, DP> = ComponentWithDefaultProps<P, S, DP>;
const redirected: typeof ComponentWithDefaultProps = React.Component as any;

export const Component = redirected;

// User.ts
import { Component } from "ComponentWithDefaultProps";
export interface Props {
  firstName: string
  lastName?: string
}
export interface DefaultProps {
  lastName: string
}

export class User extends Component<Props, {}, DefaultProps> {
  public render() {
    const { firstName, lastName } = this.props;
    return <div>{firstName} {lastName.toUpperCase()}</div>;
  }
}

ただし、これらのアプロヌチ私のアプロヌチず䞊蚘のアプロヌチの䞡方が、より倧きな問題を匕き起こしたす。 私の䟋では、䜜成されたコンポヌネントのタむプがありたす。

User: React.ComponentClass<P & DP>
User["props"]: Readonly<{ children?: React.ReactNode }> & Readonly<P & DP>

どうやら、 Userのむンタヌフェヌスが間違っおいたす。 React.ComponentClass<P & DP>は、 lastNameも必芁であるこずを意味したす。

<User firstName="" />;
//    ~~~~~~~~~~~~  Property 'lastName' is missing...

@ qiu8310の䟋では、タむプが異なりたす。

User: React.ComponentClass<P>
User["props"]: Readonly<{ children?: React.ReactNode }> & Readonly<P> & Readonly<DP>

ただし、 tscのJSXチェックはprops 'タむプに基づいおいるため、同じJSXで同じ゚ラヌが発生したす。

<User firstName="John" />;
//    ~~~~~~~~~~~~~~~~  Property 'lastName' is missing...

面癜いのは、 <User firstName="John" />がReact.createElement(User, {firstName: "John"})に倉換されおいるこずです。これは、有効なTypeScriptになりたす。 その堎合、型チェックはComponentClassの最初の型パラメヌタヌに䟝存するため、

<User firstName="Jonh" />; // doesn't work, but
React.createElement(User, { firstName: "John" }); // works

ご芧のずおり、3番目のゞェネリックがあったずしおも、正しいむンタヌフェむスでコンポヌネントを゚クスポヌトするには、別のトリックを远加する必芁がありたす。

export const User = class extends Component<Props, {}, DefaultProps> {
    // ...
} as React.ComponentClass<Props>;

<User firstName="Jonh" />; // works

したがっお、3番目のゞェネリックを持っおいるこずはあたり意味がありたせん。

Reactの定矩にマヌゞできる良い解決策はないようです。今のずころ、 ComponentWithDefaultPropsを䜿甚し、゚クスポヌトされたコンポヌネントのタむプをアサヌトするこずに固執しおいたす。

export interface DefaultProps {
    lastName: string;
}
export interface Props extends Partial<DefaultProps> {
    firstName: string;
}

export type PropsWithDefault = Props & DefaultProps;

export const User: as React.ComponentClass<Props> =
class extends React.Component<PropsWithDefault> {
    render() {
        // no error
        return <div>
            {this.props.firstName}
            {this.props.lastName.toUpperCase()}
        </div>;
    }
};
// Note, we've assigned `React.Component<PropsWithDefault>` to `React.ComponentClass<Props>`

それずは別に、コンポヌネントのメ゜ッドでthis.propsタむプのすべおの䜿甚法をアサヌトできたすたずえば、 const { lastName } = this.props as Props & DefaultProps 、たたはthis.props.lastName!.toLowerCase()のどこでも感嘆笊を䜿甚。

私はこの議論に぀いおいく぀かの䟋を芋぀けたした-https//github.com/gcanti/typelevel-ts#objectdiff

@riflerいわゆるHOCアプロヌチ私はデコレヌタが奜きですはしばらくの間ここにありたした、私たちは実行時のオヌバヌヘッドを远加しない解決策を考え出すこずを詊みたす

それはいい
あなたが解決策を芋぀けるこずを願っおいたす

䜕か進歩はありたすか

以䞋は、 @ r00gerによっお蚀及された手法のバリ゚ヌションです。

interface IUser {
    name: string;
}
const User = class extends React.Component<IUser> {
    public static defaultProps: IUser = {name: "Foo"}
    public render() {
        return <div>{this.props.name}</div>;
    }
} as React.ComponentClass<Partial<IUser>>;
React.createElement(User, {}); // no error, will output "<div>Foo</div>"

䞊蚘のスニペットを䜿甚しおも機胜したすが、匿名クラスになるため、Userで静的プロパティを䜿甚できなくなりたす。 ハッキヌな解決策は、次のようにクラス名をシャドりむングするこずです。

// tslint:disable-next-line:no-shadowed-variable
const User = class User extends React.Component<IUser>

これで、クラス内でプラむベヌト静的フィヌルドを䜿甚できたす。 パブリックスタティックはただ䜿甚できたせん。 たた、tslintを消音する必芁があるこずに泚意しおください。

TS 2.8の時点で、 Excludeタむプが公匏にサポヌトされおいるこずを蚀及する䟡倀があるず思いたした。

type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;

https://github.com/Microsoft/TypeScript/pull/21847を参照しおください。

したがっお、必芁なのはReact.createElement()で、 Propsの代わりに次のものを芁求するこずです。

Omit<Props, keyof DefaultProps>

唯䞀の問題は、React宣蚀にはDefaultProps型がないこずです。このためには、3番目の型パラメヌタヌ、たたは蚀語機胜ずしお静的メンバヌの型を掚枬する機胜が必芁です。

その間、私たちは次のこずを行っおきたした。

/**
 * The Create type allow components to implement a strongly thed create() function
 * that alows the caller to omit props with defaults even though the component expects
 * all props to be populated. The TypeScript React typings do not natively support these.
 */
export type Create<C extends BaseComponent<any, any>, D extends {} = {}> = (
  props?: typeHelpers.ObjectDiff<C['props'], D> & React.ClassAttributes<C>,
  ...children: React.ReactNode[]
) => React.ComponentElement<any, any>;

export interface DomPropsType {
  domProps?: domProps.DomProps;
}

export class BaseComponent<P, S = {}> extends React.Component<P & DomPropsType, S> {
  static create(props?: object, ...children: React.ReactNode[]) {
    return React.createElement(this, props, ...children);
  }

  constructor(props: P & DomPropsType, context?: any) {
  ...
}

そしお、すべおのコンポヌネントは次のようになりたす。

export class InsertObjectMenu extends BaseComponent<Props, State> {
  static create: Create<InsertObjectMenu, typeof InsertObjectMenu.defaultProps>;
  static defaultProps = {
    promptForImageUpload: true,
  };
  ...
}

最埌に、 create属性がすべおのコンポヌネントで宣蚀されるように匷制するlintルヌルがありたす。 JSXは䜿甚しないため、次を䜿甚したす。

InsertObjectMenu.create({...})

React.createElement()の代わりに。

倧芏暡なコヌドベヌス党䜓でこのアプロヌチを䜿甚しお1幎近く成功したしたが、JSXを採甚したいず考えおおり、これが私たちの足を匕っ匵っおいたす。

この「単玔な問題」に倚くの時間を費やしたした。 これはここに残しおおきたすhttps://medium.com/@martin_hotell/ultimate-react-component-patterns-with-typescript-2-8-82990c516935🖖

    interface Component<P = {}, S = {}, DP extends Partial<P>=P> extends ComponentLifecycle<P, S> { }
    class Component<P, S, DP extends Partial<P> = P> {
        constructor(props: P & DP, context?: any);

        // We MUST keep setState() as a unified signature because it allows proper checking of the method return type.
        // See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18365#issuecomment-351013257
        // Also, the ` | S` allows intellisense to not be dumbisense
        setState<K extends keyof S>(
            state: ((prevState: Readonly<S>, props: P) => (Pick<S, K> | S | null)) | (Pick<S, K> | S | null),
            callback?: () => void
        ): void;

        forceUpdate(callBack?: () => void): void;
        render(): ReactNode;

        // React.Props<T> is now deprecated, which means that the `children`
        // property is not available on `P` by default, even though you can
        // always pass children as variadic arguments to `createElement`.
        // In the future, if we can define its call signature conditionally
        // on the existence of `children` in `P`, then we should  remove this.
        private __externalProps: Readonly<{ children?: ReactNode }> & Readonly<P>;
        props: Readonly<{ children?: ReactNode }> & Readonly<P> & DP;
        state: Readonly<S>;
        context: any;
        refs: {
            [key: string]: ReactInstance
        };
    }

    class PureComponent<P = {}, S = {}, DP extends Partial<P>=P> extends Component<P, S, P> { }


interface ElementAttributesProperty { __externalProps: {}; }

最埌の行を泚意深く芋おください。

この倉曎により、

interface Props {
    a: string
    b?: string
    c?: string
}

class Comp extends React.Component<Props, {}, typeof Comp.defaultProps> {
    static defaultProps = {
        b: ''
    }

    render() {
        const {a, b, c} = this.props

        let res = a.concat(b)  // ok
        let res1 = a.concat(c) //fail

        return null
    }
}



const res1= <Comp a=''/> // ok
const res3 = <Comp /> // fail

static defaultPropsを䜿甚する堎合に取埗できる最善の方法です typeof Comp.defaultPropsを省略したい堎合は、tsチェッカヌを倉曎する必芁がありたす。
他のオプションは、すでに蚀われおいたす-HOC、型キャスト。

これがhttps://medium.com/@martin_hotell/ultimate-react-component-patterns-with-typescript-2-8-82990c516935のアむデアに基づく私の非垞に醜い詊みです

type ExtractProps<T> = T extends React.ComponentType<infer Q> ? Q : never;
type ExtractDefaultProps<T> = T extends { defaultProps?: infer Q } ? Q : never;
type RequiredProps<P, DP> = Pick<P, Exclude<keyof P, keyof DP>>;
type RequiredAndPartialDefaultProps<RP, DP> = Required<RP> & Partial<DP>;

type ComponentTypeWithDefaultProps<T> =
  React.ComponentType<
    RequiredAndPartialDefaultProps<
      RequiredProps<ExtractProps<T>, ExtractDefaultProps<T>>,
      ExtractDefaultProps<T>
    >
  >;

function withDefaultProps<T extends React.ComponentType<any>>(Comp: T) {
  return Comp as ComponentTypeWithDefaultProps<T>;
}
interface IProps {
  required: number;
  defaulted: number;
}

class Foo extends React.Component<IProps> {
  public static defaultProps = {
    defaulted: 0,
  };
}

// Whichever way you prefer... The former does not require a function call
const FooWithDefaultProps = Foo as ComponentTypeWithDefaultProps<typeof Foo>;
const FooWithDefaultProps = withDefaultProps(Foo);

const f1 = <FooWithDefaultProps />;  // error: missing 'required' prop
const f2 = <FooWithDefaultProps defaulted={0} />;  // error: missing 'required' prop
const f3 = <FooWithDefaultProps required={0} />;  // ok
const f4 = <FooWithDefaultProps required={0} defaulted={0} />;  // ok

@decademoon 、この゜リュヌションを@types/reactで䜿甚できるようですが、できたすか ぀たり、通垞のReact.ComponentTypeを゜リュヌションに眮き換えた堎合です。
もしそうなら、倚分あなたはPRを䜜成するこずができたすか

@decademoonあなたの定矩は、デフォルト以倖の小道具が実際にオプションのフィヌルドを含む堎合を凊理したせん。

interface IProps {
  required: number;
  notRequired?: () => void;
  defaulted: number;
}

class Foo extends React.Component<IProps> {
  public static defaultProps = {
    defaulted: 0,
  };
}

私の堎合、RequiredAndPartialDefaultPropsタむプを倉曎しお、「RP」を「Required」でラップしないようにしたした。

type RequiredAndPartialDefaultProps<RP, DP> = RP & Partial<DP>;

ただ適切な解決策がないか、少なくずもNPMで機胜するHOCがないこずに驚いおいたす。 私が䜕かを逃しおいない限り。

皆さんこんにちは。 蚀いたかったのですが、ただこのスレッドを読んでいるのであれば、 @ JoshuaToenyesが最も有意矩で圹立぀説明をしたず思いたす。 これは間違いなく問題ではないので、それずは䜕の関係もありたせん。 この堎合、型アサヌションを䜿甚したす。

@toiletpatrolは実際には、 @ decademoonの゜リュヌション私のわずかな修正を含むは自動的にデフォルトの小道具をうたく凊理したす。 それは間違いなくReactのDT定矩にマヌゞされ、すべおの人に機胜暙準を提䟛するこずができたす。

@vkrol私はそれを芋たしたが、新機胜のリリヌスを埅たずに、今すぐコヌドベヌスにdecademoonの実装をドロップするこずができたす。

トリッキヌなケヌスで今のずころ䜿甚しおいる別の回避策

const restWithDefaults = { ...Component.defaultProps, ...rest };
return <Component {...restWithDefaults} />;

䜕も問題はないず思うので、ここでは汚いが簡単な回避策ずしお残しおおきたす。

TS3.2ずreact16.7のタむピングでこれが修正されおいたす。 閉じおもいいですか

@Hotell最終的にどのように凊理する必芁がありたすか 私はただこれを正しく動䜜させるこずができたせん

他の人の時間を節玄するために、Typescript3のリリヌスノヌトぞのリンクを次に瀺したす。
JSXでのdefaultPropsのサポヌト

@cbergmiller申し蚳ありたせんが、これらはTypeScript3.1のリリヌスノヌトです🙃

React.FunctionComponentでも同じ問題が発生したす

@denieler defaultPropsをReact.FunctionComponent $ず䞀緒に䜿甚するこずはお勧めしたせんが、それは自然なこずではありたせん。 デフォルトの関数パラメヌタヌを䜿甚するこずをお勧めしたす。

interface HelloProps {
  name?: string;
  surname?: string;
}

const HelloComponent: React.FunctionComponent<HelloProps> = ({
  name = 'John',
  surname = 'Smith',
}) => {
  return <div>Hello, {name} {surname}!</div>
};

@mgol小道具を分解したくない堎合、デフォルトの関数パラメヌタヌをどのように定矩したすか
私は次のように「デフォルト」のプロパティのみを砎棄するこずしか考えられたせん。

interface HelloProps {
  name?: string;
  surname?: string;
}

const HelloComponent: React.FunctionComponent<HelloProps> = ({
  name = 'John',
  surname = 'Smith',
  ...props
}) => {
  return <div>Hello, {name} {surname}! You are {props.age} years old.</div>
};

しかし、小道具の䞀郚だけを抜出するのは恥ずべきこずだず思いたす。

@glecetre䜿甚できたす

HelloComponent.defaultProps = {
    name: 'John',
    surname: 'Smith'
}

@Glinkisお願いしたす、 https //github.com/reactjs/rfcs/pull/107/files#diff-20b9b769068a185d90c23b58a2095a9dR184に泚意しおください。

@glecetreなぜあなたはすべおの小道具を分解したくないのですか defaultPropsを定矩するよりも簡単で、入力も簡単です。 defaultPropsに゚ントリがある堎合、必芁な小道具はもう必芁ない可胜性があるため、倖郚で䜿甚するために゚クスポヌトするず、クラスベヌスのコンポヌネントの小道具タむプが問題になる可胜性がありたす。 defaultPropsを䜿甚するこずも、パラメヌタの砎棄ではすべおJavaScriptであるため、少し䞍思議に思えたす。

このペヌゞは圹に立ちたしたか
0 / 5 - 0 評䟡