React不渲染Li元素

时间:2016-12-19 10:19:58

标签: javascript list reactjs

尝试渲染元素列表,但浏览器会返回类似的内容。 在我看的教程中,返回" li"元素,但我不知道它返回的原因 此

<div id="root">
    <div data-reactroot="">
       <ul>
          <contact name="vasya"></contact>
          <contact name="Petya"></contact>
          <contact name="Killa"></contact>
          <contact name="Pedro"></contact>
       </ul>
     </div>
</div>

需要返回&#34; li&#34;元素

我是React的新手,所以我们不知道它为什么会发生 我的代码

var contacts = [
    {
    id: 1,
    name: "vasya",
    phone: "0989893"
    },
    {
        id: 2,
        name: "Petya",
        phone: "0986666"
    },
    {
        id: 31,
        name: "Killa",
        phone: "09833333"
    },
    {
        id: 4,
        name: "Pedro",
        phone: "09833434"
    },
]

var contact = React.createClass({
    render: function () {

        return(
            <li> {this.props.name}</li>
              );

    }
});

var ContactList = React.createClass({
    render: function() {
        return (
            <div>
                <ul>
                    {
                    contacts.map(function (el) {
                        return <contact key={el.id} name={el.name}/>;
                    })
                }
                </ul>
            </div>
        );
    }
});

ReactDOM.render(

        <ContactList />,
    document.getElementById('root')
);

2 个答案:

答案 0 :(得分:3)

您的组件必须稍后以资金开始。

在JSX中,小写标记名称被视为HTML标记。

var Contact = React.createClass({
    render: function () {
        return (<li> {this.props.name} </li>);
    }
});

然后渲染为

<Contact {...props} />

答案 1 :(得分:1)

组件名称必须为<Contact />而不是<contact />

&#13;
&#13;
var contacts = [
    { id: 1, name: "vasya", phone: "0989893" },
    { id: 2, name: "Petya", phone: "0986666" },
    { id: 31, name: "Killa", phone: "09833333" },
    { id: 4, name: "Pedro", phone: "09833434" },
]

var Contact = React.createClass({
  render: function () {
    return (
      <li> {this.props.name}</li>
    );
  }
});

var ContactList = React.createClass({
  render: function() {
    return (
      <div>
        <ul>
          {
            contacts.map(function (el) {
              return <Contact key={el.id} name={el.name}/>;
            })
          }
        </ul>
      </div>
    );
  }
});

ReactDOM.render(
  <ContactList />,
  document.getElementById('root')
);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
&#13;
&#13;
&#13;

在React网站上,有关于元素和组件之间差异的解释 - React Components, Elements, and Instances