首页 > 其他 > 详细

[React] Cleanly Map Over A Stateless Functional Component with a Higher Order Component

时间:2017-05-26 15:44:24      阅读:358      评论:0      收藏:0      [点我收藏+]

In this lesson we‘ll create a Higher Order Component (HOC) that takes care of the key property that React looks for when using map to create elements from a list. This HOC will allow us to wrap any component and it will take care of placing the keyprop on the component for us based on the property name that we specify.

 

Consider following code:

import React from ‘react‘;
import { render } from ‘react-dom‘;

const todos = [
  { id: 1, name: ‘Create the initial state‘, isComplete: true },
  { id: 2, name: ‘Map over data‘, isComplete: true },
  { id: 3, name: ‘Refactor‘, isComplete: true },
  { id: 4, name: ‘Use HOC to remove warning‘, isComplete: false },
];

const TodoItem = (todo) => (
  <li
    style={{
      textDecoration: todo.isComplete ? ‘line-through‘ : ‘‘,
    }}
  >
    {todo.name} 
  </li>
);

const App = (props) => (
  <div>
    <ul>
      {props.todos.map(todo => <TodoItem key={todo.id} {...todo} />)}
    </ul>
  </div>
);

render(<App todos={todos}/>, document.getElementById(‘root‘));

When we trying to render <TodoItem>, we use map function, just because we have to add ‘key‘ attr to each TodoItem. We can improve this by using HoC. A HoC is just a function which takes component as arguement and return a function which render the component:

const withKeyFromProps = (Comp, propName) => (props) => (
  <Comp key={props[propName]} {...props} /> 
); 

 

----

[React] Cleanly Map Over A Stateless Functional Component with a Higher Order Component

原文:http://www.cnblogs.com/Answer1215/p/6908577.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!