简体   繁体   中英

Remove prop from ...this.props in React

What I am looking for is a quick way to remove a prop before passing ...this.props to another React Component. Currently I have a Higher Order Component that performs some logic and then passes all its props to another component, but the next component doesn't need one of the props. Is it possible to remove that prop while still using ...this.props or do I have to send each prop individually?

You should be able to use the rest operator with destructuring to achieve the desired result as follows:

 const props = { a: 1, b: 2, c: 3 } // We want newProps without b const { b, ...newProps } = props; console.log(newProps);

Alternatively, you can copy the object and delete the undesired prop from the new object.

 const props = { a: 1, b: 2, c: 3 } const newProps = { ...props }; delete newProps.b; console.log(newProps);

At this point, you can spread your newProps into the returned component:

<MyComponent {...newProps} />

A simple solution would be to use rest destructuring syntax like so:

 /* Full set of input props, with "dontWant" that you would like to exclude */ const props = { dontWant : true, keep : 1, keepAlso : 2 } /* Obtain filteredProps, which contains all of props without the dontWant prop */ const { dontWant, ...filteredProps } = props console.log("Original props:", props) console.log("Filtered props to use:", filteredProps)

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