React map items

WEB前端 waitig 396℃ 百度已收录 0评论
<html>
  <head>
      <title>Document</title>
      <script src="../react.js"></script>
      <script src="../react-dom.js"></script>
      <!-- //引用资源,JSX转HTML -->
      <script src="http://cdn.bootcss.com/babel-core/5.8.38/browser.min.js"></script>
  </head>

  <body>
      <div id="reactContainer"/>

      <script type="text/babel">
        const numbers = [1, 2, 3, 4, 5]
        const listItems = numbers.map((numbers) => 
          <li>{numbers}</li>
        )
        ReactDOM.render(
          <ul>{listItems}</ul>,
          document.getElementById('reactContainer')
        )
      </script>
  </body>
</html>

better

  <script type="text/babel">
        function NumberList(props) {
          const numbers = props.numbers
          const listItems = numbers.map(num => <li key={num}>{num}</li>)
          return (
            <ul>{listItems}</ul>
          )
        }

        const numbers = [1, 2, 3, 4, 5]

        ReactDOM.render(
          <NumberList numbers={numbers} />,
          document.getElementById('reactContainer')
        )
      </script>

extract

<script type="text/babel">
        function Item(props) {
          return (
            <li>{props.num}</li>
          )
        }

        function NumberList(props) {
          const numbers = props.numbers
          const listItems = numbers.map(num => <Item key={num} num={num}/>)
          return (
            <ul>{listItems}</ul>
          )
        }

        const numbers = [1, 2, 3, 4, 5]

        ReactDOM.render(
          <NumberList numbers={numbers} />,
          document.getElementById('reactContainer')
        )
      </script>

本文由【waitig】发表在等英博客
本文固定链接:React map items
欢迎关注本站官方公众号,每日都有干货分享!
等英博客官方公众号
点赞 (0)分享 (0)