【问题标题】:When declaring a function component with ReactJS使用 ReactJS 声明函数组件时
【发布时间】:2020-12-09 07:04:31
【问题描述】:

所以我看到人们使用不同的方式来声明一个函数。但是,我看到了一种我不太理解的方式。示例代码如下:

type Props = { 
    name: string,
    age: number
}

const someFunction = ({
    name,
    age
}: Props) => {
   return (
    // Do something here
   )
}

所以我知道这里的代码首先是创建一个带有名称和年龄的 Props 对象。我没有得到的部分是它显示({name, age}: Props) 的部分。我猜这是一个将状态映射到道具的参数,但我不确定。谁能解释一下?

【问题讨论】:

标签: reactjs typescript react-props react-state react-functional-component


【解决方案1】:

它被称为Destructuring Assignment。这是一种 ES6 语法。

它存在于arraysobjects

它基本上是一种提取数组/对象的一部分的方法。

在执行{ name, age } = props 时,您从通常称为props 的对象中提取 nameage

使用解构:

const someFunction = ({
    name,
    age
}: Props) => {
  console.log(name, age)
}

没有解构:

const someFunction = (props: Props) => {
  const name = props.name
  const age = props.age

  console.log(name, age)  
}

【讨论】:

  • 所以如果我有类似 ({"Andy", 10}: Props) 的东西,它会将它传递给 name = "Andy", age = 10?
  • 我编辑了示例。这不是一种分配值的方法,它只是一种捷径,以避免像const name = props.name那样重复自己。你可以简单地说:const { name } = props.
  • 现在说得通了。非常感谢
猜你喜欢
  • 2019-12-05
  • 2020-12-29
  • 2018-04-18
  • 2019-10-26
  • 1970-01-01
  • 2014-11-29
  • 2018-04-23
  • 2021-09-19
  • 2015-07-29
相关资源
最近更新 更多