首页 > 移动平台 > 详细

[React] Pass Data To Event Handlers with Partial Function Application

时间:2017-02-02 17:36:10      阅读:262      评论:0      收藏:0      [点我收藏+]

In this lesson we’ll see how to pass an item’s id value in an event handler and get the state to reflect our change. We’ll also create a helper function that allows us to use partial function application to clean up the event handler code and make it more “functional”

 

Previous code:

const ActionBtns = ({ selectedBox, onBtnClick }) => (
    <nav className={classnames(nav)}>
        <RaisedButton
            label="Red"
            style={style}
            onClick={() => onBtnClick(red, selectedBox)}/>
        <RaisedButton
            label="Green"
            style={style}
            onClick={() => onBtnClick(green, selectedBox)}/>
    </nav>
);

 

We want to change the highlight code to partial applied function:

const ActionBtns = ({ selectedBox, onBtnClick }) => {
    const setGreenColor = partial(onBtnClick, green, selectedBox);
    const setRedColor = partial(onBtnClick, red, selectedBox);
    return (
        <nav className={classnames(nav)}>
            <RaisedButton
                label="Red"
                style={style}
                onClick={setRedColor}/>
            <RaisedButton
                label="Green"
                style={style}
                onClick={setGreenColor}/>
        </nav>
    );
};

 

lib:

export const partial = (fn, ...args) => fn.bind(null, ...args);

 

Test:

import {partial} from ../lib/util;

const add = (a, b) => a + b;
const addThree = (a,b,c) => a + b + c;

test(partial applies the first argument ahead of time, () => {
   const inc = partial(add, 1);
   const result = inc(2);
   expect(result).toBe(3);
});

test(partial applies the multiple arguments ahead of time, () => {
   const inc = partial(addThree, 1, 2);
   const result = inc(3);
   expect(result).toBe(6);
});

 

[React] Pass Data To Event Handlers with Partial Function Application

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

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