简体   繁体   English

如何遍历JSON数据并在React中动态创建和填充组件?

[英]How to iterate through JSON data and dynamically create and populate components in React?

I'm new to React and JSX and have created a component which displays a title and image which will serve all as a link. 我是React和JSX的新手,并创建了一个显示标题和图像的组件,所有这些都将用作链接。 I would now like to set the title and image by iterating through JSON data (currently my JSON is accessible via a locally defined variable). 我现在想通过遍历JSON数据来设置标题和图像(当前可以通过本地定义的变量访问JSON)。

I would like to know how to dynamically create and populate the components with the appropriate data. 我想知道如何使用适当的数据动态创建和填充组件。 My code currently looks like this: 我的代码当前如下所示:

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

This can be achieved by passing the JSON data into the items prop of your <RecipeList /> so that this data is used to dynamically render the component via that data. 这可以通过将JSON数据传递到<RecipeList />items <RecipeList />来实现,以便使用该数据通过该数据动态呈现组件。

Additionally, there are a few other things to update to get this to work: 此外,还有一些其他更新要使它起作用:

  1. you'll want to fix the format of your input JSON so that item keys are either wrapped with quotes, or don't have hyphens. 您将需要修复输入JSON的格式,以便项目键要么用引号引起来,要么没有连字符。

  2. ensure you're accessing data from the item in map() when rendering the list items, rather than accessing the item data from this 确保你从访问数据itemmap()从渲染列表项的时候,而不是访问的项目数据this

  3. wrap the list items that you're rendering with a "root element" at the return line of your render() method. render()方法的return行上用“根元素”包装要呈现的列表项。 A simple solution is to usually wrap the return result with a <div> , however with more recent versions of React you can use <React.Fragment> (this allows you to return multiple elements in a render() result, without adding the extra "div element" to be resulting DOM). 一个简单的解决方案是通常用<div>包装返回结果,但是在React的最新版本中,您可以使用<React.Fragment> (这允许您在render()结果中返回多个元素,而无需添加额外的“ div元素”作为结果DOM)。

Here's a working snippet: 这是一个工作片段:

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

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM