簡體   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