React - JSX语法问题,以及如何在换行符上迭代地图和显示项目 [英] React - JSX syntax issue, and how to iterate with map and display items on newlines

查看:109
本文介绍了React - JSX语法问题,以及如何在换行符上迭代地图和显示项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是React noob并制作待办事项列表样式食谱列表应用。我有一个功能组件,Item.js,我正在使用JSX和map函数迭代每个配方项并显示它们。我希望每个食谱项目都出现在一个新行上,但是当我使用.map迭代它们时,React将整个食谱项目列表放入一个p标签而不是每个项目的一个p标签。

I'm a React noob and making a ToDo list style Recipe List app. I have a functional component, Item.js, and I am using JSX and the map function to iterate through each recipe item and display them. I want each recipe item to appear on a new line, but when I use .map to iterate through them React puts the entire list of recipe items into one p tag instead of one p tag for each item.

如何迭代配方项目并将它们显示在不同的行上?即使我尝试将它们显示为无序列表,React也希望将每个项目放在一个li标签中。

How can I iterate through the recipe items and display them on separate lines? Even if I try to display them as an unordered list React wants to throw each item in one li tag.

这是我的代码:

import React from 'react';
import Button from 'react-bootstrap/lib/Button';


const Item = (props) => (
  <div>
    <div className="Recipe-Item-Container" key={props.text}>

        {props.items.map((item, index) => 
        <div className="Recipe-Item" key={index}>

            <h3>{item}</h3>

            <p>{props.ingredients[index]}</p>

          <div className="buttons-container">
            <Button className="edit-button" onClick={() => props.edit(item, index)}>Edit</Button>
            <Button className="delete-button" onClick={() => props.delete(item, index)}>Delete</Button>
          </div>

        </div>
      )}
    </div>
  </div>
)


export default Item;

同样在 {props.items.map((item,index) => 如果我在=>之后添加大括号,我会收到错误。我安装了React / JSX linter并且没有捕获任何内容。问题是什么?

Also on the {props.items.map((item, index) => line if I add a curly brace after the => I get an error. I have a React/JSX linter installed and it isn't catching anything. What's the issue?

我知道这可能是一个noob错误,但JSX在这里抛出一个循环。

I know this is probably a noob error but JSX is throwing me for a loop here.

推荐答案

这是工作版本。

class App extends React.Component {
  state = {
    items: [ "Pumpkin Pie", "Spaghetti", "Onion Pie" ],
    ingredients: [
      [ "Pumpkin Puree", "Sweetened Condensed Milk", "Eggs", "Pumpkin Pie Spice", "Pie Crust" ],
      [ "Noodles", "Tomatoe", "Sauce", "Meatballs" ],
      [ "Onion", "Pie Crust" ],
    ],
  }

  render() {
    return (
      <div className="box">
        <Item items={this.state.items} ingredients={this.state.ingredients} />
      </div>
    );
  }
}

const Item = props => (
  <div>
    <div className="Recipe-Item-Container" key={props.text}>

      {props.items.map( ( item, index ) => (
        <div className="Recipe-Item" key={item}>

          <h3>{item}</h3>
          <ul>
            {
              props.ingredients[ index ].map( ingredient =>
                <li key={ingredient}>{ingredient}</li> )
            }
          </ul>


          <div className="buttons-container">
            <button className="edit-button" onClick={() => props.edit( item, index )}>Edit</button>
            <button className="delete-button" onClick={() => props.delete( item, index )}>Delete</button>
          </div>

        </div>
      ) )}
    </div>
  </div>
);

ReactDOM.render(<App />, document.getElementById("root"));

<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>

但如果我是你,我会改变我的状态。类似的东西:

But if I were you I would change my state shape. Something like that:

class App extends React.Component {
  state = {
    items: [
      {
        name: "Pumpkin Pie",
        ingredients: [
          "Pumpkin Puree",
          "Sweetened Condensed Milk",
          "Eggs",
          "Pumpkin Pie Spice",
          "Pie Crust"
        ]
      },
      {
        name: "Spaghetti",
        ingredients: ["Noodles", "Tomatoe", "Sauce", "Meatballs"]
      },
      {
        name: "Onion Pie",
        ingredients: ["Onion", "Pie Crust"]
      }
    ]
  };

  removeItem = item => {
    const newItems = this.state.items.filter(el => el.name !== item.name);
    this.setState({ items: newItems });
  };

  editItem = item => alert(`${item.name} will be edited`);

  renderItems = () =>
    this.state.items.map(item => (
      <Item
        key={item.name}
        item={item}
        removeItem={this.removeItem}
        editItem={this.editItem}
      />
    ));

  render() {
    return <div className="box">{this.renderItems()}</div>;
  }
}

const Item = props => {
  const { item, removeItem, editItem } = props;
  const handleRemove = () => removeItem(item);
  const handleEdit = () => editItem(item);

  return (
    <div>
      <div className="Recipe-Item-Container" key={props.text}>
        <div className="Recipe-Item">
          <h3>{item.name}</h3>
          <ul>
            {item.ingredients.map(ingredient => (
              <li key={ingredient}>{ingredient}</li>
            ))}
          </ul>
          <div className="buttons-container">
            <button className="edit-button" onClick={handleEdit}>
              Edit
            </button>
            <button className="delete-button" onClick={handleRemove}>
              Delete
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));

<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>

更改


  • 状态形状:我们不是保留两个数组,而是每个项目保留一个对象。此对象具有名称成分属性。也许在将来,它可能有一个唯一的 id ?对象是灵活的。

  • 我们不是将所有项目传递给 Item 组件,而是映射父组件中的项目并传递只有一个项目到 Item 组件。

  • 我们仍然在父级中定义了处理函数。但是,我们没有使用箭头函数直接在按钮的回调中使用它们。因此,它们不会在每个渲染中重新创建。此外,我们不必使用索引将项目传递回父项。我们有项目道具本身!您可以看到我们如何处理删除功能:使用 .filter 您可以将相同的功能应用于其他功能。 .map .filter Object.assign 或点差语法都是很好的工具。只是,避免直接改变你的状态。

  • State shape: Instead of holding two arrays, we are keeping an object per item. This object has a name and ingredients property. Maybe in the future, it may have a unique id? Objects are flexible.
  • Instead of passing all the items to an Item component, we are mapping the items in the parent component and pass just one item to the Item component.
  • We still have handler functions defined in the parent. But, we are not using them directly in the button's callback with an arrow function. So, they are not recreated in every render. Also, we don't have to use an index to pass the items back to the parent. We have the item prop itself! You can see how we handle the remove functionality: with .filter You can apply the same functionality to other functions. .map, .filter, Object.assign or spread syntax are all good tools. Just, avoid mutating your state directly.

这篇关于React - JSX语法问题,以及如何在换行符上迭代地图和显示项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆