簡體   English   中英

我可以刪除反應中的道具嗎

[英]Can I delete props in react

我只想知道是否可以從組件中安全地刪除反應組件道具。

有沒有function之類的

this.destroyProps({someProp})

不,你不能。 react 組件的 props 是不可變的,不應被組件更改。

如果您需要在本地處理數據,您可以使用組件狀態,或者更好地創建 prop 數據的本地副本。

如果您將道具傳遞給子組件,您可以創建一個新對象,從中刪除屬性,然后傳遞給子組件。

const childProps = { ...this.props };
delete childProps.someProp;
return (
  <ChildComponent {...childProps} />
)

為什么不解構已刪除的道具,然后您可以使用其余的道具?

const {someProp, ...rest} = this.props;
return (
    <ChildComponent {...rest} />
);

但實際上,這里的問題是你為什么要傳入someProp開始。

Typescript 救援

使用Omit (在 TS 3.5 中添加)您可以擴展現有組件,刪除不需要的道具。

用法:

interface Original {
    foo: string;
    bar: number;
    baz: boolean;
}

// Omit a single property:
type OmitFoo = Omit<Original, "foo">; // Equivalent to: {bar: number, baz: boolean}

// Or, to omit multiple properties:
type OmitFooAndBar = Omit<Original, "foo" | "bar">; // Equivalent to: {baz: boolean}

我們可以結合OmitExtends來創建一個新的界面,我們可以添加額外的道具來喜歡這樣。

例子:

假設我們要基於 3rd 方庫中的按鈕組件創建一個按鈕組件,但刪除一些道具。

import {
  Button as ThirdPartyButton,
  ButtonProps as ThirdPartyButtonProps,
} from '<SOME-THIRD-PARTY-LIBRARY>';

export interface ButtonProps extends Omit<ThirdPartyButtonProps, 'someProperty'> {
  /**
   * The content of the component.
   */
  children: React.ReactNode;
}

/**
 * Button Component
 */
const Button = ({ children, ...otherProps }: ButtonProps): JSX.Element => (
  <ThirdPartyButton {...otherProps}>{children}</ThirdPartyButton>
);

export default Button;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM