首页 > 其他 > 详细

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

时间:2017-05-14 09:26:53      阅读:272      评论:0      收藏:0      [点我收藏+]

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(show, toggleShow, false)(
    ({ status, show, toggleShow }) =>
        (<span onClick={() => toggleShow((val) => !val)}>
            {status}
            {show && <StatusList/>}
        </span>)
);

withState, we create a variable ‘show‘ and a function ‘toggleShow‘, the default value for ‘show‘ is false. Now the variable and function are injected into our stateless component as props.

The function ‘toggleShow‘ can just take a value as arguement or it can also take function as an arguement.

take as function:

onClick={() => toggleShow((val) => !val)}

take as value:

onClick={() => toggleShow(!show)}

 

withHandlers & compose:

To make withState more reuseable, we can use ‘withHandler‘ & ‘compose‘ to create an HoC.

const withToggle = compose(
    withState(toggleState, toggleShow, false),
    withHandlers({
        toggle: ({toggleShow}) => (e) => toggleShow((val) => !val),
        show: ({toggleShow}) => (e) => toggleShow(true),
        hide: ({toggleShow}) => (e) => toggleShow(false)
                 })
);

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>
));

 

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

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

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