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教程说:
如果要使它成为真正可扩展的列表,则可以创建一个项目数组,然后将它们通过ToDoList组件传递到props中,然后渲染每个项目。现在开始吧。
如何在上面的代码中传递项目数组?
数据可以通过道具传递到组件。
https://facebook.github.io/react/tutorial/tutorial.html#passing-data-through- props
在您的情况下,道具可以通过在组件内部访问this.props。
this.props
<TodoList />需要一个称为项的道具,它是一个数组。在内部,<TodoList />您可以映射该数组并返回元素。
<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> )); }