[英]Defining function for withHandler in Recompose for React
我看到的所有示例中,实际调用withHandlers
的函数似乎都是从props
调用函数,但我不知道该函数是如何定义的。 以下是人类文档中的一个小例子。
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
需要知道状态更新程序名称,或者如果是这种情况它甚至是如何相关的。
它是否只为您自动定义一个函数,它将用您传递的任何参数替换状态参数(如果是这样,则为facepalm ..)
withHandlers
采用withHandlers
/ higher阶函数来设置来自其他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>
);
找到答案,我的例子比我的组件简单,但我会尽力翻译我的发现......尽管下面没有测试过。
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
就是为了显示扩展运算符的使用,如果你想要一些具有默认值或传递的道具你想要专门召唤...欢呼
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.