这在javascript里叫什么?({name, value}) =>& lt; span> & lt; / span>

What is this called in javascript? ({name, value}) => <span></span>

本文关键字:lt span value javascript 什么 name 这在      更新时间:2023-09-26

(in javascript)在这方面:const component = ({ name, value }) => <span></span>

箭头函数的第一个参数与它的成员分开。props => ({ name, value })

这叫什么?我看到有些人用babel做这个,但不知道正确的术语是什么。

箭头函数的第一个参数与它的成员分开。props => ({ name, value })……这叫什么?

它被称为参数解构(有时参数解构,重要的是解构部分)。传递给函数的是一个对象,但是函数接收到的是对象的属性。也就是说,它们已经从结构(对象)中取出,并被制成不同的东西(因此,"解构"):

const adams = ({question, answer}) => {
  console.log(question);
  console.log(answer);
};
adams({question: "Life, the Unverse, and Everything!", answer: 42});

JavaScript在一些地方有解构,包括上面的函数参数列表。您也可以使用赋值:

const o = {question: "Life, the Unverse, and Everything!", answer: 42};
const {answer, question} = o;
console.log(question);
console.log(answer);


在ES2018和以后的版本中有一个相关的特性(但它已经在JSX代码中通过转换支持了多年):能够将属性的"剩余"作为对象:

// ES2018+
const adams = ({question, answer, ...rest}) => {
  console.log(question);
  console.log(answer);
  console.log(rest);
};
adams({
  question: "Life, the Unverse, and Everything!",
  answer: 42,
  legend: true,
  missed: true
});

参数列表中{}中的...rest创建了一个具有"剩余"属性(未作为离散参数捕获的那些)的对象。它是JavaScript的"rest参数"的解构版本。你也可以在赋值中这样做:

// ES2018+
const o = {
  question: "Life, the Unverse, and Everything!",
  answer: 42,
  legend: true,
  missed: true
};
const {question, answer, ...rest} = o;
console.log(question);
console.log(answer);
console.log(rest);

ES2015规范为数组添加了它,ES2018为对象属性添加了它。

这叫做解构。下面是一个关于它如何工作和如何使用的示例:

const employeeOne = { name: 'John', phone: '555-5555', age: 27 };
const { name, phone, age: john_age } = employeeOne;
console.log(name); // 'John'
console.log(phone); // '555-5555'
console.log(john_age); // '27'
sayHi = ({ name }) => console.log(`Hello ${name}, how are you?`);
sayHi(employeeOne); //'Hello John, how are you?'