使用JSX与原生Javascript将数据传递给组件

时间:2016-01-13 23:27:03

标签: javascript reactjs ecmascript-6 react-jsx

这应该是一个简单的。我正在使用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 />时为什么没有传递数据?

2 个答案:

答案 0 :(得分:2)

相当于

React.createElement(ContactItem, contact);
JSX中的

<ContactItem {...contact} />;

有关详细信息,请参阅JSX Spread Attributes

答案 1 :(得分:-1)

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

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