[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);
});
复制代码

 

posted @   Zhentiw  阅读(279)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-02-02 [Cycle.js] Read effects from the DOM: click events
2016-02-02 [Cycle.js] Introducing run() and driver functions
2016-02-02 [Cycle.js] Customizing effects from the main function
2016-02-02 [Cycle.js] Main function and effects functions
点击右上角即可分享
微信分享提示