2017-05-25 89 views
1

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

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; 
} 

由于它是从所谓的道具,使用组件当你做,你必须在把它作为道具?我很困惑,为什么withState需要知道状态更新者的名字,或者如果是这样的话,甚至是相关的。

是否只定义为您自动功能,它将取代与任何参数传递给它的状态参数(捂脸如果是这样..)

回答

1

withHandlers需要一个curried/higher order函数来设置来自其他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> 
); 
+0

感谢您的回答。值得注意的是,我在问题('setCount')中提到的“函数”是由'withState'为创建的var创建的setter。 –

0

找到了答案,我在这里的例子是比我的部件简单,但我会尽我所能翻译我的发现...虽然这未在下面进行测试。

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是只是为了显示使用传播经营者,如果你想要一些道具有默认或获得通过您要特别调用...干杯