[React] Pass Data To Event Handlers with Partial Function Application
React to with Data Function application Event pass
2023-09-14 09:00:52 时间
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报错之Expected `onClick` listener to be a function
- react-navigation重复点击多次跳转的解决方案
- react父子组件传值
- react项目的@路径配置
- React Error: Failed at the xxx@0.1.0 start script 'react-scripts start'.
- React:不要动,否则你会被炒鱿鱼
- 一天梳理完react面试高频题
- react源码分析:深度理解React.Context_2023-02-28
- react hook 源码解读
- react的源码架构
- react中的useState源码分析
- React源码学习入门(十一)React组件更新流程详解
- React源码学习入门(十二)DOM组件更新流程与Diff算法
- react项目登录验证功能
- To add browser notifications to an online customer support live chat service system - gofly - self h
- react源码解析18事件系统4
- react的jsx和React.createElement是什么关系?面试常问5
- react源码分析:深度理解React.Context_2023-02-07
- Htmx意外走红,我们从React“退回去”后:代码行数减少 67%,JS 依赖项从 255 下降到 9
- 探索React框架中MySQL数据库的应用(react mssql)