在 Recompose for React 中定义 withHandler 函数

Nic*_*ady 5 reactjs recompose

我查看的所有示例中,实际调用的函数withHandlers似乎都是从 调用函数props,但我不知道该函数是如何定义的。这是人类文档中的一个小例子。

compose(
  withState('count', 'setCount', 0),
  withHandlers({
    incrementCount: props => event => {
      event.preventDefault()
      props.setCount(props.count + 1)
    }
  })
)(ComponentToEnhance)
Run Code Online (Sandbox Code Playgroud)

我的理解是,这将创建一个带有“状态”的 HOC 来跟踪count。我将能够通过使用定义的处理程序的操作来增加计数(例如onClick={incrementCount})。

那么我的问题是,setCount实际定义在哪里..我正在想象类似的东西

function setCount(i) {
    return i+1;
}
Run Code Online (Sandbox Code Playgroud)

既然它是从 props 调用的,那么在使用组件时是否必须将其作为 props 传入?我很困惑为什么withState需要知道状态更新程序名称,或者如果是这种情况,它是如何相关的。

它是否只是自动为您定义一个函数,该函数将用您传递的任何参数替换状态参数(如果是的话,捂脸......)

Per*_*ive 3

withHandlers采用柯里化/高阶函数来设置其他 HOC(高阶组件)的 props,例如withSate或形成其用法。

增强组件示例:

import { compose } from 'recompose';
import React from 'react';

const enhance = compose(
  withState('count', 'setCount', 0),
  withHandlers({
    incrementCount: props => event => {
      // props would contain copy prop. 
      props.setCount(props.count + 1)
    },
    otherExample: () => event => {
      // If you didn't need props in your handler
    },
    otherIncrementCountExample: ({ count, setCount }) => () => {
      // you can exclude event also
      setCount(count + 1);
    }
  });

export default IncButton = ({ count, incrementCount, copy }) => (
  <div>
   <button onClick={incrementCount}> {copy} </button>
  </div>
);
Run Code Online (Sandbox Code Playgroud)

用法:

import React from 'react';
import IncButton from './IncButton';
export default App = () => (
  <div>
    <IncButton copy="Increment Me"/>
  </div>
);
Run Code Online (Sandbox Code Playgroud)