reactjs - 如何在 React.js 中传递项目数组

标签 reactjs

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 教程说:

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.

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

最佳答案

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

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

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

<TodoList />接受一个名为 items 的 prop,它是一个数组。里面<TodoList />您可以映射该数组并返回元素。

例如,在类的 render 方法中,您将返回带有项目属性的 TodoList:

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

然后在 TodoList 中映射项目

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

关于reactjs - 如何在 React.js 中传递项目数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43948828/

相关文章:

css - 背景隐藏行边框?

javascript - 超时获取 - React Native

javascript - react-router:无法路由到子组件

javascript - 如何使用游标映射来自 Twitch API 的所有结果 - React

loops - 在渲染中调用 Object.keys().map 内的状态和类方法

node.js - ReactJS - 项目不会立即附加,仅刷新页面

reactjs - map 不是reactJS 中的函数

html - Flex-end 和 start 不垂直对齐

reactjs - {...{ key }} 与 key={key} 相同来分配 React 属性吗?

javascript - React KeyboardEvent 在 onPressEnter 后更改输入值