简体   繁体   English

从 React 中的 ...this.props 中删除 prop

[英]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.我正在寻找的是一种在将...this.props传递给另一个 React 组件之前删除道具的快速方法。 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?是否可以在仍在使用...this.props同时删除该道具,还是必须单独发送每个道具?

You should be able to use the rest operator with destructuring to achieve the desired result as follows:您应该能够使用带有解构的 rest 运算符来实现所需的结果,如下所示:

 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:此时,您可以将newProps到返回的组件中:

<MyComponent {...newProps} />

A simple solution would be to use rest destructuring syntax like so:一个简单的解决方案是使用rest解构语法,如下所示:

 /* 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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