简体   繁体   English

我可以删除反应中的道具吗

[英]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有没有function之类的

this.destroyProps({someProp}) 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. react 组件的 props 是不可变的,不应被组件更改。

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.如果您需要在本地处理数据,您可以使用组件状态,或者更好地创建 prop 数据的本地副本。

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.但实际上,这里的问题是你为什么要传入someProp开始。

Typescript to the rescue Typescript 救援

Using Omit (which was added in TS 3.5) you could extend your existing component removing the undesired props.使用Omit (在 TS 3.5 中添加)您可以扩展现有组件,删除不需要的道具。

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.我们可以结合OmitExtends来创建一个新的界面,我们可以添加额外的道具来喜欢这样。

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.假设我们要基于 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