【问题标题】:How to iterate through JSON data and dynamically create and populate components in React?如何遍历 JSON 数据并在 React 中动态创建和填充组件?
【发布时间】:2019-06-20 08:51:47
【问题描述】:

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

【问题讨论】:

标签: javascript reactjs jsx


【解决方案1】:

这可以通过将 JSON 数据传递到 &lt;RecipeList /&gt;items 属性中来实现,以便该数据用于通过该数据动态呈现组件。

此外,还有一些其他内容需要更新以使其正常工作:

  1. 您需要修复输入 JSON 的格式,以便项目键用引号括起来,或者没有连字符。

  2. 确保在呈现列表项时访问来自 item 中的 item 的数据,而不是访问来自 this 的项目数据

  3. render() 方法的return 行中用“根元素”包装您正在呈现的列表项。一个简单的解决方案是通常用 &lt;div&gt; 包装返回结果,但是对于更新版本的 React,您可以使用 &lt;React.Fragment&gt;(这允许您在 render() 结果中返回多个元素,而无需添加额外的“div element" 成为生成的 DOM)。

这是一个有效的 sn-p:

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

希望有帮助!

【讨论】:

  • 感谢您的回复,我已经更新了代码但是仍然没有输出显示
  • @S.Miller 刚刚更新了答案和代码 sn-p 并进行了一些其他修复 - 这有帮助吗?
  • 我还不能让它显示,但我看到你的例子工作得很好。非常感谢,我真的很感激。
  • @S.Miller 刚刚再次更新了答案,提供了更多细节 - 很高兴我能提供帮助! :)
  • 是的,如果我理解你的问题,那么只需将&lt;div className="container-fluid"&gt; 从组件render() 方法中移出,并移到ReactDOM.render( .. ) 方法中,以便它包装` `
猜你喜欢
  • 2017-02-16
  • 1970-01-01
  • 1970-01-01
  • 2018-03-07
  • 2021-10-06
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多