React使用JSX和Native Javascript向组件传递数据

React Passing Data to Components with JSX vs Native Javascript

本文关键字:组件 数据 Javascript 使用 JSX Native React      更新时间:2023-09-26

这应该是一个简单的例子。我正在使用JSX和ES6以及Babel来转换我的JSX和ES6,这些方面肯定是有效的。然而,当我试图通过JSX风格的调用将数据传递给ContactItem组件时,遇到了一个绊脚石。请参阅下面的简单示例。。。

const contacts = [
    {key: 1, name: "Bob"},
    {key: 2, name:"Dude"}
  ]
class ContactItem extends React.Component {
   ...
}
// the following Javascript call works to loop through each contact and pass the data to ContactItem 
const contactListItems = contacts
  .map(contact => { return React.createElement(ContactItem, contact); });
// While using JSX, the contact data is not flowing through to ContactItem.
const contactListItemsJSX = contacts
  .map(contact => { return <ContactItem contact /> });

为什么在使用<ContactItem contact />时没有传递数据?

的等价物

React.createElement(ContactItem, contact);

在JSX中是

<ContactItem {...contact} />;

有关详细信息,请参见JSX排列属性。

语法正确吗?看起来你需要用括号括起来。

const contactListItemsJSX = contacts.map(contact => { return (<ContactItem contact />) });