简体   繁体   中英

Can I delete props in react

I just want to know is it possible to delete react component props safely from the component.

Is there any function like

this.destroyProps({someProp})

No, you can't. The props of a react component are immutable and are not supposed to be changed by the component.

If you need to work with the data locally, you could use the state of the component , or better create a local copy of the prop data.

If you were passing the props onto a child component, you could create a new object, delete the properties from that and then pass to the child.

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

Why not just deconstruct the deleted prop out and then you can use the rest?

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

But really, the question here is why you're passing in the someProp to begin with.

Typescript to the rescue

Using Omit (which was added in TS 3.5) you could extend your existing component removing the undesired props.

Usage:

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}

We can combine Omit with Extends to create a new interface we can add our additional props to like so.

Example:

say we want to create a button component based on the button component from a 3rd party library but remove some of the props.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM