JSX道具不应该使用箭头函数



我有两个组件,一个传递一些函数作为道具给另一个,我不确定什么是正确的方法来做到这一点,而不必收到eslint错误:

代码:

<Parent>
const doSmthHandler = useCallback((id: number)=> {
//do some stuff 
},[])
<ComponentB>
doSmth={()=>doSmthHandler(id)} // Here I get eslint warning: JSX props should not use arrow functions eslint warning
</ComponentB>
</Parent>

组件B接收doSmthprop作为功能,有一个按钮,如:

<Button onPress={doSmth}>Do stuff</Button>

我想知道我如何将一些参数传递给作为cb prop传递给另一个组件的函数,我不会得到eslint错误!

代码的问题是您直接将回调作为属性传递。您可以在将其传递给组件之前使用useCallback将其声明为包装器,如下所示:

const doSmthHandlerWrapper = useCallback(
() => doSmthHandler(id),
[id]
)
<ComponentB>
doSmth={doSmthHandlerWrapper}
</ComponentB>

最新更新