繁体   English   中英

ReactJS onClick参数未传递到父组件

[英]ReactJS onClick arguments not getting passed to parent component

我有一个带有注入Mobx存储的组件,该组件具有以下方法:

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

我将此方法作为对子组件的支持:

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

子组件具有另一种方法:

 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] }) } 

我正在传递给语义UI复选框组件:

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

现在发生的是,使用正确的参数调用了Checkbox方法( this.handleCheckbox )。 然后, this.props.updateNotifications使用正确的参数调用this.props.updateNotifications方法,但是使用undefinedundefined调用父组件中的函数( updateNotifications )。

我究竟做错了什么?

我认为您应该传递函数本身,而不是“调用函数”。 在此处删除()。

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

问题是,在所有将方法binding两次的地方,一个是通过使用

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

还有一个:

updateNotifications = () => 

只需从所有位置删除第一种方法,它将起作用。

只需使用:

this.updateNotifications={this.updateNotifications}

并使用arrow function定义arrow function

updateNotifications = () => 

暂无
暂无

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

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