Functional React Component with an argument in curly braces

蓝咒 提交于 2021-02-04 11:15:12

问题


I recently came across this piece of code on a website

const List = ({ items }) => (
  <ul className="list">
    {items.map(item => <ListItem item={item} />)}
  </ul>
);

Why have they wrapped the items in curly braces and is it a prop


回答1:


This is called a "destructuring". Actually, you're passing an object as an argument to the function, but the destructuring uses only the named properties of the object.

const destructuring = ({ used }) => console.log(used);
    
const properties = {
  unused: 1,
  used: 2,
};

destructuring(properties); // 2

You can even use it for creating variables.

const properties = {
  name: 'John Doe',
  age: 21,
};

const { name, age } = properties;

console.log(name, age); // John Doe 21



回答2:


I'm a newbie to React, but I think yes, items is a prop, and passing {items} as an argument destructures the props object, and thus the function uses only the prop items, in order to simplify the code. This way you can use items in the functional component, instead of props.items. For example, I tested a similar situation in the following code. Using destructuring looks like this:

const ListItem = ({content}) => (
  <li>{content}</li>
);
...
<ListItem key={index} content={content} />

Whereas if you used props it would look like this:

const ListItem = (props) => (
  <li>{props.content}</li>
);
...
<ListItem key={index} content={content} />

So for your example, using props would look like this:

const List = (props) => (
  <ul className="list">
    {props.items.map(item => <ListItem item={item} />)}
  </ul>
);

Meanwhile, destructuring allows you to simplify to items, rather than props.items which is what was being done in your original code:

const List = ({ items }) => (
  <ul className="list">
    {items.map(item => <ListItem item={item} />)}
  </ul>
);

Cheers! --Omar



来源:https://stackoverflow.com/questions/41460886/functional-react-component-with-an-argument-in-curly-braces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!