使用 JSX 与本机反应将数据传递给组件 Javascript
React Passing Data to Components with JSX vs Native Javascript
这应该是一个简单的。我将 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 />
时数据传不出去?
语法正确吗?看起来你需要用方括号括起来。
const contactListItemsJSX = contacts.map(contact => { return (<ContactItem contact />) });
相当于
React.createElement(ContactItem, contact);
在 JSX 中是
<ContactItem {...contact} />;
有关详细信息,请参阅 JSX Spread Attributes。
这应该是一个简单的。我将 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 />
时数据传不出去?
语法正确吗?看起来你需要用方括号括起来。
const contactListItemsJSX = contacts.map(contact => { return (<ContactItem contact />) });
相当于
React.createElement(ContactItem, contact);
在 JSX 中是
<ContactItem {...contact} />;
有关详细信息,请参阅 JSX Spread Attributes。