[React] Cleanly Map Over A Stateless Functional Component with a Higher Order Component
2017-05-26 15:05
337 查看
In this lesson we'll create a Higher Order Component (HOC) that takes care of the
Consider following code:
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:
----
keyproperty that React looks for when using
mapto 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] Implement a Higher Order Component with Render Props
- REACT Stateless Functional Component
- [React] Refactor a Stateful List Component to a Functional Component with React PowerPlug
- [React Intl] Use a react-intl Higher Order Component to format messages
- [React] Creating a Stateless Functional Component
- react 创建组件 (四)Stateless Functional Component
- over ,talked more with higher-up!
- Stateless functional component 和 shouldComponentUpdate
- [Recompose] Add Lifecycle Hooks to a Functional Stateless Component using Recompose
- kibana uses openStreetMap and Gaode map with higher zoom level
- React小工程——map方法 花店(getInitialState,componentWillMount,render)
- React学习笔记_无状态组件(Stateless Component) 与高阶组件
- React高级指南(十一)【Higher Order Components】
- [React] Validate Custom React Component Props with PropTypes
- Cannot evaluate module react-native-baidu-map : Configuration with name 'default' not found.
- [React] Style a React component with styled-components
- [React] Stop Memory Leaks with componentWillUnmount Lifecycle Method in React
- [React & Debug] Quick way to debug Stateless component
- [React] displayName for stateless component
- [React] Create component variations in React with styled-components and "extend"