Как перебирать данные JSON и динамически создавать и заполнять компоненты в React? - PullRequest
0 голосов
/ 27 января 2019

Я новичок в React и JSX и создал компонент, который отображает заголовок и изображение, которые будут служить ссылкой. Теперь я хотел бы установить заголовок и изображение, просматривая данные JSON (в настоящее время мой JSON доступен через локально определенную переменную).

Я хотел бы знать, как динамически создавать и заполнять компоненты соответствующими данными. Мой код в настоящее время выглядит так:

<script>
        var RecipeList = React.createClass({
                const items = [
                    {
                        id: 2234567,
                        title: "Fried Chicken",
                        image-url: "https://images.media-allrecipes.com/userphotos/560x315/4577069.jpg",
                        ingredient: ["Chicken", "Flour", "Eggs", "Salt", "Pepper"]
                    },
                    {
                        id: 2234567,
                        title: "Grilled Chicken",
                        image-url: "https://images.media-allrecipes.com/userphotos/560x315/4577069.jpg",
                        ingredient: ["Chicken", "Olive oil", "Salt", "Pepper"]
                    }
                ]
                getDefaultProps: function() {
                  return {items: []}  
                },
                render: function() {
                    var listItems = this.props.items.map(function(item) {
                       return(
                            <div className="container-fluid">
                                <div className="row">
                                    <div className="recipeContainer col-sm-12 col-md-6 col-lg-4">
                                        <h3 className="recipeTitle">{this.props.title}</h3>
                                        <div className="recipeImage">
                                            <img src="{this.props.image}" />
                                        </div>
                                        <div className="recipeBtn">See recipe</div>
                                    </div>
                                </div>
                            </div>
                        );
                    });

                    return (
                        {listItems}
                    );
                 }
            });

ReactDOM.render(
                <div>
                    <IngredientList></IngredientList>
                    <RecipeList items={items}></RecipeList>
                    <RecipeSection></RecipeSection>
                </div>
                , document.getElementById("module"));
        </script>

1 Ответ

0 голосов
/ 27 января 2019

Этого можно достичь, передав данные JSON в items реквизит вашего <RecipeList />, чтобы эти данные использовались для динамического рендеринга компонента через эти данные.

Кроме того, существует несколькодругие вещи, которые нужно обновить, чтобы заставить это работать:

  1. вы захотите исправить формат входного JSON, чтобы ключи элементов либо заключались в кавычки, либо не содержали дефисы.

  2. обеспечивает доступ к данным из item в map() при визуализации элементов списка, а не к данным элементов из this

  3. оберните элементы списка, которые вы отображаете, "корневым элементом" в строке return вашего метода render().Простое решение состоит в том, чтобы обычно обернуть возвращаемый результат символом <div>, однако с более свежими версиями React вы можете использовать <React.Fragment> (это позволяет вам возвращать несколько элементов в результате render(), без добавления дополнительного "div"элемент "должен быть результатом DOM).

Вот рабочий фрагмент:

<div id="module"></div>
<script src="https://unpkg.com/react@16/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js" crossorigin></script>
<script type="text/babel">

  /*
  Use class to define component using React16
  */
  class RecipeList extends React.Component {
    
    render() {
    
      var listItems = this.props.items.map(function(item) {
        return(
          <div className="container-fluid">
            <div className="row">
              <div className="recipeContainer col-sm-12 col-md-6 col-lg-4">
                <h3 className="recipeTitle">{item.title}</h3> { /* <-- Corrected this to use item.title */ }
                <div className="recipeImage">
                  <img src={item.image} /> { /* <-- Corrected this to use item.image */ }
                </div>
              <div className="recipeBtn">See recipe</div>
            </div>
          </div>
        </div>
      );
    });
    
    /*
    When rendering multiple DOM elements as a list, you
    must wrap these with React.Fragment, or something else
    like a div
    */
    return (<React.Fragment>{listItems}</React.Fragment>);
    }
  };

  /*
  Declare items data array which will passed to the items
  prop of the <RecipeList> component
  */
  const items = [{
      'id': 2234567,
      'title': "Fried Chicken",
      'image': "https://images.media-allrecipes.com/userphotos/560x315/4577069.jpg",
      'ingredient': ['Chicken', 'Olive oil', 'Salt', 'Pepper']
  },
  {
      'id': 2234567,
      'title': "Grilled Chicken",
      'image': "https://images.media-allrecipes.com/userphotos/560x315/4577069.jpg",
      'ingredient': ['Chicken', 'Olive oil', 'Salt', 'Pepper']
  }];

  ReactDOM.render(
      <div>
        { /* Pass the items data array to the items prop */ }
        <RecipeList items={items}></RecipeList>
      </div>, 
  document.getElementById("module"));
</script>

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...