如何用新语法编写React?

时间:2017-07-12 22:34:33

标签: reactjs ecmascript-6 jsx

基本问题。我正在尝试以新的方式重新编写我的旧React Skeleton项目,但我遇到了使其工作的问题。我做错了什么?

旧方法

var React = require('react');
var ListItem = require('./ListItem.jsx')

//Component
var ingredients = [{ "id": 1, "text": "Ham"}, { "id": 2, "text": "Cheese"}, { "id": 3, "text": "Bread"},]

//Component
var List = React.createClass({
  render: function() {
    var listItems = ingredients.map(function(item) {
      return <ListItem key = {item.id} ingredient = {item.text} />
    });
    return ( <ul>{listItems}</ul> );
  }
});

module.exports = List;

新方法

import React from 'react';
import ListItem from './ListItem.jsx';

const ingredients = [{ "id": 1, "text": "Ham"}, { "id": 2, "text": "Cheese"}, { "id": 3, "text": "Bread"}];

class List extends React.Component {

  render() {
    const listItems = ingredients.map((item) =>
      <ListItem key = {item.id} ingredient = {item.text} />
    );

    return (
      <ul>{listItems}</ul>
    );
  }
};

我是新人,如果我的错误是基本的,请原谅我。提前谢谢。

1 个答案:

答案 0 :(得分:2)

正如您在此处所介绍的那样,无状态组件不会被编写为类。相反,您更有可能将其视为functional component

import React from 'react'

import ListItem from './ListItem'

const ingredients =
  [{ "id": 1, "text": "Ham"}, { "id": 2, "text": "Cheese"}, { "id": 3, "text": "Bread"}]

const List = props =>
  <ul>{ingredients.map (item =>
    <ListItem key={item.id} ingredient={item.text} />)}</ul>

export default List

或许更有可能你会看到像ingredients这样的数据作为属性传递,而不是像你一样访问自由变量

点击下面的运行代码段,查看运行中的演示代码

&#13;
&#13;
const ingredients =
  [{ "id": 1, "text": "Ham"}, { "id": 2, "text": "Cheese"}, { "id": 3, "text": "Bread"}]

const List = props =>
  <ul>{props.ingredients.map (item =>
    <ListItem key={item.id} ingredient={item.text} />)}</ul>

const ListItem = props =>
  <li>{props.ingredient}</li>
  
ReactDOM.render(<List ingredients={ingredients} />, document.querySelector('#main'))
&#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="main"></div>
&#13;
&#13;
&#13;

当然,现在ListListItem可以更加通用。为什么仅限于使用成分?

&#13;
&#13;
const ingredients =
  [{ "id": 1, "text": "Ham"}, { "id": 2, "text": "Cheese"}, { "id": 3, "text": "Bread"}]

const List = ({items,each}) =>
  <ul>{items.map((item,key) =>
    <ListItem key={key} item={each(item)} />)}</ul>

const ListItem = ({item}) =>
  <li>{item}</li>
 
const Ingredient = ({text}) =>
  <div className="ingredient">{text}</div>
  
ReactDOM.render(<List items={ingredients} each={Ingredient} />, document.querySelector('#main'))
&#13;
.ingredient {
  font-family: monospace;
  background-color: #333;
  color: #aaa;
  padding: 0.25rem;
}
&#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="main"></div>
&#13;
&#13;
&#13;