【问题标题】:Defining function for withHandler in Recompose for React在 Recompose for React 中为 withHandler 定义函数
【发布时间】:2017-10-26 15:49:09
【问题描述】:

我看的所有示例,withHandlers 中实际调用的函数似乎调用了props 中的函数,但我不知道该函数是如何定义的。这是来自docs for humans 的一个小例子。

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

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

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

function setCount(i) {
    return i+1;
}

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

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

【问题讨论】:

    标签: reactjs recompose


    【解决方案1】:

    withHandlers 采用柯里化/高阶函数来设置来自其他 HOC(高阶组件)的道具,例如 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>
    );
    

    用法:

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

    【讨论】:

    • 感谢您的回答。值得注意的是,我在问题 (setCount) 中所指的“函数”是 withState 为正在创建的 var 创建的 setter。
    【解决方案2】:

    找到答案了,我这里的例子比我的组件简单,但我会尽力翻译我的发现......虽然下面没有测试。

    compose(
      withState('count', 'setCount', 0),
      withHandlers({
        incrementCount: props => event => {
          props.setCount(props.count + 1)
        }
      })
    

    (facepalm),正如我在我的问题中所怀疑的那样。 withHandlers 只是自动为您定义一个函数,它将用您传递的任何参数替换状态参数。它不是一个智能功能,虽然很有用。它将接受您提供的任何参数,并使用该参数更新您的 HOC 状态。你会这样使用它...

    function ComponentToEnhance({someProp="default str", ...props}) {
      return (
        <div>
          <h1>{props.count}</h1>
          <button onClick={props.setCount}/>
        </div>
      );
    }
    

    someProp 只是用来展示扩展运算符的使用,如果你想要一些具有默认值或传入的道具,你想特别调出...干杯

    【讨论】:

      猜你喜欢
      • 2018-07-29
      • 2019-01-10
      • 2018-03-13
      • 2018-05-21
      • 2017-08-09
      • 1970-01-01
      • 2019-02-21
      • 2021-07-27
      • 2018-06-10
      相关资源
      最近更新 更多