zoukankan      html  css  js  c++  java
  • [React] Pass Data To Event Handlers with Partial Function Application

    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);
    });
  • 相关阅读:
    bzoj4563: [Haoi2016]放棋子(错排+高精)
    bzoj1089 [SCOI2003]严格n元树(dp+高精)
    9.15NOIP模拟题
    洛谷 P2010 回文日期 题解
    洛谷 P1147 连续自然数和 题解
    洛谷 P1152 欢乐的跳 题解
    信息学奥赛一本通 高手训练1 统计方案数
    想学习找不到好的博客?看这里>>
    信息学奥赛一本通 高手训练1 游戏通关
    洛谷 P3398 仓鼠找sugar 题解
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6361366.html
Copyright © 2011-2022 走看看