Reactjs 在React的重新组合中为withHandler定义函数
在我看的所有示例中,实际在Reactjs 在React的重新组合中为withHandler定义函数,reactjs,recompose,Reactjs,Recompose,在我看的所有示例中,实际在with handlers中调用的函数似乎是从props调用函数,但我不知道该函数是如何定义的。下面是一个来自中国的小例子 我的理解是这将创建一个带有“state”的HOC来跟踪count。我将能够通过定义的处理程序使用的操作来增加计数(例如,onClick={incrementCount}) 那么,我的问题是,setCount实际定义在哪里。。我在想象类似这样的事情 function setCount(i) { return i+1; } 因为它是从道具调用
with handlers
中调用的函数似乎是从props
调用函数,但我不知道该函数是如何定义的。下面是一个来自中国的小例子
我的理解是这将创建一个带有“state”的HOC来跟踪count
。我将能够通过定义的处理程序使用的操作来增加计数(例如,onClick={incrementCount}
)
那么,我的问题是,setCount
实际定义在哪里。。我在想象类似这样的事情
function setCount(i) {
return i+1;
}
因为它是从道具调用的,所以在使用组件时是否必须将其作为道具传入?我很困惑为什么和state
需要知道状态更新程序的名称,或者如果是这样的话,它是如何关联的
它只是为您自动定义一个函数,用您传递的任何参数替换状态参数(如果是facepalm…)找到了答案,我这里的示例比我的组件简单,但我会尽力翻译我的发现。。。虽然下面没有测试
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=“default str”,…props}){
返回(
{props.count}
);
}
someProp
只是用来显示spread操作符的用法,如果您想要一些具有默认值的道具,或者想要特别调用的道具,那么就可以使用spread操作符…cheerswithHandlers
使用curried/higher-order函数来设置来自其他HOC(高阶组件)的道具例如与state
或表单的用法
增强组件示例:
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>
);
从“重新组合”导入{compose};
从“React”导入React;
常数增强=合成(
带状态('count','setCount',0),
带处理器({
递增计数:道具=>事件=>{
//道具将包含复制道具。
道具设置计数(道具计数+1)
},
其他示例:()=>event=>{
//如果你的操控者不需要道具
},
otherIncrementCountExample:({count,setCount})=>()=>{
//您还可以排除事件
设置计数(计数+1);
}
});
导出默认IncButton=({count,incrementCount,copy})=>(
{copy}
);
用法:
import React from 'react';
import IncButton from './IncButton';
export default App = () => (
<div>
<IncButton copy="Increment Me"/>
</div>
);
从“React”导入React;
从“/IncButton”导入IncButton;
导出默认应用=()=>(
);
谢谢你的回答。值得注意的是,我在问题中提到的“函数”(setCount
)是由和state
为正在创建的var创建的设置器。
import React from 'react';
import IncButton from './IncButton';
export default App = () => (
<div>
<IncButton copy="Increment Me"/>
</div>
);