zoukankan      html  css  js  c++  java
  • [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} /> 
    ); 

    ----

  • 相关阅读:
    第十章学习笔记
    MyOD(选作,计入平时成绩)
    学习笔记第九章
    第一、二章学习笔记
    团队作业(一):团队展示
    C语言实现Linux下od -tx -tc XXX的功能
    第七、八章学习笔记
    Sort 在 Linux
    Linux C语言编程基础
    MyOD
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6908577.html
Copyright © 2011-2022 走看看