【问题标题】:how to use destructuring in react components如何在反应组件中使用解构
【发布时间】:2017-11-30 08:08:19
【问题描述】:

我在网上做了很多阅读,只是无法在脑海中解构,好吧。

//before destructuring
function me(details){
  console.log('My name is ' + details.name + ' and I work for ' + details.company);
}
//after destructuring
function me({ name, company }){
  console.log('my name is ' + name + ' and i work for ' + company);
}

me({
  name: 'Rich',
  age: 34,
  city: 'London',
  company: 'Google'
})

我已经写了这个,这很有意义,但我没有得到的一件事是反应中的以下内容。

如果你这样做:

export default ({ name }) => <h1>Hello {name}!</h1>;

<Hello name="CodeSandbox" />

为什么我不能这样做:

export default ( name ) => <h1>Hello {name}!</h1>;

去掉函数参数中的{}

如果有人看到我做错了什么,请他们解释一下吗?

我习惯了这样的功能:

functionA (a) => { // do something with the parameter a }

不确定参数内的卷曲{}

【问题讨论】:

  • 因为 react 将 props 对象传递给组件 - { name: "asdf" }。要获得名称,您需要对其进行解构。
  • 因为 <Hello name="CodeSandbox" /> 被传递给函数类似于 yourFunction({name:"CodeSandbox" })

标签: javascript reactjs ecmascript-6 destructuring


【解决方案1】:
export default (name) => <h1>Hello {name}!</h1>;

不会起作用,因为对于任何组件,只有一个参数是 props

所以你可以写成最长的形式

export default (props) => {
  return <h1>Hello {props.name}!</h1>;
}

可以缩短(使用解构)为:

export default (props) => {
  const {name} = props; // Extract name from props using destructuring
  return <h1>Hello {name}!</h1>;
}

可以缩短(在参数级别使用解构):

export default ({name}) => { // Extract name directly here
  return <h1>Hello {name}!</h1>;
}

可以缩短(去掉函数体花括号)为:

export default ({name}) => <h1>Hello {name}!</h1>;

【讨论】:

  • 这是有史以来最有帮助的答案之一,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-12
  • 1970-01-01
  • 2019-09-18
相关资源
最近更新 更多