简体   繁体   English

支持 React 中的 Class 变量解构

[英]Prop to Class Variable Destructuring in React

Is there a way to break down a prop object and assign them to a variable of the same name in the class?有没有办法分解道具 object 并将它们分配给 class 中的同名变量?

I know about我知道

({ first: this.first, second: this.second, } = props)

but you still have to specify what goes where.但你仍然必须指定什么去哪里。 This gets messy with many variables.这会因许多变量而变得混乱。

I tried using我尝试使用

Object.assign(this, props);

but can't get it to work in the way I described.但不能让它按照我描述的方式工作。

I just think that doing something like:我只是认为做类似的事情:

this.first = props.first;
this.second = props.second;
...

is very cumbersome.很麻烦。

Unfortunately, your Object.assign(this, props);不幸的是,你的Object.assign(this, props); is about as automatic as it gets in JavaScript (and even in TypeScript; for now, you can't use destructuring with automatic initialization).与它在 JavaScript 中一样自动(甚至在 TypeScript 中;现在,您不能将解构与自动初始化一起使用)。

Mostly you don't want to do that with props anyway, see under the line below, but sticking to the question asked:大多数情况下,无论如何你都不想用道具来做到这一点,请参阅下面的行,但坚持提出的问题:

You could use an array with the names of the props, probably with a reusable utility function, for instance:您可以使用带有道具名称的数组,可能带有可重复使用的实用程序 function,例如:

constructor(props) {
    super(props);
    grab(["first", "second"], this, props);
}

where grab is grab在哪里

function grab(names, target, source) {
    for (const name of names) {
        target[name] = source[name];
    }
    return target;
}

But mixing string literals with property literals like that can give you a bit of hassle when using refactoring tools that might miss them.但是,在使用可能会遗漏它们的重构工具时,将字符串文字与属性文字混合在一起会给您带来一些麻烦。


However , assigning props to instance properties is fairly unusual vs. simply using them from this.props (which is set up by React.Component 's constructor), perhaps via destructuring in the method where you want to use them:然而,将 props 分配给实例属性与简单地从this.props (由React.Component的构造函数设置)使用它们相比是相当不寻常的,也许是通过在你想使用它们的方法中解构:

render() {
    const {first, second} = this.props;
    return /*... JSX using `first` and `second` ... */;
}

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

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