简体   繁体   English

区分参数和反应事件

[英]Distinguish between arguments and react events

Two handlers (in different parts of a Reactjs application) call the same function. 两个处理程序(在Reactjs应用程序的不同部分中)调用同一函数。

One place: 一个地方:

Foo.bar({key: 'value'});

Other place: 其他地方:

<a onClick={Foo.bar}>

In the last case, unless I change it to Foo.bar.bind(null, null), the first argument for the bar-function will be the React event object. 在最后一种情况下,除非我将其更改为Foo.bar.bind(null,null),否则bar函数的第一个参数将是React事件对象。

Is there a good way to handle this, knowing in bar if it was passed an argument or just a React event? 有没有一种好的方法来处理这个问题,在bar中知道它是否被传递了一个参数或只是一个React事件? Without having to bind a null as argument everywhere that function is used. 无需在所有使用该函数的地方都将null绑定为参数。 That does not seem like a very good solution as changing the number of argument later will require to check all places using the function. 这似乎不是一个很好的解决方案,因为以后更改参数数量将需要使用该函数检查所有位置。

Checking for some key of React event objects in all functions called this way to make sure what was passed was an argument and not the React event also feel like it should not be necessary. 在所有以这种方式调用的函数中检查React事件对象的某些键,以确保传递的是参数,而不是React事件也没有必要。

I would probably have two separate functions: 我可能有两个单独的功能:

Foo.bar({key: 'value'});

And

<a onClick={Foo.barClick}>

where barClick calls Foo.bar(null) or similar. 其中barClick调用Foo.bar(null)或类似名称。

If you are compiling your code from jsx with ES6 arrow function support you can use next variant: 如果使用ES6箭头功能支持从jsx编译代码,则可以使用下一个变体:

<a onClick={() => Foo.bar({ key: 'value' })}>

or if you need event object: 或者如果您需要事件对象:

<a onClick={event => Foo.bar({ key: event.prop })}>

You can use just anonymous functions, but it looks worse: 您可以只使用匿名函数,但看起来更糟:

<a onClick={function() { Foo.bar({ key: 'value' }) }}>

Without arrow functions, anonymous functions or creation of new functions you can achieve this only by using bind method (as you already specified in question): 如果没有箭头功能,匿名功能或新功能的创建,则只能通过使用bind方法(如您已经提到的那样)来实现:

<a onClick={Foo.bar.bind(Foo, { key: 'value' })}>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM