Reputation: 292
I am using the following code:
handleOwnerMode = ownerChecked => {
this.setState(prev => ({ ownerChecked, showOwner: !prev.showOwner}))
// this.setState(prev => ({ ownerChecked: !prev.ownerChecked, showOwner: !prev.showOwner }))
}
Inside the render is
<Switch onChange={this.handleOwnerMode} checked={this.state.ownerChecked} />
OnChange
, I somehow was able to receive what was changed about ownerChecked
. Why is this the case? I didn't write onChange={this.handleOwnerMode(event.value)}
or anything like that...
Also, for setState
. I normally just use this.setState( { state: newState} )
, but now I can somehow pass in the previous state with this.setState( prev => {} )
. Is there defined overloading somewhere that lets me do this?
Thank you.
Upvotes: 0
Views: 85
Reputation: 466
React events are synthetic so that even when yo do not pass any event parameters, function takes it. Take a look at these. More information 1, More information 2.
Upvotes: 1
Reputation: 28654
OnChange, I somehow was able to receive what was changed about ownerChecked. Why is this the case? I didn't write onChange={this.handleOwnerMode(event.value)} or anything like that...
In both cases you have passed a function (callback) to "receivers". First time to Switch
Component, second time to React. Each of them can call your function/callback using any parameter they want. This is how normally callbacks are used.
Is there defined overloading somewhere that lets me do this?
Yeah probably setState
checks if you passed a function to it and behaves differently: e.g. gives you previous state and calls your function. If you pass an object to it, it doesn't do that.
Upvotes: 3