我查看的所有示例中,在 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 ..)
最佳答案
withHandlers
采用柯里化/高阶函数来设置来自其他 HOC(高阶组件)的 Prop ,例如 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>
);