2024-06-20 06:07PM
解构赋值是JavaScript中一种语法特性,解构赋值允许我们从数组或对象中提取值,并将这些值赋给变量。
1.数组解构:
let [a, b, c] = [1, 2, 3]
console.log(a, b, c);
// 输出:1 2 3
2.对象解构:
let { name, age } = { name: 'John', age: 30 };
console.log(name, age);
// 输出 'John' 303.解构赋值的实例:
src/pages/FormComponent.jsx 文件代码内容如下:
import React from 'react';
const inputOptions = [ 
  { id: 1, label: '名字', name: 'name' },
  { id: 2, label: '邮箱', name: 'email' },
  { id: 3, label: '密码', name: 'password' },
];
const title = "信息表单";
export default function FormComponent() {
  console.info("===inputOptions:", inputOptions)
  return (
    <>  
      <h2>{title}</h2>
      <form>
        // 使用 inputOptions 数组,遍历每个选项,渲染一个 <div> 元素,包含一个 <label> 和一个 <input> 元素。这里使用了解构赋值,从每个 option 对象中提取 id、label 和 name 属性
        {inputOptions.map((option) => (
          <div key={option.id}>
            <label htmlFor={option.id}>{option.label}</label>
            <input type="text" id={option.id} name={option.name} />
          </div>
        ))} 
      </form>
    </> 
  );  
}
页面展示情况如下:

4.解构赋值的好处:
1)可以使代码更简洁;
2)可以是代码更容易理解;
3)当属性不存在时,可以为变量设置默认值;
4)可以为变量设置别名,以适应不同的命名需求;
5)可以对嵌套的数据结构进行结构赋值;
登录
请登录后再发表评论。
评论列表:
目前还没有人发表评论