[Recompose] Add Lifecycle Hooks to a Functional Stateless Component using Recompose

Learn how to use the ‘lifecycle‘ higher-order component to conveniently use hooks without using a class component.

import React from ‘react‘;
import { withReducer, withHandlers, compose, lifecycle } from ‘recompose‘;

// Mock Configuration
function fetchConfiguration() {
    return new Promise((resolve) => {
        setTimeout(() => resolve({
                                     showStatus: true,
                                     canDeleteUsers: true
                                 }), 300);
    });
}
const withConfig = lifecycle({
                                 getInitialState(){
                                     return { config: {} };
                                 },
                                 componentDidMount() {
                                     fetchConfiguration()
                                         .then((config) => {
                                             this.setState({ config })
                                         })
                                 }
                             })

const UserStyle = {
    position: ‘relative‘,
    background: ‘lightblue‘,
    display: ‘inline-block‘,
    padding: ‘10px‘,
    cursor: ‘pointer‘,
    marginTop: ‘50px‘
};

const StatusListStyle = {
    background: ‘#eee‘,
    padding: ‘5px‘,
    margin: ‘5px 0‘
};

const TooltipStyle = {
    fontSize: ‘10px‘,
    position: ‘absolute‘,
    top: ‘-10px‘,
    width: ‘80px‘,
    background: ‘#666‘,
    color: ‘white‘,
    textAlign: ‘center‘
};

const StatusList = () =>
    <div style={StatusListStyle}>
        <div>pending</div>
        <div>inactive</div>
        <div>active</div>
    </div>;

const withToggle = compose(
    withReducer(‘toggleState‘, ‘dispatch‘, (state = false, action) => {
        switch( action.type ) {
            case ‘SHOW‘:
                return true;
            case ‘HIDE‘:
                return false;
            case ‘TOGGLE‘:
                return !state;
            default:
                return state;
        }
    }, false),
    withHandlers({
                     toggle: ({ dispatch }) => (e) => dispatch({ type: ‘TOGGLE‘ }),
                     show: ({ dispatch }) => (e) => dispatch({ type: ‘SHOW‘ }),
                     hide: ({ dispatch }) => (e) => dispatch({ type: ‘HIDE‘ })
                 })
);

const Statue = withToggle(
    ({ status, toggle, toggleState }) =>
        (<span onClick={() => toggle(!toggleState)}>
            {status}
            {toggleState && <StatusList/>}
        </span>)
);

const Tooltip = withToggle(({ show, hide, toggleState, text, children }) => (
    <span>
        <span>
            {toggleState && <div
                style={TooltipStyle}>
                { text }
            </div>}
            <span
                onMouseOver={show}
                onMouseOut={hide}
            >
                { children }
            </span>
        </span>
    </span>
));

const User3 = withConfig(({ status, name, config }) => (
    <div style={UserStyle}>
        <Tooltip text="Cool Dude!">{name}</Tooltip>-
        {config.showStatus && <Statue status={status}/>}
        {config.canDeleteUsers && <button>X</button>  }
    </div>
));

export default User3;
时间: 2024-10-23 14:19:02

[Recompose] Add Lifecycle Hooks to a Functional Stateless Component using Recompose的相关文章

[Recompose] Add Local State to a Functional Stateless Component using Recompose

Learn how to use the 'withState' and 'withHandlers' higher order components to easily add local state to—and create a reusable local state pattern for—your functional stateless components. No need for classes! withState: const Statue = withState('sho

[Recompose] Add Local State with Redux-like Reducers using Recompose

Learn how to use the 'withReducer' higher order component using the alternative reducer form. If you like using reducers in redux, you’ll be able to reuse that same technique but for local state. import React from 'react'; import {withReducer, withHa

5月面试题总结

HTML Doctype作用?标准模式与兼容模式各有什么区别? (1).<!DOCTYPE>声明位于HTML文档中的第一行,处于 <html> 标签之前.告知浏览器的解析器用什么文档标准解析这个文档.DOCTYPE不存在或格式不正确会导致文档以兼容模式呈现. (2).标准模式的排版 和JS运作模式都是以该浏览器支持的最高标准运行.在兼容模式中,页面以宽松的向后兼容的方式显示,模拟老式浏览器的行为以防止站点无法工作. HTML5 为什么只需要写 <!DOCTYPE HTML&g

[React] Creating a Stateless Functional Component

Most of the components that you write will be stateless, meaning that they take in props and return what you want to be displayed. In React 0.14, a simpler syntax for writing these kinds of components was introduced, and we began calling these compon

[MST] Create an Entry Form to Add Models to the State Tree

It is time to add new entries to the wishlist. We will achieve this by reusing forms and models we've built so far. In this lesson you will learn: MST is not limited to a single state tree. Every model can form a tree on its own Appending model insta

[Vue @Component] Pass Props to Vue Functional Templates

Functional templates allow you to create components consisting of only the template tag and exposing the props passed into the template with the props object off of the template context. This approach allows you to build simple configurable templates

Angular2版本更新

2.0.0-beta.0 somnambulant-inauguration (2015-12-15) Enjoy! 2.0.0-alpha.55 (2015-12-15) Bug Fixes router: export ROUTER_LINK_DSL_PROVIDER and hide MockPopStateEvent (fc75220) Features core: enable dev mode by default (3dca9d5) BREAKING CHANGES Before

Android application testing with the Android test framework

目录(?)[-] Android automated testing 1 How to test Android applications Tip 2 Unit tests vs functional tests 3 JUnit 3 4 Running tests on a server without display Test hooks into the Android framework 1 Instrumentation 2 How the Android system executes

Vue.js:轻量高效的前端组件化方案(转载)

摘要:Vue.js通过简洁的API提供高效的数据绑定和灵活的组件系统.在前端纷繁复杂的生态中,Vue.js有幸受到一定程度的关注,目前在GitHub上已经有5000+的star.本文将从各方面对Vue.js做一个深入的介绍. Vue.js 是我在2014年2月开源的一个前端开发库,通过简洁的 API 提供高效的数据绑定和灵活的组件系统.在前端纷繁复杂的生态中,Vue.js有幸受到一定程度的关注,目前在 GitHub上已经有5000+的star.本文将从各方面对Vue.js做一个深入的介绍. 开发