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

本文介绍了一种通过创建偏应用函数来简化React组件中事件处理器的方法,这不仅使代码更简洁,还增强了其功能性。文章展示了如何将颜色设置逻辑抽象成偏应用函数,并通过测试案例验证了该方法的有效性。

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

 

转载于:https://www.cnblogs.com/Answer1215/p/6361366.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值