简体   繁体   中英

Distinguish between arguments and react events

Two handlers (in different parts of a Reactjs application) call the same function.

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.

Is there a good way to handle this, knowing in bar if it was passed an argument or just a React event? Without having to bind a null as argument everywhere that function is used. 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.

I would probably have two separate functions:

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

And

<a onClick={Foo.barClick}>

where barClick calls Foo.bar(null) or similar.

If you are compiling your code from jsx with ES6 arrow function support you can use next variant:

<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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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