简体   繁体   中英

ReactJS onClick arguments not getting passed to parent component

I have a component with an injected Mobx store that has the following method:

 constructor(props) { super(props) this.state = { propertyChangeNotifications: true, smsNotifications: false } } updateNotifications = (type, value) => { this.props.uiStore.updateProfile(type, value) } 

I am passing this method as a prop to a child component:

 <ProfileDetails {...this.props.uiStore.profile} updateNotifications={()=> this.updateNotifications()} /> 

The child component has another method:

 constructor(props) { super(props) // Get profile data from props const { propertyChangeNotifications, smsNotifications, person: { fiscalId, residentialAddress, name, lastName, phoneNumber, type, email } } = props // Set state according to props this.state = { name: name, lastName: lastName, fiscalId: fiscalId, residentialAddress: residentialAddress, phoneNumber: phoneNumber, type: type, email: email, propertyChangeNotifications: propertyChangeNotifications, smsNotifications: smsNotifications } } handleCheckbox = (type) => { this.props.updateNotifications(type, !this.state[type]) this.setState({ [type]: !this.state[type] }) } 

That I am passing to a semantic UI checkbox component:

 <Checkbox toggle label="Notify via SMS " checked={smsNotifications} onChange={()=> this.handleCheckbox('smsNotifications')} /> 

Now what happens is that the Checkbox method ( this.handleCheckbox ) gets called with the correct argument. Then the this.props.updateNotifications method gets called with the correct arguments as well, but the function in the parent component ( updateNotifications ), gets called with undefined , undefined .

What am I doing wrong?

I think you should pass the function itself, not "invoke the function". Delete () here.

<ProfileDetails
    {...this.props.uiStore.profile}
    updateNotifications={this.updateNotifications}
/>

Issue is, at all the places you are binding the method twice, one by using

this.updateNotifications={() => this.updateNotifications()} //here you are calling the function with no parameter.

And one by:

updateNotifications = () => 

Just remove the first way from all the places, it will work.

Simply use:

this.updateNotifications={this.updateNotifications}

and define the function by using arrow function :

updateNotifications = () => 

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