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

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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(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的主要内容,如果未能解决你的问题,请参考以下文章

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

[Recompose] Lock Props using Recompose -- withProps

[Recompose] Transform Props using Recompose --mapProps

[Recompose] Refactor React Render Props to Streaming Props with RxJS and Recompose

使用 recompose 和 typescript 正确键入 HigherOrderComponents

你如何从 recompose 中读取这个 curry'd 函数……我的脑痛