2017-04-26 55 views
1

我有注入Mobx商店,有以下方法。組件:ReactJS的onClick參數沒有得到傳遞給父組件

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組件:

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

現在什麼Happe的ns是用正確的參數調用複選框方法(this.handleCheckbox)。然後使用正確的參數調用this.props.updateNotifications方法,但父組件(updateNotifications)中的函數被調用undefined,undefined

我在做什麼錯?

回答

1

我想你應該通過函數本身,而不是「調用函數」。刪除()在這裏。

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

的問題是,在所有的地方,你是binding的方法兩次,一次使用

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

一個接:

updateNotifications =() => 

剛剛從刪除第一個道路上的一切地方,它會工作。

只需使用:

this.updateNotifications={this.updateNotifications} 

,並通過使用arrow function定義函數:

updateNotifications =() => 
相關問題