【问题标题】:React Passing Data to Components with JSX vs Native JavascriptReact 使用 JSX 与原生 Javascript 将数据传递给组件
【发布时间】:2016-01-13 23:27:02
【问题描述】:

这应该是一个简单的。我正在使用带有 Babel 的 JSX 和 ES6 来转换我的 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 /> });

为什么使用&lt;ContactItem contact /&gt;时数据不传?

【问题讨论】:

  • "为什么使用时数据没有传过来?" 因为&lt;ContactItem contact /&gt;表示ContactItem传的是boolean i> 道具contact.

标签: javascript reactjs ecmascript-6 react-jsx


【解决方案1】:

相当于

React.createElement(ContactItem, contact);

在 JSX 中是

<ContactItem {...contact} />;

更多信息请参见JSX Spread Attributes

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      • 2021-01-05
      • 2022-07-07
      • 2019-03-03
      • 2015-01-28
      • 2020-06-01
      相关资源
      最近更新 更多