如何在 React.js 中传递一组项目 [英] How to pass an array of items in React.js

查看:31
本文介绍了如何在 React.js 中传递一组项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const ListItem = React.createClass({
  render: function() {
    return <li > {
      this.props.item
    } < /li>;
  }
});

const ToDoList = React.createClass({
  render: function() {

    const todoItems = this.props.items.map(item => {
      return <ListItem item = {
        item
      } > < /ListItem>
    })

    return ( <
      ul > {
        todoItems
      } < /ul>
    );
  }
});

//creating a basic component with no data, just a render function
const MyApp = React.createClass({
  render: function() {
    return ( <
      div className = "well" >
      <
      h1 > Hello < /h1> <
      ToDoList > < /ToDoList> <
      /div>
    );
  }
});

//insert the component into the DOM
ReactDOM.render( < MyApp / > , document.getElementById('container'));



<
div id = "container" > < /div>

<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="container"></div>

ReactJs 教程说:

A ReactJs tutorial says:

如果我们想让它成为一个真正可扩展的列表,我们可以创建一个项目数组,然后通过 ToDoList 组件将它们传递给 props,然后渲染出每个项目.让我们现在就这样做.

If we want to make this a truly extensible list, we could create an array of items, then pass them into props through the ToDoList component, then render out each item. Let's do that now.

如何在上面的代码中传递项目数组?

How can I pass the array of items in the above code?

推荐答案

数据可以通过 props 传递给组件.

Data can be passed to components via props.

https://facebook.github.io/react/tutorial/tutorial.html#passing-data-through-props

在你的情况下,props 将通过 this.props 在组件内部访问.

In your case props would be accessed inside the components via this.props.

接受一个名为 items 的道具,它是一个数组.在 <TodoList/> 中,您可以映射该数组并返回元素.

<TodoList /> takes a prop called items which is an array. Inside <TodoList /> you can map through that array and return elements.

例如,在您的类的渲染方法中,您将返回带有项目道具的 TodoList:

For example in the render method of your class you would return TodoList with a prop of items:

const myItems = [{ name: 'item 1' }, { name: 'item2' }];
function MyApp() {
    return (
       <TodoList items={myItems} />
    );
}

然后在 TodoList 中映射项目

Then in TodoList you map the items

function TodoList({ items }) {
    return items.map(item => (
        <h1>{item.name}</h1>
    ));
}

这篇关于如何在 React.js 中传递一组项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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