javascript - 如何在 React 中迭代 JSON 数据并动态创建和填充组件?

标签 javascript reactjs jsx

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

最佳答案

这可以通过将 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>

希望有帮助!

关于javascript - 如何在 React 中迭代 JSON 数据并动态创建和填充组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54383588/

相关文章:

javascript - Antlr4 Javascript 目标 - 访客问题和标记替代方案

javascript - location.hash 更新为链接的新哈希值,该哈希值在*点击后*被替换

javascript - 我可以跨多个组件订阅过滤后的 RTK 查询数据结果吗?

javascript - 如何将组件对象传递给 React.js 中的容器?

javascript - 我可以使用函数中声明的变量作为嵌套在该函数中的另一个函数的参数吗?

javascript - 做 CORS 时 getJSON 和 ajax 之间的 cookie 差异

JavaScript 检测互联网连接

javascript - 如何在javascript中获取文件对象的所有属性?

reactjs - 类型错误 : undefined is not iterable (cannot read property Symbol(Symbol. 迭代器))

javascript - 如何打印属性名称而不是整个 JS 对象?