[英]Can I delete props in react
我只想知道是否可以從組件中安全地刪除反應組件道具。
有沒有function之類的
this.destroyProps({someProp})
如果您將道具傳遞給子組件,您可以創建一個新對象,從中刪除屬性,然后傳遞給子組件。
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}
我們可以結合Omit和Extends來創建一個新的界面,我們可以添加額外的道具來喜歡這樣。
例子:
假設我們要基於 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.