'React - ES6 way' of binding click handlers with parameters

后端 未结 5 2093
暗喜
暗喜 2021-02-09 12:52

I\'ve read a bunch of articles about the use of () => {} syntax, binding in the constructor, binding in the props etc.. but from what I understand, binding

5条回答
  •  我寻月下人不归
    2021-02-09 13:06

    Syntactically, I much prefer arrow functions to binding (especially since only arrow functions facilitate passing extra arguments to event handlers). Understanding the performance penalty associated with arrow functions, I created a utility function that accepts arrow function definitions which will be cached for the lifetime of a component:

    utils.js

    export function createLambdaCache() {
      const result = {};
      return (key, lambda) => {
        if (!(key in result)) {
          result[key] = lambda;
        }
        return result[key];
      };
    }
    

    component.js

    class MyComponent extends React.Component {
      render() {
        return (
          ...  
          // below 'btnEvent' string is used as a key to cache the event reference for subsequent renders
          

    typescript version of above createLambdaCache:

    type evtHandler = (evt: E) => void;
    export function createLambdaCache() {
      const result: {[key in keyof T]: evtHandler} = {} as any;
      return (key: keyof T, lambda: evtHandler) => {
        if (!(key in result)) {
          result[key] = lambda;
        }
        return >result[key];
      };
    }
    

提交回复
热议问题