如何在 React 组件中使用解构

how to use destructuring in react components

我在网上看了很多书,只是无法理解解构,嗯。

//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 }

不确定参数中的卷曲 {}

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>;