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

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[React] Cleanly Map Over A Stateless Functional Component with a Higher Order Component相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

How to Iterate Over a Map in Java?

解决git did not exit cleanly (exit code 128)

解决git did not exit cleanly (exit code 128)

在普通键的情况下使用map over unordered_map有什么好处吗?

在 Javascript 中使用 Map over Object 有啥缺点吗?

为啥 map over 一个 iterable 返回一个一次性的 iterable?