2017-04-26 6 views
1

親コンポーネントに渡されるばかりではありません子コンポーネント:ReactJS onClickの引数は、私は次のメソッドを持って注入さMobxストアでコンポーネントを持って

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

子コンポーネントは、別の方法があります。

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

何happe:私は、意味UIのチェックボックスコンポーネントに渡しています

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

nsは、Checkboxメソッド(this.handleCheckbox)が正しい引数で呼び出されることです。次にthis.props.updateNotificationsメソッドも正しい引数で呼び出されますが、親コンポーネントの関数(updateNotifications)はundefined,undefinedで呼び出されます。

私は間違っていますか?

答えて

1

"関数を呼び出す"のではなく、関数自体を渡すべきだと思います。ここで削除()をクリックします。

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

問題は

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

そしてずつ使用して1、あなたは二回binding方法であるすべての場所で、次のとおりです。

updateNotifications =() => 

ちょうどすべての最初の方法を削除場所、それは動作します。

は単純に使用します。

this.updateNotifications={this.updateNotifications} 

arrow functionを使用して関数を定義:

updateNotifications =() => 
関連する問題