[英]how to use destructuring in react components
I have done lots of reading online and just cant get destructuring into my head, well sort of. 我在网上做了很多阅读,只是无法破坏我的头脑。
//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'
})
I've written this and this makes sense but one thing I dont get is the following in react. 我已经写了这个,这很有意义,但是我没有得到的一件事是反应。
if you do this: 如果您这样做:
export default ({ name }) => <h1>Hello {name}!</h1>;
<Hello name="CodeSandbox" />
why cant i do this: 我为什么不能这样做:
export default ( name ) => <h1>Hello {name}!</h1>;
removing the {}
in the function parameter? 删除功能参数中的
{}
?
if someone sees what im doing wrong please can they explain this? 如果有人看到我做错了什么,请他们能解释一下吗?
im used to functions like so: 我习惯于这样的功能:
functionA (a) => { // do something with the parameter a }
not sure about the curlys {}
inside the parameters 不确定参数中的卷发
{}
export default (name) => <h1>Hello {name}!</h1>;
won't work because for any component, there is only one argument which is props
将不起作用,因为对于任何组件,只有一个参数是
props
So in its longest form you could write 因此,以最长的形式,您可以编写
export default (props) => {
return <h1>Hello {props.name}!</h1>;
}
which can be shortened (using destructuring) as: 可以缩短(使用解构)为:
export default (props) => {
const {name} = props; // Extract name from props using destructuring
return <h1>Hello {name}!</h1>;
}
which can be shortened (using destructuring at parameter level) as: 可以将其缩短为(使用参数级别的解构):
export default ({name}) => { // Extract name directly here
return <h1>Hello {name}!</h1>;
}
which can be shortened (removing the function body curly braces) as: 可以将其缩短为(删除功能主体花括号):
export default ({name}) => <h1>Hello {name}!</h1>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.