2017-04-26 103 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 =() => 
相关问题