本文介绍了难以理解JSX传播算子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从React文档中获得以下示例代码:

Given this example code from the React docs:

var props = {};
props.foo = x;
props.bar = y;
var component = <Component {...props} />;

我仔细研究了...props的实际计算结果,这是这样的:

I did some looking into what ...props actually evaluates to, which is this:

React.__spread({}, props)

反过来求值为{foo: x, bar: y}.

但是我想知道的是,为什么我不能这样做:

But what I'm wondering is, why can't I just do this:

var component = <Component props />;

我看不出点差运算符的含义是什么.

I don't see understand what the point of the spread operator is.

推荐答案

这有助于使代码更简洁-由于props是对象,所以散布运算符采用您所对象的 properties 传入并将它们应用于组件.因此,该组件将具有值为xfoo和值为ybar属性.

This helps make your code more succinct - since props is an object, the spread operator takes the properties of the object you pass in and applied them to the component. So the Component will have properties a foo with a value of x and a bar with a value of y.

它与以下内容相同:

var component = <Component foo={props.foo} bar={props.bar} />;

短些

这篇关于难以理解JSX传播算子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 09:44